LLVM  10.0.0
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"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #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"
39 #include "llvm/CodeGen/Analysis.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/KnownBits.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
94  "amdgpu-disable-loop-alignment",
95  cl::desc("Do not align and prefetch loops"),
96  cl::init(false));
97 
98 static bool hasFP32Denormals(const MachineFunction &MF) {
100  return Info->getMode().FP32Denormals;
101 }
102 
103 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
105  return Info->getMode().FP64FP16Denormals;
106 }
107 
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109  unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110  for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111  if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112  return AMDGPU::SGPR0 + Reg;
113  }
114  }
115  llvm_unreachable("Cannot allocate sgpr");
116 }
117 
119  const GCNSubtarget &STI)
120  : AMDGPUTargetLowering(TM, STI),
121  Subtarget(&STI) {
122  addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
123  addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 
125  addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
126  addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 
128  addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
129  addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
130  addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 
132  addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
133  addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
134 
135  addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
136  addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
137 
138  addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
139  addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
140 
141  addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
142  addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
143 
144  addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
145  addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147  addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
148  addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
149 
150  if (Subtarget->has16BitInsts()) {
151  addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
152  addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
153 
154  // Unless there are also VOP3P operations, not operations are really legal.
155  addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
156  addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
157  addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
158  addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
159  }
160 
161  if (Subtarget->hasMAIInsts()) {
162  addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
163  addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
164  }
165 
167 
168  // The boolean content concept here is too inflexible. Compares only ever
169  // really produce a 1-bit result. Any copy/extend from these will turn into a
170  // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
171  // it's what most targets use.
174 
175  // We need to custom lower vector stores from local memory
184 
193 
205 
208 
213 
219 
224 
227 
236 
243 
246 
249 
253 
254 #if 0
257 #endif
258 
259  // We only support LOAD/STORE and vector manipulation ops for vectors
260  // with > 4 elements.
264  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265  switch (Op) {
266  case ISD::LOAD:
267  case ISD::STORE:
268  case ISD::BUILD_VECTOR:
269  case ISD::BITCAST:
275  break;
276  case ISD::CONCAT_VECTORS:
278  break;
279  default:
281  break;
282  }
283  }
284  }
285 
287 
288  // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289  // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291  // Most operations are naturally 32-bit vector operations. We only support
292  // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293  for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
296 
299 
302 
305  }
306 
311 
314 
315  // Avoid stack access for these.
316  // TODO: Generalize to more vector types.
321 
327 
331 
336 
337  // Deal with vec3 vector operations when widened to vec4.
342 
343  // Deal with vec5 vector operations when widened to vec8.
348 
349  // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350  // and output demarshalling
353 
354  // We can't return success/failure, only the old value,
355  // let LLVM add the comparison
358 
359  if (Subtarget->hasFlatAddressSpace()) {
362  }
363 
366 
367  // On SI this is s_memtime and s_memrealtime on VI.
371 
372  if (Subtarget->has16BitInsts()) {
377  }
378 
379  // v_mad_f32 does not support denormals. We report it as unconditionally
380  // legal, and the context where it is formed will disallow it when fp32
381  // denormals are enabled.
383 
384  if (!Subtarget->hasBFI()) {
385  // fcopysign can be done in a single instruction with BFI.
388  }
389 
390  if (!Subtarget->hasBCNT(32))
392 
393  if (!Subtarget->hasBCNT(64))
395 
396  if (Subtarget->hasFFBH())
398 
399  if (Subtarget->hasFFBL())
401 
402  // We only really have 32-bit BFE instructions (and 16-bit on VI).
403  //
404  // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
405  // effort to match them now. We want this to be false for i64 cases when the
406  // extraction isn't restricted to the upper or lower half. Ideally we would
407  // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
408  // span the midpoint are probably relatively rare, so don't worry about them
409  // for now.
410  if (Subtarget->hasBFE())
411  setHasExtractBitsInsn(true);
412 
417 
418 
419  // These are really only legal for ieee_mode functions. We should be avoiding
420  // them for functions that don't have ieee_mode enabled, so just say they are
421  // legal.
426 
427 
428  if (Subtarget->haveRoundOpsF64()) {
432  } else {
437  }
438 
440 
445 
446  if (Subtarget->has16BitInsts()) {
448 
451 
454 
457 
460 
465 
468 
474 
476 
478 
480 
482 
487 
490 
491  // F16 - Constant Actions.
493 
494  // F16 - Load/Store Actions.
499 
500  // F16 - VOP1 Actions.
504 
507 
513 
514  // F16 - VOP2 Actions.
517 
519 
520  // F16 - VOP3 Actions.
522  if (STI.hasMadF16())
524 
525  for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
526  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
527  switch (Op) {
528  case ISD::LOAD:
529  case ISD::STORE:
530  case ISD::BUILD_VECTOR:
531  case ISD::BITCAST:
537  break;
538  case ISD::CONCAT_VECTORS:
540  break;
541  default:
543  break;
544  }
545  }
546  }
547 
548  // XXX - Do these do anything? Vector constants turn into build_vector.
551 
554 
559 
564 
571 
576 
581 
586 
590 
591  if (!Subtarget->hasVOP3PInsts()) {
594  }
595 
597  // This isn't really legal, but this avoids the legalizer unrolling it (and
598  // allows matching fneg (fabs x) patterns)
600 
605 
608 
611  }
612 
613  if (Subtarget->hasVOP3PInsts()) {
624 
628 
631 
633 
636 
639 
646 
651 
655 
658 
662 
666  }
667 
670 
671  if (Subtarget->has16BitInsts()) {
676  } else {
677  // Legalization hack.
680 
683  }
684 
687  }
688 
696 
706 
715 
743 
744  // All memory operations. Some folding on the pointer operand is done to help
745  // matching the constant offsets in the addressing modes.
764 
766 }
767 
769  return Subtarget;
770 }
771 
772 //===----------------------------------------------------------------------===//
773 // TargetLowering queries
774 //===----------------------------------------------------------------------===//
775 
776 // v_mad_mix* support a conversion from f16 to f32.
777 //
778 // There is only one special case when denormals are enabled we don't currently,
779 // where this is OK to use.
780 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
781  EVT DestVT, EVT SrcVT) const {
782  return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
783  (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
784  DestVT.getScalarType() == MVT::f32 &&
785  SrcVT.getScalarType() == MVT::f16 &&
787 }
788 
790  // SI has some legal vector types, but no legal vector operations. Say no
791  // shuffles are legal in order to prefer scalarizing some vector operations.
792  return false;
793 }
794 
796  CallingConv::ID CC,
797  EVT VT) const {
798  if (CC == CallingConv::AMDGPU_KERNEL)
799  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
800 
801  if (VT.isVector()) {
802  EVT ScalarVT = VT.getScalarType();
803  unsigned Size = ScalarVT.getSizeInBits();
804  if (Size == 32)
805  return ScalarVT.getSimpleVT();
806 
807  if (Size > 32)
808  return MVT::i32;
809 
810  if (Size == 16 && Subtarget->has16BitInsts())
811  return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
812  } else if (VT.getSizeInBits() > 32)
813  return MVT::i32;
814 
815  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
816 }
817 
819  CallingConv::ID CC,
820  EVT VT) const {
821  if (CC == CallingConv::AMDGPU_KERNEL)
822  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
823 
824  if (VT.isVector()) {
825  unsigned NumElts = VT.getVectorNumElements();
826  EVT ScalarVT = VT.getScalarType();
827  unsigned Size = ScalarVT.getSizeInBits();
828 
829  if (Size == 32)
830  return NumElts;
831 
832  if (Size > 32)
833  return NumElts * ((Size + 31) / 32);
834 
835  if (Size == 16 && Subtarget->has16BitInsts())
836  return (NumElts + 1) / 2;
837  } else if (VT.getSizeInBits() > 32)
838  return (VT.getSizeInBits() + 31) / 32;
839 
840  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
841 }
842 
845  EVT VT, EVT &IntermediateVT,
846  unsigned &NumIntermediates, MVT &RegisterVT) const {
847  if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
848  unsigned NumElts = VT.getVectorNumElements();
849  EVT ScalarVT = VT.getScalarType();
850  unsigned Size = ScalarVT.getSizeInBits();
851  if (Size == 32) {
852  RegisterVT = ScalarVT.getSimpleVT();
853  IntermediateVT = RegisterVT;
854  NumIntermediates = NumElts;
855  return NumIntermediates;
856  }
857 
858  if (Size > 32) {
859  RegisterVT = MVT::i32;
860  IntermediateVT = RegisterVT;
861  NumIntermediates = NumElts * ((Size + 31) / 32);
862  return NumIntermediates;
863  }
864 
865  // FIXME: We should fix the ABI to be the same on targets without 16-bit
866  // support, but unless we can properly handle 3-vectors, it will be still be
867  // inconsistent.
868  if (Size == 16 && Subtarget->has16BitInsts()) {
869  RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
870  IntermediateVT = RegisterVT;
871  NumIntermediates = (NumElts + 1) / 2;
872  return NumIntermediates;
873  }
874  }
875 
877  Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
878 }
879 
881  // Only limited forms of aggregate type currently expected.
882  assert(Ty->isStructTy() && "Expected struct type");
883 
884 
885  Type *ElementType = nullptr;
886  unsigned NumElts;
887  if (Ty->getContainedType(0)->isVectorTy()) {
888  VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
889  ElementType = VecComponent->getElementType();
890  NumElts = VecComponent->getNumElements();
891  } else {
892  ElementType = Ty->getContainedType(0);
893  NumElts = 1;
894  }
895 
896  assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
897 
898  // Calculate the size of the memVT type from the aggregate
899  unsigned Pow2Elts = 0;
900  unsigned ElementSize;
901  switch (ElementType->getTypeID()) {
902  default:
903  llvm_unreachable("Unknown type!");
904  case Type::IntegerTyID:
905  ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
906  break;
907  case Type::HalfTyID:
908  ElementSize = 16;
909  break;
910  case Type::FloatTyID:
911  ElementSize = 32;
912  break;
913  }
914  unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
915  Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
916 
917  return MVT::getVectorVT(MVT::getVT(ElementType, false),
918  Pow2Elts);
919 }
920 
922  const CallInst &CI,
923  MachineFunction &MF,
924  unsigned IntrID) const {
925  if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
926  AMDGPU::lookupRsrcIntrinsic(IntrID)) {
928  (Intrinsic::ID)IntrID);
929  if (Attr.hasFnAttribute(Attribute::ReadNone))
930  return false;
931 
933 
934  if (RsrcIntr->IsImage) {
935  Info.ptrVal = MFI->getImagePSV(
937  CI.getArgOperand(RsrcIntr->RsrcArg));
938  Info.align.reset();
939  } else {
940  Info.ptrVal = MFI->getBufferPSV(
942  CI.getArgOperand(RsrcIntr->RsrcArg));
943  }
944 
946  if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
948  Info.memVT = MVT::getVT(CI.getType(), true);
949  if (Info.memVT == MVT::Other) {
950  // Some intrinsics return an aggregate type - special case to work out
951  // the correct memVT
952  Info.memVT = memVTFromAggregate(CI.getType());
953  }
955  } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
956  Info.opc = ISD::INTRINSIC_VOID;
957  Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
959  } else {
960  // Atomic
962  Info.memVT = MVT::getVT(CI.getType());
966 
967  // XXX - Should this be volatile without known ordering?
969  }
970  return true;
971  }
972 
973  switch (IntrID) {
974  case Intrinsic::amdgcn_atomic_inc:
975  case Intrinsic::amdgcn_atomic_dec:
976  case Intrinsic::amdgcn_ds_ordered_add:
977  case Intrinsic::amdgcn_ds_ordered_swap:
978  case Intrinsic::amdgcn_ds_fadd:
979  case Intrinsic::amdgcn_ds_fmin:
980  case Intrinsic::amdgcn_ds_fmax: {
982  Info.memVT = MVT::getVT(CI.getType());
983  Info.ptrVal = CI.getOperand(0);
984  Info.align.reset();
986 
987  const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
988  if (!Vol->isZero())
990 
991  return true;
992  }
993  case Intrinsic::amdgcn_buffer_atomic_fadd: {
995 
996  Info.opc = ISD::INTRINSIC_VOID;
997  Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
998  Info.ptrVal = MFI->getBufferPSV(
1000  CI.getArgOperand(1));
1001  Info.align.reset();
1003 
1004  const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1005  if (!Vol || !Vol->isZero())
1007 
1008  return true;
1009  }
1010  case Intrinsic::amdgcn_global_atomic_fadd: {
1011  Info.opc = ISD::INTRINSIC_VOID;
1012  Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1013  ->getPointerElementType());
1014  Info.ptrVal = CI.getOperand(0);
1015  Info.align.reset();
1017 
1018  return true;
1019  }
1020  case Intrinsic::amdgcn_ds_append:
1021  case Intrinsic::amdgcn_ds_consume: {
1022  Info.opc = ISD::INTRINSIC_W_CHAIN;
1023  Info.memVT = MVT::getVT(CI.getType());
1024  Info.ptrVal = CI.getOperand(0);
1025  Info.align.reset();
1027 
1028  const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1029  if (!Vol->isZero())
1031 
1032  return true;
1033  }
1034  case Intrinsic::amdgcn_ds_gws_init:
1035  case Intrinsic::amdgcn_ds_gws_barrier:
1036  case Intrinsic::amdgcn_ds_gws_sema_v:
1037  case Intrinsic::amdgcn_ds_gws_sema_br:
1038  case Intrinsic::amdgcn_ds_gws_sema_p:
1039  case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1040  Info.opc = ISD::INTRINSIC_VOID;
1041 
1043  Info.ptrVal =
1045 
1046  // This is an abstract access, but we need to specify a type and size.
1047  Info.memVT = MVT::i32;
1048  Info.size = 4;
1049  Info.align = Align(4);
1050 
1052  if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1054  return true;
1055  }
1056  default:
1057  return false;
1058  }
1059 }
1060 
1063  Type *&AccessTy) const {
1064  switch (II->getIntrinsicID()) {
1065  case Intrinsic::amdgcn_atomic_inc:
1066  case Intrinsic::amdgcn_atomic_dec:
1067  case Intrinsic::amdgcn_ds_ordered_add:
1068  case Intrinsic::amdgcn_ds_ordered_swap:
1069  case Intrinsic::amdgcn_ds_fadd:
1070  case Intrinsic::amdgcn_ds_fmin:
1071  case Intrinsic::amdgcn_ds_fmax: {
1072  Value *Ptr = II->getArgOperand(0);
1073  AccessTy = II->getType();
1074  Ops.push_back(Ptr);
1075  return true;
1076  }
1077  default:
1078  return false;
1079  }
1080 }
1081 
1082 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1083  if (!Subtarget->hasFlatInstOffsets()) {
1084  // Flat instructions do not have offsets, and only have the register
1085  // address.
1086  return AM.BaseOffs == 0 && AM.Scale == 0;
1087  }
1088 
1089  return AM.Scale == 0 &&
1090  (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1092  /*Signed=*/false));
1093 }
1094 
1096  if (Subtarget->hasFlatGlobalInsts())
1097  return AM.Scale == 0 &&
1098  (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1100  /*Signed=*/true));
1101 
1102  if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1103  // Assume the we will use FLAT for all global memory accesses
1104  // on VI.
1105  // FIXME: This assumption is currently wrong. On VI we still use
1106  // MUBUF instructions for the r + i addressing mode. As currently
1107  // implemented, the MUBUF instructions only work on buffer < 4GB.
1108  // It may be possible to support > 4GB buffers with MUBUF instructions,
1109  // by setting the stride value in the resource descriptor which would
1110  // increase the size limit to (stride * 4GB). However, this is risky,
1111  // because it has never been validated.
1112  return isLegalFlatAddressingMode(AM);
1113  }
1114 
1115  return isLegalMUBUFAddressingMode(AM);
1116 }
1117 
1118 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1119  // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1120  // additionally can do r + r + i with addr64. 32-bit has more addressing
1121  // mode options. Depending on the resource constant, it can also do
1122  // (i64 r0) + (i32 r1) * (i14 i).
1123  //
1124  // Private arrays end up using a scratch buffer most of the time, so also
1125  // assume those use MUBUF instructions. Scratch loads / stores are currently
1126  // implemented as mubuf instructions with offen bit set, so slightly
1127  // different than the normal addr64.
1128  if (!isUInt<12>(AM.BaseOffs))
1129  return false;
1130 
1131  // FIXME: Since we can split immediate into soffset and immediate offset,
1132  // would it make sense to allow any immediate?
1133 
1134  switch (AM.Scale) {
1135  case 0: // r + i or just i, depending on HasBaseReg.
1136  return true;
1137  case 1:
1138  return true; // We have r + r or r + i.
1139  case 2:
1140  if (AM.HasBaseReg) {
1141  // Reject 2 * r + r.
1142  return false;
1143  }
1144 
1145  // Allow 2 * r as r + r
1146  // Or 2 * r + i is allowed as r + r + i.
1147  return true;
1148  default: // Don't allow n * r
1149  return false;
1150  }
1151 }
1152 
1154  const AddrMode &AM, Type *Ty,
1155  unsigned AS, Instruction *I) const {
1156  // No global is ever allowed as a base.
1157  if (AM.BaseGV)
1158  return false;
1159 
1160  if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1161  return isLegalGlobalAddressingMode(AM);
1162 
1163  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1166  // If the offset isn't a multiple of 4, it probably isn't going to be
1167  // correctly aligned.
1168  // FIXME: Can we get the real alignment here?
1169  if (AM.BaseOffs % 4 != 0)
1170  return isLegalMUBUFAddressingMode(AM);
1171 
1172  // There are no SMRD extloads, so if we have to do a small type access we
1173  // will use a MUBUF load.
1174  // FIXME?: We also need to do this if unaligned, but we don't know the
1175  // alignment here.
1176  if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1177  return isLegalGlobalAddressingMode(AM);
1178 
1179  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1180  // SMRD instructions have an 8-bit, dword offset on SI.
1181  if (!isUInt<8>(AM.BaseOffs / 4))
1182  return false;
1183  } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1184  // On CI+, this can also be a 32-bit literal constant offset. If it fits
1185  // in 8-bits, it can use a smaller encoding.
1186  if (!isUInt<32>(AM.BaseOffs / 4))
1187  return false;
1188  } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1189  // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1190  if (!isUInt<20>(AM.BaseOffs))
1191  return false;
1192  } else
1193  llvm_unreachable("unhandled generation");
1194 
1195  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1196  return true;
1197 
1198  if (AM.Scale == 1 && AM.HasBaseReg)
1199  return true;
1200 
1201  return false;
1202 
1203  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1204  return isLegalMUBUFAddressingMode(AM);
1205  } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1206  AS == AMDGPUAS::REGION_ADDRESS) {
1207  // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1208  // field.
1209  // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1210  // an 8-bit dword offset but we don't know the alignment here.
1211  if (!isUInt<16>(AM.BaseOffs))
1212  return false;
1213 
1214  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1215  return true;
1216 
1217  if (AM.Scale == 1 && AM.HasBaseReg)
1218  return true;
1219 
1220  return false;
1221  } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1223  // For an unknown address space, this usually means that this is for some
1224  // reason being used for pure arithmetic, and not based on some addressing
1225  // computation. We don't have instructions that compute pointers with any
1226  // addressing modes, so treat them as having no offset like flat
1227  // instructions.
1228  return isLegalFlatAddressingMode(AM);
1229  } else {
1230  llvm_unreachable("unhandled address space");
1231  }
1232 }
1233 
1234 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1235  const SelectionDAG &DAG) const {
1236  if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1237  return (MemVT.getSizeInBits() <= 4 * 32);
1238  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1239  unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1240  return (MemVT.getSizeInBits() <= MaxPrivateBits);
1241  } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1242  return (MemVT.getSizeInBits() <= 2 * 32);
1243  }
1244  return true;
1245 }
1246 
1248  unsigned Size, unsigned AddrSpace, unsigned Align,
1249  MachineMemOperand::Flags Flags, bool *IsFast) const {
1250  if (IsFast)
1251  *IsFast = false;
1252 
1253  if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1254  AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1255  // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1256  // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1257  // with adjacent offsets.
1258  bool AlignedBy4 = (Align % 4 == 0);
1259  if (IsFast)
1260  *IsFast = AlignedBy4;
1261 
1262  return AlignedBy4;
1263  }
1264 
1265  // FIXME: We have to be conservative here and assume that flat operations
1266  // will access scratch. If we had access to the IR function, then we
1267  // could determine if any private memory was used in the function.
1268  if (!Subtarget->hasUnalignedScratchAccess() &&
1269  (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1270  AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1271  bool AlignedBy4 = Align >= 4;
1272  if (IsFast)
1273  *IsFast = AlignedBy4;
1274 
1275  return AlignedBy4;
1276  }
1277 
1278  if (Subtarget->hasUnalignedBufferAccess()) {
1279  // If we have an uniform constant load, it still requires using a slow
1280  // buffer instruction if unaligned.
1281  if (IsFast) {
1282  *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1283  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1284  (Align % 4 == 0) : true;
1285  }
1286 
1287  return true;
1288  }
1289 
1290  // Smaller than dword value must be aligned.
1291  if (Size < 32)
1292  return false;
1293 
1294  // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1295  // byte-address are ignored, thus forcing Dword alignment.
1296  // This applies to private, global, and constant memory.
1297  if (IsFast)
1298  *IsFast = true;
1299 
1300  return Size >= 32 && Align >= 4;
1301 }
1302 
1304  EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1305  bool *IsFast) const {
1306  if (IsFast)
1307  *IsFast = false;
1308 
1309  // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1310  // which isn't a simple VT.
1311  // Until MVT is extended to handle this, simply check for the size and
1312  // rely on the condition below: allow accesses if the size is a multiple of 4.
1313  if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1314  VT.getStoreSize() > 16)) {
1315  return false;
1316  }
1317 
1318  return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1319  Align, Flags, IsFast);
1320 }
1321 
1323  uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1324  bool ZeroMemset, bool MemcpyStrSrc,
1325  const AttributeList &FuncAttributes) const {
1326  // FIXME: Should account for address space here.
1327 
1328  // The default fallback uses the private pointer size as a guess for a type to
1329  // use. Make sure we switch these to 64-bit accesses.
1330 
1331  if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1332  return MVT::v4i32;
1333 
1334  if (Size >= 8 && DstAlign >= 4)
1335  return MVT::v2i32;
1336 
1337  // Use the default.
1338  return MVT::Other;
1339 }
1340 
1342  unsigned DestAS) const {
1343  return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1344 }
1345 
1347  const MemSDNode *MemNode = cast<MemSDNode>(N);
1348  const Value *Ptr = MemNode->getMemOperand()->getValue();
1349  const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1350  return I && I->getMetadata("amdgpu.noclobber");
1351 }
1352 
1354  unsigned DestAS) const {
1355  // Flat -> private/local is a simple truncate.
1356  // Flat -> global is no-op
1357  if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1358  return true;
1359 
1360  return isNoopAddrSpaceCast(SrcAS, DestAS);
1361 }
1362 
1364  const MemSDNode *MemNode = cast<MemSDNode>(N);
1365 
1366  return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1367 }
1368 
1371  int NumElts = VT.getVectorNumElements();
1372  if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1375 }
1376 
1378  Type *Ty) const {
1379  // FIXME: Could be smarter if called for vector constants.
1380  return true;
1381 }
1382 
1384  if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1385  switch (Op) {
1386  case ISD::LOAD:
1387  case ISD::STORE:
1388 
1389  // These operations are done with 32-bit instructions anyway.
1390  case ISD::AND:
1391  case ISD::OR:
1392  case ISD::XOR:
1393  case ISD::SELECT:
1394  // TODO: Extensions?
1395  return true;
1396  default:
1397  return false;
1398  }
1399  }
1400 
1401  // SimplifySetCC uses this function to determine whether or not it should
1402  // create setcc with i1 operands. We don't have instructions for i1 setcc.
1403  if (VT == MVT::i1 && Op == ISD::SETCC)
1404  return false;
1405 
1406  return TargetLowering::isTypeDesirableForOp(Op, VT);
1407 }
1408 
1409 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1410  const SDLoc &SL,
1411  SDValue Chain,
1412  uint64_t Offset) const {
1413  const DataLayout &DL = DAG.getDataLayout();
1414  MachineFunction &MF = DAG.getMachineFunction();
1416 
1417  const ArgDescriptor *InputPtrReg;
1418  const TargetRegisterClass *RC;
1419 
1420  std::tie(InputPtrReg, RC)
1422 
1425  SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1426  MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1427 
1428  return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1429 }
1430 
1431 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1432  const SDLoc &SL) const {
1433  uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1434  FIRST_IMPLICIT);
1435  return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1436 }
1437 
1438 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1439  const SDLoc &SL, SDValue Val,
1440  bool Signed,
1441  const ISD::InputArg *Arg) const {
1442  // First, if it is a widened vector, narrow it.
1443  if (VT.isVector() &&
1444  VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1445  EVT NarrowedVT =
1447  VT.getVectorNumElements());
1448  Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1449  DAG.getConstant(0, SL, MVT::i32));
1450  }
1451 
1452  // Then convert the vector elements or scalar value.
1453  if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1454  VT.bitsLT(MemVT)) {
1455  unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1456  Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1457  }
1458 
1459  if (MemVT.isFloatingPoint())
1460  Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1461  else if (Signed)
1462  Val = DAG.getSExtOrTrunc(Val, SL, VT);
1463  else
1464  Val = DAG.getZExtOrTrunc(Val, SL, VT);
1465 
1466  return Val;
1467 }
1468 
1469 SDValue SITargetLowering::lowerKernargMemParameter(
1470  SelectionDAG &DAG, EVT VT, EVT MemVT,
1471  const SDLoc &SL, SDValue Chain,
1472  uint64_t Offset, unsigned Align, bool Signed,
1473  const ISD::InputArg *Arg) const {
1475 
1476  // Try to avoid using an extload by loading earlier than the argument address,
1477  // and extracting the relevant bits. The load should hopefully be merged with
1478  // the previous argument.
1479  if (MemVT.getStoreSize() < 4 && Align < 4) {
1480  // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1481  int64_t AlignDownOffset = alignDown(Offset, 4);
1482  int64_t OffsetDiff = Offset - AlignDownOffset;
1483 
1484  EVT IntVT = MemVT.changeTypeToInteger();
1485 
1486  // TODO: If we passed in the base kernel offset we could have a better
1487  // alignment than 4, but we don't really need it.
1488  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1489  SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1492 
1493  SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1494  SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1495 
1496  SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1497  ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1498  ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1499 
1500 
1501  return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1502  }
1503 
1504  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1505  SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1508 
1509  SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1510  return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1511 }
1512 
1513 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1514  const SDLoc &SL, SDValue Chain,
1515  const ISD::InputArg &Arg) const {
1516  MachineFunction &MF = DAG.getMachineFunction();
1517  MachineFrameInfo &MFI = MF.getFrameInfo();
1518 
1519  if (Arg.Flags.isByVal()) {
1520  unsigned Size = Arg.Flags.getByValSize();
1521  int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1522  return DAG.getFrameIndex(FrameIdx, MVT::i32);
1523  }
1524 
1525  unsigned ArgOffset = VA.getLocMemOffset();
1526  unsigned ArgSize = VA.getValVT().getStoreSize();
1527 
1528  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1529 
1530  // Create load nodes to retrieve arguments from the stack.
1531  SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1532  SDValue ArgValue;
1533 
1534  // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1536  MVT MemVT = VA.getValVT();
1537 
1538  switch (VA.getLocInfo()) {
1539  default:
1540  break;
1541  case CCValAssign::BCvt:
1542  MemVT = VA.getLocVT();
1543  break;
1544  case CCValAssign::SExt:
1545  ExtType = ISD::SEXTLOAD;
1546  break;
1547  case CCValAssign::ZExt:
1548  ExtType = ISD::ZEXTLOAD;
1549  break;
1550  case CCValAssign::AExt:
1551  ExtType = ISD::EXTLOAD;
1552  break;
1553  }
1554 
1555  ArgValue = DAG.getExtLoad(
1556  ExtType, SL, VA.getLocVT(), Chain, FIN,
1558  MemVT);
1559  return ArgValue;
1560 }
1561 
1562 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1563  const SIMachineFunctionInfo &MFI,
1564  EVT VT,
1566  const ArgDescriptor *Reg;
1567  const TargetRegisterClass *RC;
1568 
1569  std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1570  return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1571 }
1572 
1574  CallingConv::ID CallConv,
1576  BitVector &Skipped,
1577  FunctionType *FType,
1579  for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1580  const ISD::InputArg *Arg = &Ins[I];
1581 
1582  assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1583  "vector type argument should have been split");
1584 
1585  // First check if it's a PS input addr.
1586  if (CallConv == CallingConv::AMDGPU_PS &&
1587  !Arg->Flags.isInReg() && PSInputNum <= 15) {
1588  bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1589 
1590  // Inconveniently only the first part of the split is marked as isSplit,
1591  // so skip to the end. We only want to increment PSInputNum once for the
1592  // entire split argument.
1593  if (Arg->Flags.isSplit()) {
1594  while (!Arg->Flags.isSplitEnd()) {
1595  assert((!Arg->VT.isVector() ||
1596  Arg->VT.getScalarSizeInBits() == 16) &&
1597  "unexpected vector split in ps argument type");
1598  if (!SkipArg)
1599  Splits.push_back(*Arg);
1600  Arg = &Ins[++I];
1601  }
1602  }
1603 
1604  if (SkipArg) {
1605  // We can safely skip PS inputs.
1606  Skipped.set(Arg->getOrigArgIndex());
1607  ++PSInputNum;
1608  continue;
1609  }
1610 
1611  Info->markPSInputAllocated(PSInputNum);
1612  if (Arg->Used)
1613  Info->markPSInputEnabled(PSInputNum);
1614 
1615  ++PSInputNum;
1616  }
1617 
1618  Splits.push_back(*Arg);
1619  }
1620 }
1621 
1622 // Allocate special inputs passed in VGPRs.
1624  MachineFunction &MF,
1625  const SIRegisterInfo &TRI,
1626  SIMachineFunctionInfo &Info) const {
1627  const LLT S32 = LLT::scalar(32);
1629 
1630  if (Info.hasWorkItemIDX()) {
1631  Register Reg = AMDGPU::VGPR0;
1632  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1633 
1634  CCInfo.AllocateReg(Reg);
1636  }
1637 
1638  if (Info.hasWorkItemIDY()) {
1639  Register Reg = AMDGPU::VGPR1;
1640  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1641 
1642  CCInfo.AllocateReg(Reg);
1644  }
1645 
1646  if (Info.hasWorkItemIDZ()) {
1647  Register Reg = AMDGPU::VGPR2;
1648  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1649 
1650  CCInfo.AllocateReg(Reg);
1652  }
1653 }
1654 
1655 // Try to allocate a VGPR at the end of the argument list, or if no argument
1656 // VGPRs are left allocating a stack slot.
1657 // If \p Mask is is given it indicates bitfield position in the register.
1658 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1659 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1660  ArgDescriptor Arg = ArgDescriptor()) {
1661  if (Arg.isSet())
1662  return ArgDescriptor::createArg(Arg, Mask);
1663 
1664  ArrayRef<MCPhysReg> ArgVGPRs
1665  = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1666  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1667  if (RegIdx == ArgVGPRs.size()) {
1668  // Spill to stack required.
1669  int64_t Offset = CCInfo.AllocateStack(4, 4);
1670 
1671  return ArgDescriptor::createStack(Offset, Mask);
1672  }
1673 
1674  unsigned Reg = ArgVGPRs[RegIdx];
1675  Reg = CCInfo.AllocateReg(Reg);
1676  assert(Reg != AMDGPU::NoRegister);
1677 
1678  MachineFunction &MF = CCInfo.getMachineFunction();
1679  Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1680  MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1681  return ArgDescriptor::createRegister(Reg, Mask);
1682 }
1683 
1685  const TargetRegisterClass *RC,
1686  unsigned NumArgRegs) {
1687  ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1688  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1689  if (RegIdx == ArgSGPRs.size())
1690  report_fatal_error("ran out of SGPRs for arguments");
1691 
1692  unsigned Reg = ArgSGPRs[RegIdx];
1693  Reg = CCInfo.AllocateReg(Reg);
1694  assert(Reg != AMDGPU::NoRegister);
1695 
1696  MachineFunction &MF = CCInfo.getMachineFunction();
1697  MF.addLiveIn(Reg, RC);
1698  return ArgDescriptor::createRegister(Reg);
1699 }
1700 
1702  return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1703 }
1704 
1706  return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1707 }
1708 
1710  MachineFunction &MF,
1711  const SIRegisterInfo &TRI,
1712  SIMachineFunctionInfo &Info) const {
1713  const unsigned Mask = 0x3ff;
1715 
1716  if (Info.hasWorkItemIDX()) {
1717  Arg = allocateVGPR32Input(CCInfo, Mask);
1718  Info.setWorkItemIDX(Arg);
1719  }
1720 
1721  if (Info.hasWorkItemIDY()) {
1722  Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1723  Info.setWorkItemIDY(Arg);
1724  }
1725 
1726  if (Info.hasWorkItemIDZ())
1727  Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1728 }
1729 
1731  CCState &CCInfo,
1732  MachineFunction &MF,
1733  const SIRegisterInfo &TRI,
1734  SIMachineFunctionInfo &Info) const {
1735  auto &ArgInfo = Info.getArgInfo();
1736 
1737  // TODO: Unify handling with private memory pointers.
1738 
1739  if (Info.hasDispatchPtr())
1740  ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1741 
1742  if (Info.hasQueuePtr())
1743  ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1744 
1745  if (Info.hasKernargSegmentPtr())
1746  ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1747 
1748  if (Info.hasDispatchID())
1749  ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1750 
1751  // flat_scratch_init is not applicable for non-kernel functions.
1752 
1753  if (Info.hasWorkGroupIDX())
1754  ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1755 
1756  if (Info.hasWorkGroupIDY())
1757  ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1758 
1759  if (Info.hasWorkGroupIDZ())
1760  ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1761 
1762  if (Info.hasImplicitArgPtr())
1763  ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1764 }
1765 
1766 // Allocate special inputs passed in user SGPRs.
1768  MachineFunction &MF,
1769  const SIRegisterInfo &TRI,
1770  SIMachineFunctionInfo &Info) const {
1771  if (Info.hasImplicitBufferPtr()) {
1772  unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1773  MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1774  CCInfo.AllocateReg(ImplicitBufferPtrReg);
1775  }
1776 
1777  // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1778  if (Info.hasPrivateSegmentBuffer()) {
1779  unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1780  MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1781  CCInfo.AllocateReg(PrivateSegmentBufferReg);
1782  }
1783 
1784  if (Info.hasDispatchPtr()) {
1785  unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1786  MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1787  CCInfo.AllocateReg(DispatchPtrReg);
1788  }
1789 
1790  if (Info.hasQueuePtr()) {
1791  unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1792  MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1793  CCInfo.AllocateReg(QueuePtrReg);
1794  }
1795 
1796  if (Info.hasKernargSegmentPtr()) {
1798  Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1799  CCInfo.AllocateReg(InputPtrReg);
1800 
1801  Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1803  }
1804 
1805  if (Info.hasDispatchID()) {
1806  unsigned DispatchIDReg = Info.addDispatchID(TRI);
1807  MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1808  CCInfo.AllocateReg(DispatchIDReg);
1809  }
1810 
1811  if (Info.hasFlatScratchInit()) {
1812  unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1813  MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1814  CCInfo.AllocateReg(FlatScratchInitReg);
1815  }
1816 
1817  // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1818  // these from the dispatch pointer.
1819 }
1820 
1821 // Allocate special input registers that are initialized per-wave.
1823  MachineFunction &MF,
1825  CallingConv::ID CallConv,
1826  bool IsShader) const {
1827  if (Info.hasWorkGroupIDX()) {
1828  unsigned Reg = Info.addWorkGroupIDX();
1829  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1830  CCInfo.AllocateReg(Reg);
1831  }
1832 
1833  if (Info.hasWorkGroupIDY()) {
1834  unsigned Reg = Info.addWorkGroupIDY();
1835  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1836  CCInfo.AllocateReg(Reg);
1837  }
1838 
1839  if (Info.hasWorkGroupIDZ()) {
1840  unsigned Reg = Info.addWorkGroupIDZ();
1841  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1842  CCInfo.AllocateReg(Reg);
1843  }
1844 
1845  if (Info.hasWorkGroupInfo()) {
1846  unsigned Reg = Info.addWorkGroupInfo();
1847  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1848  CCInfo.AllocateReg(Reg);
1849  }
1850 
1851  if (Info.hasPrivateSegmentWaveByteOffset()) {
1852  // Scratch wave offset passed in system SGPR.
1853  unsigned PrivateSegmentWaveByteOffsetReg;
1854 
1855  if (IsShader) {
1856  PrivateSegmentWaveByteOffsetReg =
1858 
1859  // This is true if the scratch wave byte offset doesn't have a fixed
1860  // location.
1861  if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1862  PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1863  Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1864  }
1865  } else
1866  PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1867 
1868  MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1869  CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1870  }
1871 }
1872 
1874  MachineFunction &MF,
1875  const SIRegisterInfo &TRI,
1877  // Now that we've figured out where the scratch register inputs are, see if
1878  // should reserve the arguments and use them directly.
1879  MachineFrameInfo &MFI = MF.getFrameInfo();
1880  bool HasStackObjects = MFI.hasStackObjects();
1881  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1882 
1883  // Record that we know we have non-spill stack objects so we don't need to
1884  // check all stack objects later.
1885  if (HasStackObjects)
1886  Info.setHasNonSpillStackObjects(true);
1887 
1888  // Everything live out of a block is spilled with fast regalloc, so it's
1889  // almost certain that spilling will be required.
1890  if (TM.getOptLevel() == CodeGenOpt::None)
1891  HasStackObjects = true;
1892 
1893  // For now assume stack access is needed in any callee functions, so we need
1894  // the scratch registers to pass in.
1895  bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1896 
1897  if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1898  // If we have stack objects, we unquestionably need the private buffer
1899  // resource. For the Code Object V2 ABI, this will be the first 4 user
1900  // SGPR inputs. We can reserve those and use them directly.
1901 
1902  Register PrivateSegmentBufferReg =
1904  Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1905  } else {
1906  unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1907  // We tentatively reserve the last registers (skipping the last registers
1908  // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1909  // we'll replace these with the ones immediately after those which were
1910  // really allocated. In the prologue copies will be inserted from the
1911  // argument to these reserved registers.
1912 
1913  // Without HSA, relocations are used for the scratch pointer and the
1914  // buffer resource setup is always inserted in the prologue. Scratch wave
1915  // offset is still in an input SGPR.
1916  Info.setScratchRSrcReg(ReservedBufferReg);
1917  }
1918 
1919  // hasFP should be accurate for kernels even before the frame is finalized.
1920  if (ST.getFrameLowering()->hasFP(MF)) {
1922 
1923  // Try to use s32 as the SP, but move it if it would interfere with input
1924  // arguments. This won't work with calls though.
1925  //
1926  // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1927  // registers.
1928  if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1929  Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1930  } else {
1932 
1933  if (MFI.hasCalls())
1934  report_fatal_error("call in graphics shader with too many input SGPRs");
1935 
1936  for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1937  if (!MRI.isLiveIn(Reg)) {
1938  Info.setStackPtrOffsetReg(Reg);
1939  break;
1940  }
1941  }
1942 
1943  if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1944  report_fatal_error("failed to find register for SP");
1945  }
1946 
1947  if (MFI.hasCalls()) {
1948  Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1949  Info.setFrameOffsetReg(AMDGPU::SGPR33);
1950  } else {
1951  unsigned ReservedOffsetReg =
1953  Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1954  Info.setFrameOffsetReg(ReservedOffsetReg);
1955  }
1956  } else if (RequiresStackAccess) {
1957  assert(!MFI.hasCalls());
1958  // We know there are accesses and they will be done relative to SP, so just
1959  // pin it to the input.
1960  //
1961  // FIXME: Should not do this if inline asm is reading/writing these
1962  // registers.
1963  Register PreloadedSP = Info.getPreloadedReg(
1965 
1966  Info.setStackPtrOffsetReg(PreloadedSP);
1967  Info.setScratchWaveOffsetReg(PreloadedSP);
1968  Info.setFrameOffsetReg(PreloadedSP);
1969  } else {
1970  assert(!MFI.hasCalls());
1971 
1972  // There may not be stack access at all. There may still be spills, or
1973  // access of a constant pointer (in which cases an extra copy will be
1974  // emitted in the prolog).
1975  unsigned ReservedOffsetReg
1977  Info.setStackPtrOffsetReg(ReservedOffsetReg);
1978  Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1979  Info.setFrameOffsetReg(ReservedOffsetReg);
1980  }
1981 }
1982 
1985  return !Info->isEntryFunction();
1986 }
1987 
1989 
1990 }
1991 
1994  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1996 
1997  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1998  if (!IStart)
1999  return;
2000 
2001  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2002  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2003  MachineBasicBlock::iterator MBBI = Entry->begin();
2004  for (const MCPhysReg *I = IStart; *I; ++I) {
2005  const TargetRegisterClass *RC = nullptr;
2006  if (AMDGPU::SReg_64RegClass.contains(*I))
2007  RC = &AMDGPU::SGPR_64RegClass;
2008  else if (AMDGPU::SReg_32RegClass.contains(*I))
2009  RC = &AMDGPU::SGPR_32RegClass;
2010  else
2011  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2012 
2013  Register NewVR = MRI->createVirtualRegister(RC);
2014  // Create copy from CSR to a virtual register.
2015  Entry->addLiveIn(*I);
2016  BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2017  .addReg(*I);
2018 
2019  // Insert the copy-back instructions right before the terminator.
2020  for (auto *Exit : Exits)
2021  BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2022  TII->get(TargetOpcode::COPY), *I)
2023  .addReg(NewVR);
2024  }
2025 }
2026 
2028  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2029  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2030  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2032 
2033  MachineFunction &MF = DAG.getMachineFunction();
2034  const Function &Fn = MF.getFunction();
2035  FunctionType *FType = MF.getFunction().getFunctionType();
2037 
2038  if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2039  DiagnosticInfoUnsupported NoGraphicsHSA(
2040  Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2041  DAG.getContext()->diagnose(NoGraphicsHSA);
2042  return DAG.getEntryNode();
2043  }
2044 
2047  BitVector Skipped(Ins.size());
2048  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2049  *DAG.getContext());
2050 
2051  bool IsShader = AMDGPU::isShader(CallConv);
2052  bool IsKernel = AMDGPU::isKernel(CallConv);
2053  bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2054 
2055  if (IsShader) {
2056  processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2057 
2058  // At least one interpolation mode must be enabled or else the GPU will
2059  // hang.
2060  //
2061  // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2062  // set PSInputAddr, the user wants to enable some bits after the compilation
2063  // based on run-time states. Since we can't know what the final PSInputEna
2064  // will look like, so we shouldn't do anything here and the user should take
2065  // responsibility for the correct programming.
2066  //
2067  // Otherwise, the following restrictions apply:
2068  // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2069  // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2070  // enabled too.
2071  if (CallConv == CallingConv::AMDGPU_PS) {
2072  if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2073  ((Info->getPSInputAddr() & 0xF) == 0 &&
2074  Info->isPSInputAllocated(11))) {
2075  CCInfo.AllocateReg(AMDGPU::VGPR0);
2076  CCInfo.AllocateReg(AMDGPU::VGPR1);
2077  Info->markPSInputAllocated(0);
2078  Info->markPSInputEnabled(0);
2079  }
2080  if (Subtarget->isAmdPalOS()) {
2081  // For isAmdPalOS, the user does not enable some bits after compilation
2082  // based on run-time states; the register values being generated here are
2083  // the final ones set in hardware. Therefore we need to apply the
2084  // workaround to PSInputAddr and PSInputEnable together. (The case where
2085  // a bit is set in PSInputAddr but not PSInputEnable is where the
2086  // frontend set up an input arg for a particular interpolation mode, but
2087  // nothing uses that input arg. Really we should have an earlier pass
2088  // that removes such an arg.)
2089  unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2090  if ((PsInputBits & 0x7F) == 0 ||
2091  ((PsInputBits & 0xF) == 0 &&
2092  (PsInputBits >> 11 & 1)))
2093  Info->markPSInputEnabled(
2095  }
2096  }
2097 
2098  assert(!Info->hasDispatchPtr() &&
2099  !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2100  !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2101  !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2102  !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2103  !Info->hasWorkItemIDZ());
2104  } else if (IsKernel) {
2105  assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2106  } else {
2107  Splits.append(Ins.begin(), Ins.end());
2108  }
2109 
2110  if (IsEntryFunc) {
2111  allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2112  allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2113  }
2114 
2115  if (IsKernel) {
2116  analyzeFormalArgumentsCompute(CCInfo, Ins);
2117  } else {
2118  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2119  CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2120  }
2121 
2122  SmallVector<SDValue, 16> Chains;
2123 
2124  // FIXME: This is the minimum kernel argument alignment. We should improve
2125  // this to the maximum alignment of the arguments.
2126  //
2127  // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2128  // kern arg offset.
2129  const unsigned KernelArgBaseAlign = 16;
2130 
2131  for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2132  const ISD::InputArg &Arg = Ins[i];
2133  if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2134  InVals.push_back(DAG.getUNDEF(Arg.VT));
2135  continue;
2136  }
2137 
2138  CCValAssign &VA = ArgLocs[ArgIdx++];
2139  MVT VT = VA.getLocVT();
2140 
2141  if (IsEntryFunc && VA.isMemLoc()) {
2142  VT = Ins[i].VT;
2143  EVT MemVT = VA.getLocVT();
2144 
2145  const uint64_t Offset = VA.getLocMemOffset();
2146  unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2147 
2148  SDValue Arg = lowerKernargMemParameter(
2149  DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2150  Chains.push_back(Arg.getValue(1));
2151 
2152  auto *ParamTy =
2153  dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2154  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2155  ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2156  ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2157  // On SI local pointers are just offsets into LDS, so they are always
2158  // less than 16-bits. On CI and newer they could potentially be
2159  // real pointers, so we can't guarantee their size.
2160  Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2161  DAG.getValueType(MVT::i16));
2162  }
2163 
2164  InVals.push_back(Arg);
2165  continue;
2166  } else if (!IsEntryFunc && VA.isMemLoc()) {
2167  SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2168  InVals.push_back(Val);
2169  if (!Arg.Flags.isByVal())
2170  Chains.push_back(Val.getValue(1));
2171  continue;
2172  }
2173 
2174  assert(VA.isRegLoc() && "Parameter must be in a register!");
2175 
2176  Register Reg = VA.getLocReg();
2177  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2178  EVT ValVT = VA.getValVT();
2179 
2180  Reg = MF.addLiveIn(Reg, RC);
2181  SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2182 
2183  if (Arg.Flags.isSRet()) {
2184  // The return object should be reasonably addressable.
2185 
2186  // FIXME: This helps when the return is a real sret. If it is a
2187  // automatically inserted sret (i.e. CanLowerReturn returns false), an
2188  // extra copy is inserted in SelectionDAGBuilder which obscures this.
2189  unsigned NumBits
2191  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2192  DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2193  }
2194 
2195  // If this is an 8 or 16-bit value, it is really passed promoted
2196  // to 32 bits. Insert an assert[sz]ext to capture this, then
2197  // truncate to the right size.
2198  switch (VA.getLocInfo()) {
2199  case CCValAssign::Full:
2200  break;
2201  case CCValAssign::BCvt:
2202  Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2203  break;
2204  case CCValAssign::SExt:
2205  Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2206  DAG.getValueType(ValVT));
2207  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2208  break;
2209  case CCValAssign::ZExt:
2210  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2211  DAG.getValueType(ValVT));
2212  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2213  break;
2214  case CCValAssign::AExt:
2215  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2216  break;
2217  default:
2218  llvm_unreachable("Unknown loc info!");
2219  }
2220 
2221  InVals.push_back(Val);
2222  }
2223 
2224  if (!IsEntryFunc) {
2225  // Special inputs come after user arguments.
2226  allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2227  }
2228 
2229  // Start adding system SGPRs.
2230  if (IsEntryFunc) {
2231  allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2232  } else {
2233  CCInfo.AllocateReg(Info->getScratchRSrcReg());
2234  CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2235  CCInfo.AllocateReg(Info->getFrameOffsetReg());
2236  allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2237  }
2238 
2239  auto &ArgUsageInfo =
2241  ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2242 
2243  unsigned StackArgSize = CCInfo.getNextStackOffset();
2244  Info->setBytesInStackArgArea(StackArgSize);
2245 
2246  return Chains.empty() ? Chain :
2247  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2248 }
2249 
2250 // TODO: If return values can't fit in registers, we should return as many as
2251 // possible in registers before passing on stack.
2253  CallingConv::ID CallConv,
2254  MachineFunction &MF, bool IsVarArg,
2255  const SmallVectorImpl<ISD::OutputArg> &Outs,
2256  LLVMContext &Context) const {
2257  // Replacing returns with sret/stack usage doesn't make sense for shaders.
2258  // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2259  // for shaders. Vector types should be explicitly handled by CC.
2260  if (AMDGPU::isEntryFunctionCC(CallConv))
2261  return true;
2262 
2264  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2265  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2266 }
2267 
2268 SDValue
2270  bool isVarArg,
2271  const SmallVectorImpl<ISD::OutputArg> &Outs,
2272  const SmallVectorImpl<SDValue> &OutVals,
2273  const SDLoc &DL, SelectionDAG &DAG) const {
2274  MachineFunction &MF = DAG.getMachineFunction();
2276 
2277  if (AMDGPU::isKernel(CallConv)) {
2278  return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2279  OutVals, DL, DAG);
2280  }
2281 
2282  bool IsShader = AMDGPU::isShader(CallConv);
2283 
2284  Info->setIfReturnsVoid(Outs.empty());
2285  bool IsWaveEnd = Info->returnsVoid() && IsShader;
2286 
2287  // CCValAssign - represent the assignment of the return value to a location.
2290 
2291  // CCState - Info about the registers and stack slots.
2292  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2293  *DAG.getContext());
2294 
2295  // Analyze outgoing return values.
2296  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2297 
2298  SDValue Flag;
2299  SmallVector<SDValue, 48> RetOps;
2300  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2301 
2302  // Add return address for callable functions.
2303  if (!Info->isEntryFunction()) {
2305  SDValue ReturnAddrReg = CreateLiveInRegister(
2306  DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2307 
2308  SDValue ReturnAddrVirtualReg = DAG.getRegister(
2309  MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2310  MVT::i64);
2311  Chain =
2312  DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2313  Flag = Chain.getValue(1);
2314  RetOps.push_back(ReturnAddrVirtualReg);
2315  }
2316 
2317  // Copy the result values into the output registers.
2318  for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2319  ++I, ++RealRVLocIdx) {
2320  CCValAssign &VA = RVLocs[I];
2321  assert(VA.isRegLoc() && "Can only return in registers!");
2322  // TODO: Partially return in registers if return values don't fit.
2323  SDValue Arg = OutVals[RealRVLocIdx];
2324 
2325  // Copied from other backends.
2326  switch (VA.getLocInfo()) {
2327  case CCValAssign::Full:
2328  break;
2329  case CCValAssign::BCvt:
2330  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2331  break;
2332  case CCValAssign::SExt:
2333  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2334  break;
2335  case CCValAssign::ZExt:
2336  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2337  break;
2338  case CCValAssign::AExt:
2339  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2340  break;
2341  default:
2342  llvm_unreachable("Unknown loc info!");
2343  }
2344 
2345  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2346  Flag = Chain.getValue(1);
2347  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2348  }
2349 
2350  // FIXME: Does sret work properly?
2351  if (!Info->isEntryFunction()) {
2352  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2353  const MCPhysReg *I =
2355  if (I) {
2356  for (; *I; ++I) {
2357  if (AMDGPU::SReg_64RegClass.contains(*I))
2358  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2359  else if (AMDGPU::SReg_32RegClass.contains(*I))
2360  RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2361  else
2362  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2363  }
2364  }
2365  }
2366 
2367  // Update chain and glue.
2368  RetOps[0] = Chain;
2369  if (Flag.getNode())
2370  RetOps.push_back(Flag);
2371 
2372  unsigned Opc = AMDGPUISD::ENDPGM;
2373  if (!IsWaveEnd)
2375  return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2376 }
2377 
2379  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2380  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2381  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2382  SDValue ThisVal) const {
2383  CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2384 
2385  // Assign locations to each value returned by this call.
2387  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2388  *DAG.getContext());
2389  CCInfo.AnalyzeCallResult(Ins, RetCC);
2390 
2391  // Copy all of the result registers out of their specified physreg.
2392  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2393  CCValAssign VA = RVLocs[i];
2394  SDValue Val;
2395 
2396  if (VA.isRegLoc()) {
2397  Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2398  Chain = Val.getValue(1);
2399  InFlag = Val.getValue(2);
2400  } else if (VA.isMemLoc()) {
2401  report_fatal_error("TODO: return values in memory");
2402  } else
2403  llvm_unreachable("unknown argument location type");
2404 
2405  switch (VA.getLocInfo()) {
2406  case CCValAssign::Full:
2407  break;
2408  case CCValAssign::BCvt:
2409  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2410  break;
2411  case CCValAssign::ZExt:
2412  Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2413  DAG.getValueType(VA.getValVT()));
2414  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2415  break;
2416  case CCValAssign::SExt:
2417  Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2418  DAG.getValueType(VA.getValVT()));
2419  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2420  break;
2421  case CCValAssign::AExt:
2422  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2423  break;
2424  default:
2425  llvm_unreachable("Unknown loc info!");
2426  }
2427 
2428  InVals.push_back(Val);
2429  }
2430 
2431  return Chain;
2432 }
2433 
2434 // Add code to pass special inputs required depending on used features separate
2435 // from the explicit user arguments present in the IR.
2437  CallLoweringInfo &CLI,
2438  CCState &CCInfo,
2439  const SIMachineFunctionInfo &Info,
2440  SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2441  SmallVectorImpl<SDValue> &MemOpChains,
2442  SDValue Chain) const {
2443  // If we don't have a call site, this was a call inserted by
2444  // legalization. These can never use special inputs.
2445  if (!CLI.CS)
2446  return;
2447 
2448  const Function *CalleeFunc = CLI.CS.getCalledFunction();
2449  assert(CalleeFunc);
2450 
2451  SelectionDAG &DAG = CLI.DAG;
2452  const SDLoc &DL = CLI.DL;
2453 
2454  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2455 
2456  auto &ArgUsageInfo =
2458  const AMDGPUFunctionArgInfo &CalleeArgInfo
2459  = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2460 
2461  const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2462 
2463  // TODO: Unify with private memory register handling. This is complicated by
2464  // the fact that at least in kernels, the input argument is not necessarily
2465  // in the same location as the input.
2475  };
2476 
2477  for (auto InputID : InputRegs) {
2478  const ArgDescriptor *OutgoingArg;
2479  const TargetRegisterClass *ArgRC;
2480 
2481  std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2482  if (!OutgoingArg)
2483  continue;
2484 
2485  const ArgDescriptor *IncomingArg;
2486  const TargetRegisterClass *IncomingArgRC;
2487  std::tie(IncomingArg, IncomingArgRC)
2488  = CallerArgInfo.getPreloadedValue(InputID);
2489  assert(IncomingArgRC == ArgRC);
2490 
2491  // All special arguments are ints for now.
2492  EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2493  SDValue InputReg;
2494 
2495  if (IncomingArg) {
2496  InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2497  } else {
2498  // The implicit arg ptr is special because it doesn't have a corresponding
2499  // input for kernels, and is computed from the kernarg segment pointer.
2500  assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2501  InputReg = getImplicitArgPtr(DAG, DL);
2502  }
2503 
2504  if (OutgoingArg->isRegister()) {
2505  RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2506  } else {
2507  unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2508  SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2509  SpecialArgOffset);
2510  MemOpChains.push_back(ArgStore);
2511  }
2512  }
2513 
2514  // Pack workitem IDs into a single register or pass it as is if already
2515  // packed.
2516  const ArgDescriptor *OutgoingArg;
2517  const TargetRegisterClass *ArgRC;
2518 
2519  std::tie(OutgoingArg, ArgRC) =
2520  CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2521  if (!OutgoingArg)
2522  std::tie(OutgoingArg, ArgRC) =
2523  CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2524  if (!OutgoingArg)
2525  std::tie(OutgoingArg, ArgRC) =
2526  CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2527  if (!OutgoingArg)
2528  return;
2529 
2530  const ArgDescriptor *IncomingArgX
2532  const ArgDescriptor *IncomingArgY
2534  const ArgDescriptor *IncomingArgZ
2536 
2537  SDValue InputReg;
2538  SDLoc SL;
2539 
2540  // If incoming ids are not packed we need to pack them.
2541  if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2542  InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2543 
2544  if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2545  SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2546  Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2547  DAG.getShiftAmountConstant(10, MVT::i32, SL));
2548  InputReg = InputReg.getNode() ?
2549  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2550  }
2551 
2552  if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2553  SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2554  Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2555  DAG.getShiftAmountConstant(20, MVT::i32, SL));
2556  InputReg = InputReg.getNode() ?
2557  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2558  }
2559 
2560  if (!InputReg.getNode()) {
2561  // Workitem ids are already packed, any of present incoming arguments
2562  // will carry all required fields.
2564  IncomingArgX ? *IncomingArgX :
2565  IncomingArgY ? *IncomingArgY :
2566  *IncomingArgZ, ~0u);
2567  InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2568  }
2569 
2570  if (OutgoingArg->isRegister()) {
2571  RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2572  } else {
2573  unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2574  SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2575  SpecialArgOffset);
2576  MemOpChains.push_back(ArgStore);
2577  }
2578 }
2579 
2581  return CC == CallingConv::Fast;
2582 }
2583 
2584 /// Return true if we might ever do TCO for calls with this calling convention.
2586  switch (CC) {
2587  case CallingConv::C:
2588  return true;
2589  default:
2590  return canGuaranteeTCO(CC);
2591  }
2592 }
2593 
2595  SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2596  const SmallVectorImpl<ISD::OutputArg> &Outs,
2597  const SmallVectorImpl<SDValue> &OutVals,
2598  const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2599  if (!mayTailCallThisCC(CalleeCC))
2600  return false;
2601 
2602  MachineFunction &MF = DAG.getMachineFunction();
2603  const Function &CallerF = MF.getFunction();
2604  CallingConv::ID CallerCC = CallerF.getCallingConv();
2606  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2607 
2608  // Kernels aren't callable, and don't have a live in return address so it
2609  // doesn't make sense to do a tail call with entry functions.
2610  if (!CallerPreserved)
2611  return false;
2612 
2613  bool CCMatch = CallerCC == CalleeCC;
2614 
2616  if (canGuaranteeTCO(CalleeCC) && CCMatch)
2617  return true;
2618  return false;
2619  }
2620 
2621  // TODO: Can we handle var args?
2622  if (IsVarArg)
2623  return false;
2624 
2625  for (const Argument &Arg : CallerF.args()) {
2626  if (Arg.hasByValAttr())
2627  return false;
2628  }
2629 
2630  LLVMContext &Ctx = *DAG.getContext();
2631 
2632  // Check that the call results are passed in the same way.
2633  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2634  CCAssignFnForCall(CalleeCC, IsVarArg),
2635  CCAssignFnForCall(CallerCC, IsVarArg)))
2636  return false;
2637 
2638  // The callee has to preserve all registers the caller needs to preserve.
2639  if (!CCMatch) {
2640  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2641  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2642  return false;
2643  }
2644 
2645  // Nothing more to check if the callee is taking no arguments.
2646  if (Outs.empty())
2647  return true;
2648 
2650  CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2651 
2652  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2653 
2654  const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2655  // If the stack arguments for this call do not fit into our own save area then
2656  // the call cannot be made tail.
2657  // TODO: Is this really necessary?
2658  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2659  return false;
2660 
2661  const MachineRegisterInfo &MRI = MF.getRegInfo();
2662  return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2663 }
2664 
2666  if (!CI->isTailCall())
2667  return false;
2668 
2669  const Function *ParentFn = CI->getParent()->getParent();
2670  if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2671  return false;
2672  return true;
2673 }
2674 
2675 // The wave scratch offset register is used as the global base pointer.
2677  SmallVectorImpl<SDValue> &InVals) const {
2678  SelectionDAG &DAG = CLI.DAG;
2679  const SDLoc &DL = CLI.DL;
2681  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2683  SDValue Chain = CLI.Chain;
2684  SDValue Callee = CLI.Callee;
2685  bool &IsTailCall = CLI.IsTailCall;
2686  CallingConv::ID CallConv = CLI.CallConv;
2687  bool IsVarArg = CLI.IsVarArg;
2688  bool IsSibCall = false;
2689  bool IsThisReturn = false;
2690  MachineFunction &MF = DAG.getMachineFunction();
2691 
2692  if (Callee.isUndef() || isNullConstant(Callee)) {
2693  if (!CLI.IsTailCall) {
2694  for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2695  InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2696  }
2697 
2698  return Chain;
2699  }
2700 
2701  if (IsVarArg) {
2702  return lowerUnhandledCall(CLI, InVals,
2703  "unsupported call to variadic function ");
2704  }
2705 
2706  if (!CLI.CS.getInstruction())
2707  report_fatal_error("unsupported libcall legalization");
2708 
2709  if (!CLI.CS.getCalledFunction()) {
2710  return lowerUnhandledCall(CLI, InVals,
2711  "unsupported indirect call to function ");
2712  }
2713 
2714  if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2715  return lowerUnhandledCall(CLI, InVals,
2716  "unsupported required tail call to function ");
2717  }
2718 
2720  // Note the issue is with the CC of the calling function, not of the call
2721  // itself.
2722  return lowerUnhandledCall(CLI, InVals,
2723  "unsupported call from graphics shader of function ");
2724  }
2725 
2726  if (IsTailCall) {
2727  IsTailCall = isEligibleForTailCallOptimization(
2728  Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2729  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2730  report_fatal_error("failed to perform tail call elimination on a call "
2731  "site marked musttail");
2732  }
2733 
2734  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2735 
2736  // A sibling call is one where we're under the usual C ABI and not planning
2737  // to change that but can still do a tail call:
2738  if (!TailCallOpt && IsTailCall)
2739  IsSibCall = true;
2740 
2741  if (IsTailCall)
2742  ++NumTailCalls;
2743  }
2744 
2746 
2747  // Analyze operands of the call, assigning locations to each operand.
2749  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2750  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2751 
2752  CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2753 
2754  // Get a count of how many bytes are to be pushed on the stack.
2755  unsigned NumBytes = CCInfo.getNextStackOffset();
2756 
2757  if (IsSibCall) {
2758  // Since we're not changing the ABI to make this a tail call, the memory
2759  // operands are already available in the caller's incoming argument space.
2760  NumBytes = 0;
2761  }
2762 
2763  // FPDiff is the byte offset of the call's argument area from the callee's.
2764  // Stores to callee stack arguments will be placed in FixedStackSlots offset
2765  // by this amount for a tail call. In a sibling call it must be 0 because the
2766  // caller will deallocate the entire stack and the callee still expects its
2767  // arguments to begin at SP+0. Completely unused for non-tail calls.
2768  int32_t FPDiff = 0;
2769  MachineFrameInfo &MFI = MF.getFrameInfo();
2771 
2772  // Adjust the stack pointer for the new arguments...
2773  // These operations are automatically eliminated by the prolog/epilog pass
2774  if (!IsSibCall) {
2775  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2776 
2777  SmallVector<SDValue, 4> CopyFromChains;
2778 
2779  // In the HSA case, this should be an identity copy.
2780  SDValue ScratchRSrcReg
2781  = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2782  RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2783  CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2784  Chain = DAG.getTokenFactor(DL, CopyFromChains);
2785  }
2786 
2787  SmallVector<SDValue, 8> MemOpChains;
2788  MVT PtrVT = MVT::i32;
2789 
2790  // Walk the register/memloc assignments, inserting copies/loads.
2791  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2792  CCValAssign &VA = ArgLocs[i];
2793  SDValue Arg = OutVals[i];
2794 
2795  // Promote the value if needed.
2796  switch (VA.getLocInfo()) {
2797  case CCValAssign::Full:
2798  break;
2799  case CCValAssign::BCvt:
2800  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2801  break;
2802  case CCValAssign::ZExt:
2803  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2804  break;
2805  case CCValAssign::SExt:
2806  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2807  break;
2808  case CCValAssign::AExt:
2809  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2810  break;
2811  case CCValAssign::FPExt:
2812  Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2813  break;
2814  default:
2815  llvm_unreachable("Unknown loc info!");
2816  }
2817 
2818  if (VA.isRegLoc()) {
2819  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2820  } else {
2821  assert(VA.isMemLoc());
2822 
2823  SDValue DstAddr;
2824  MachinePointerInfo DstInfo;
2825 
2826  unsigned LocMemOffset = VA.getLocMemOffset();
2827  int32_t Offset = LocMemOffset;
2828 
2829  SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2830  MaybeAlign Alignment;
2831 
2832  if (IsTailCall) {
2833  ISD::ArgFlagsTy Flags = Outs[i].Flags;
2834  unsigned OpSize = Flags.isByVal() ?
2835  Flags.getByValSize() : VA.getValVT().getStoreSize();
2836 
2837  // FIXME: We can have better than the minimum byval required alignment.
2838  Alignment =
2839  Flags.isByVal()
2840  ? MaybeAlign(Flags.getByValAlign())
2841  : commonAlignment(Subtarget->getStackAlignment(), Offset);
2842 
2843  Offset = Offset + FPDiff;
2844  int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2845 
2846  DstAddr = DAG.getFrameIndex(FI, PtrVT);
2847  DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2848 
2849  // Make sure any stack arguments overlapping with where we're storing
2850  // are loaded before this eventual operation. Otherwise they'll be
2851  // clobbered.
2852 
2853  // FIXME: Why is this really necessary? This seems to just result in a
2854  // lot of code to copy the stack and write them back to the same
2855  // locations, which are supposed to be immutable?
2856  Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2857  } else {
2858  DstAddr = PtrOff;
2859  DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2860  Alignment =
2861  commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2862  }
2863 
2864  if (Outs[i].Flags.isByVal()) {
2865  SDValue SizeNode =
2866  DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2867  SDValue Cpy = DAG.getMemcpy(
2868  Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2869  /*isVol = */ false, /*AlwaysInline = */ true,
2870  /*isTailCall = */ false, DstInfo,
2872 
2873  MemOpChains.push_back(Cpy);
2874  } else {
2875  SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2876  Alignment ? Alignment->value() : 0);
2877  MemOpChains.push_back(Store);
2878  }
2879  }
2880  }
2881 
2882  // Copy special input registers after user input arguments.
2883  passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2884 
2885  if (!MemOpChains.empty())
2886  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2887 
2888  // Build a sequence of copy-to-reg nodes chained together with token chain
2889  // and flag operands which copy the outgoing args into the appropriate regs.
2890  SDValue InFlag;
2891  for (auto &RegToPass : RegsToPass) {
2892  Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2893  RegToPass.second, InFlag);
2894  InFlag = Chain.getValue(1);
2895  }
2896 
2897 
2898  SDValue PhysReturnAddrReg;
2899  if (IsTailCall) {
2900  // Since the return is being combined with the call, we need to pass on the
2901  // return address.
2902 
2904  SDValue ReturnAddrReg = CreateLiveInRegister(
2905  DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2906 
2907  PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2908  MVT::i64);
2909  Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2910  InFlag = Chain.getValue(1);
2911  }
2912 
2913  // We don't usually want to end the call-sequence here because we would tidy
2914  // the frame up *after* the call, however in the ABI-changing tail-call case
2915  // we've carefully laid out the parameters so that when sp is reset they'll be
2916  // in the correct location.
2917  if (IsTailCall && !IsSibCall) {
2918  Chain = DAG.getCALLSEQ_END(Chain,
2919  DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2920  DAG.getTargetConstant(0, DL, MVT::i32),
2921  InFlag, DL);
2922  InFlag = Chain.getValue(1);
2923  }
2924 
2925  std::vector<SDValue> Ops;
2926  Ops.push_back(Chain);
2927  Ops.push_back(Callee);
2928  // Add a redundant copy of the callee global which will not be legalized, as
2929  // we need direct access to the callee later.
2930  GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2931  const GlobalValue *GV = GSD->getGlobal();
2932  Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2933 
2934  if (IsTailCall) {
2935  // Each tail call may have to adjust the stack by a different amount, so
2936  // this information must travel along with the operation for eventual
2937  // consumption by emitEpilogue.
2938  Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2939 
2940  Ops.push_back(PhysReturnAddrReg);
2941  }
2942 
2943  // Add argument registers to the end of the list so that they are known live
2944  // into the call.
2945  for (auto &RegToPass : RegsToPass) {
2946  Ops.push_back(DAG.getRegister(RegToPass.first,
2947  RegToPass.second.getValueType()));
2948  }
2949 
2950  // Add a register mask operand representing the call-preserved registers.
2951 
2952  auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2953  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2954  assert(Mask && "Missing call preserved mask for calling convention");
2955  Ops.push_back(DAG.getRegisterMask(Mask));
2956 
2957  if (InFlag.getNode())
2958  Ops.push_back(InFlag);
2959 
2960  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2961 
2962  // If we're doing a tall call, use a TC_RETURN here rather than an
2963  // actual call instruction.
2964  if (IsTailCall) {
2965  MFI.setHasTailCall();
2966  return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2967  }
2968 
2969  // Returns a chain and a flag for retval copy to use.
2970  SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2971  Chain = Call.getValue(0);
2972  InFlag = Call.getValue(1);
2973 
2974  uint64_t CalleePopBytes = NumBytes;
2975  Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2976  DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2977  InFlag, DL);
2978  if (!Ins.empty())
2979  InFlag = Chain.getValue(1);
2980 
2981  // Handle result values, copying them out of physregs into vregs that we
2982  // return.
2983  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2984  InVals, IsThisReturn,
2985  IsThisReturn ? OutVals[0] : SDValue());
2986 }
2987 
2989  const MachineFunction &MF) const {
2991  .Case("m0", AMDGPU::M0)
2992  .Case("exec", AMDGPU::EXEC)
2993  .Case("exec_lo", AMDGPU::EXEC_LO)
2994  .Case("exec_hi", AMDGPU::EXEC_HI)
2995  .Case("flat_scratch", AMDGPU::FLAT_SCR)
2996  .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2997  .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2998  .Default(Register());
2999 
3000  if (Reg == AMDGPU::NoRegister) {
3001  report_fatal_error(Twine("invalid register name \""
3002  + StringRef(RegName) + "\"."));
3003 
3004  }
3005 
3006  if (!Subtarget->hasFlatScrRegister() &&
3007  Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3008  report_fatal_error(Twine("invalid register \""
3009  + StringRef(RegName) + "\" for subtarget."));
3010  }
3011 
3012  switch (Reg) {
3013  case AMDGPU::M0:
3014  case AMDGPU::EXEC_LO:
3015  case AMDGPU::EXEC_HI:
3016  case AMDGPU::FLAT_SCR_LO:
3017  case AMDGPU::FLAT_SCR_HI:
3018  if (VT.getSizeInBits() == 32)
3019  return Reg;
3020  break;
3021  case AMDGPU::EXEC:
3022  case AMDGPU::FLAT_SCR:
3023  if (VT.getSizeInBits() == 64)
3024  return Reg;
3025  break;
3026  default:
3027  llvm_unreachable("missing register type checking");
3028  }
3029 
3030  report_fatal_error(Twine("invalid type for register \""
3031  + StringRef(RegName) + "\"."));
3032 }
3033 
3034 // If kill is not the last instruction, split the block so kill is always a
3035 // proper terminator.
3037  MachineBasicBlock *BB) const {
3038  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3039 
3040  MachineBasicBlock::iterator SplitPoint(&MI);
3041  ++SplitPoint;
3042 
3043  if (SplitPoint == BB->end()) {
3044  // Don't bother with a new block.
3046  return BB;
3047  }
3048 
3049  MachineFunction *MF = BB->getParent();
3050  MachineBasicBlock *SplitBB
3052 
3053  MF->insert(++MachineFunction::iterator(BB), SplitBB);
3054  SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3055 
3056  SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3057  BB->addSuccessor(SplitBB);
3058 
3060  return SplitBB;
3061 }
3062 
3063 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3064 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3065 // be the first instruction in the remainder block.
3066 //
3067 /// \returns { LoopBody, Remainder }
3068 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3070  MachineFunction *MF = MBB.getParent();
3072 
3073  // To insert the loop we need to split the block. Move everything after this
3074  // point to a new block, and insert a new empty block between the two.
3076  MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3077  MachineFunction::iterator MBBI(MBB);
3078  ++MBBI;
3079 
3080  MF->insert(MBBI, LoopBB);
3081  MF->insert(MBBI, RemainderBB);
3082 
3083  LoopBB->addSuccessor(LoopBB);
3084  LoopBB->addSuccessor(RemainderBB);
3085 
3086  // Move the rest of the block into a new block.
3087  RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3088 
3089  if (InstInLoop) {
3090  auto Next = std::next(I);
3091 
3092  // Move instruction to loop body.
3093  LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3094 
3095  // Move the rest of the block.
3096  RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3097  } else {
3098  RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3099  }
3100 
3101  MBB.addSuccessor(LoopBB);
3102 
3103  return std::make_pair(LoopBB, RemainderBB);
3104 }
3105 
3106 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3108  MachineBasicBlock *MBB = MI.getParent();
3109  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3110  auto I = MI.getIterator();
3111  auto E = std::next(I);
3112 
3113  BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3114  .addImm(0);
3115 
3116  MIBundleBuilder Bundler(*MBB, I, E);
3117  finalizeBundle(*MBB, Bundler.begin());
3118 }
3119 
3122  MachineBasicBlock *BB) const {
3123  const DebugLoc &DL = MI.getDebugLoc();
3124 
3126 
3127  MachineBasicBlock *LoopBB;
3128  MachineBasicBlock *RemainderBB;
3129  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3130 
3131  // Apparently kill flags are only valid if the def is in the same block?
3132  if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3133  Src->setIsKill(false);
3134 
3135  std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3136 
3137  MachineBasicBlock::iterator I = LoopBB->end();
3138 
3139  const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3141 
3142  // Clear TRAP_STS.MEM_VIOL
3143  BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3144  .addImm(0)
3145  .addImm(EncodedReg);
3146 
3148 
3149  Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3150 
3151  // Load and check TRAP_STS.MEM_VIOL
3152  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3153  .addImm(EncodedReg);
3154 
3155  // FIXME: Do we need to use an isel pseudo that may clobber scc?
3156  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3157  .addReg(Reg, RegState::Kill)
3158  .addImm(0);
3159  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3160  .addMBB(LoopBB);
3161 
3162  return RemainderBB;
3163 }
3164 
3165 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3166 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3167 // will only do one iteration. In the worst case, this will loop 64 times.
3168 //
3169 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3171  const SIInstrInfo *TII,
3173  MachineBasicBlock &OrigBB,
3174  MachineBasicBlock &LoopBB,
3175  const DebugLoc &DL,
3176  const MachineOperand &IdxReg,
3177  unsigned InitReg,
3178  unsigned ResultReg,
3179  unsigned PhiReg,
3180  unsigned InitSaveExecReg,
3181  int Offset,
3182  bool UseGPRIdxMode,
3183  bool IsIndirectSrc) {
3184  MachineFunction *MF = OrigBB.getParent();
3185  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3186  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3187  MachineBasicBlock::iterator I = LoopBB.begin();
3188 
3189  const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3190  Register PhiExec = MRI.createVirtualRegister(BoolRC);
3191  Register NewExec = MRI.createVirtualRegister(BoolRC);
3192  Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3193  Register CondReg = MRI.createVirtualRegister(BoolRC);
3194 
3195  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3196  .addReg(InitReg)
3197  .addMBB(&OrigBB)
3198  .addReg(ResultReg)
3199  .addMBB(&LoopBB);
3200 
3201  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3202  .addReg(InitSaveExecReg)
3203  .addMBB(&OrigBB)
3204  .addReg(NewExec)
3205  .addMBB(&LoopBB);
3206 
3207  // Read the next variant <- also loop target.
3208  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3209  .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3210 
3211  // Compare the just read M0 value to all possible Idx values.
3212  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3213  .addReg(CurrentIdxReg)
3214  .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3215 
3216  // Update EXEC, save the original EXEC value to VCC.
3217  BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3218  : AMDGPU::S_AND_SAVEEXEC_B64),
3219  NewExec)
3220  .addReg(CondReg, RegState::Kill);
3221 
3222  MRI.setSimpleHint(NewExec, CondReg);
3223 
3224  if (UseGPRIdxMode) {
3225  unsigned IdxReg;
3226  if (Offset == 0) {
3227  IdxReg = CurrentIdxReg;
3228  } else {
3229  IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3230  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3231  .addReg(CurrentIdxReg, RegState::Kill)
3232  .addImm(Offset);
3233  }
3234  unsigned IdxMode = IsIndirectSrc ?
3236  MachineInstr *SetOn =
3237  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3238  .addReg(IdxReg, RegState::Kill)
3239  .addImm(IdxMode);
3240  SetOn->getOperand(3).setIsUndef();
3241  } else {
3242  // Move index from VCC into M0
3243  if (Offset == 0) {
3244  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3245  .addReg(CurrentIdxReg, RegState::Kill);
3246  } else {
3247  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3248  .addReg(CurrentIdxReg, RegState::Kill)
3249  .addImm(Offset);
3250  }
3251  }
3252 
3253  // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3254  unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3255  MachineInstr *InsertPt =
3256  BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3257  : AMDGPU::S_XOR_B64_term), Exec)
3258  .addReg(Exec)
3259  .addReg(NewExec);
3260 
3261  // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3262  // s_cbranch_scc0?
3263 
3264  // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3265  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3266  .addMBB(&LoopBB);
3267 
3268  return InsertPt->getIterator();
3269 }
3270 
3271 // This has slightly sub-optimal regalloc when the source vector is killed by
3272 // the read. The register allocator does not understand that the kill is
3273 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3274 // subregister from it, using 1 more VGPR than necessary. This was saved when
3275 // this was expanded after register allocation.
3277  MachineBasicBlock &MBB,
3278  MachineInstr &MI,
3279  unsigned InitResultReg,
3280  unsigned PhiReg,
3281  int Offset,
3282  bool UseGPRIdxMode,
3283  bool IsIndirectSrc) {
3284  MachineFunction *MF = MBB.getParent();
3285  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3286  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3288  const DebugLoc &DL = MI.getDebugLoc();
3290 
3291  const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3292  Register DstReg = MI.getOperand(0).getReg();
3293  Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3294  Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3295  unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3296  unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3297 
3298  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3299 
3300  // Save the EXEC mask
3301  BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3302  .addReg(Exec);
3303 
3304  MachineBasicBlock *LoopBB;
3305  MachineBasicBlock *RemainderBB;
3306  std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3307 
3308  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3309 
3310  auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3311  InitResultReg, DstReg, PhiReg, TmpExec,
3312  Offset, UseGPRIdxMode, IsIndirectSrc);
3313 
3314  MachineBasicBlock::iterator First = RemainderBB->begin();
3315  BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3316  .addReg(SaveExec);
3317 
3318  return InsPt;
3319 }
3320 
3321 // Returns subreg index, offset
3322 static std::pair<unsigned, int>
3324  const TargetRegisterClass *SuperRC,
3325  unsigned VecReg,
3326  int Offset) {
3327  int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3328 
3329  // Skip out of bounds offsets, or else we would end up using an undefined
3330  // register.
3331  if (Offset >= NumElts || Offset < 0)
3332  return std::make_pair(AMDGPU::sub0, Offset);
3333 
3334  return std::make_pair(AMDGPU::sub0 + Offset, 0);
3335 }
3336 
3337 // Return true if the index is an SGPR and was set.
3340  MachineInstr &MI,
3341  int Offset,
3342  bool UseGPRIdxMode,
3343  bool IsIndirectSrc) {
3344  MachineBasicBlock *MBB = MI.getParent();
3345  const DebugLoc &DL = MI.getDebugLoc();
3347 
3348  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3349  const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3350 
3351  assert(Idx->getReg() != AMDGPU::NoRegister);
3352 
3353  if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3354  return false;
3355 
3356  if (UseGPRIdxMode) {
3357  unsigned IdxMode = IsIndirectSrc ?
3359  if (Offset == 0) {
3360  MachineInstr *SetOn =
3361  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3362  .add(*Idx)
3363  .addImm(IdxMode);
3364 
3365  SetOn->getOperand(3).setIsUndef();
3366  } else {
3367  Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3368  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3369  .add(*Idx)
3370  .addImm(Offset);
3371  MachineInstr *SetOn =
3372  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3373  .addReg(Tmp, RegState::Kill)
3374  .addImm(IdxMode);
3375 
3376  SetOn->getOperand(3).setIsUndef();
3377  }
3378 
3379  return true;
3380  }
3381 
3382  if (Offset == 0) {
3383  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3384  .add(*Idx);
3385  } else {
3386  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3387  .add(*Idx)
3388  .addImm(Offset);
3389  }
3390 
3391  return true;
3392 }
3393 
3394 // Control flow needs to be inserted if indexing with a VGPR.
3396  MachineBasicBlock &MBB,
3397  const GCNSubtarget &ST) {
3398  const SIInstrInfo *TII = ST.getInstrInfo();
3399  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3400  MachineFunction *MF = MBB.getParent();
3402 
3403  Register Dst = MI.getOperand(0).getReg();
3404  Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3405  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3406 
3407  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3408 
3409  unsigned SubReg;
3410  std::tie(SubReg, Offset)
3411  = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3412 
3413  const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3414 
3415  if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3417  const DebugLoc &DL = MI.getDebugLoc();
3418 
3419  if (UseGPRIdxMode) {
3420  // TODO: Look at the uses to avoid the copy. This may require rescheduling
3421  // to avoid interfering with other uses, so probably requires a new
3422  // optimization pass.
3423  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3424  .addReg(SrcReg, RegState::Undef, SubReg)
3425  .addReg(SrcReg, RegState::Implicit)
3426  .addReg(AMDGPU::M0, RegState::Implicit);
3427  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3428  } else {
3429  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3430  .addReg(SrcReg, RegState::Undef, SubReg)
3431  .addReg(SrcReg, RegState::Implicit);
3432  }
3433 
3434  MI.eraseFromParent();
3435 
3436  return &MBB;
3437  }
3438 
3439  const DebugLoc &DL = MI.getDebugLoc();
3441 
3442  Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3443  Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3444 
3445  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3446 
3447  auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3448  Offset, UseGPRIdxMode, true);
3449  MachineBasicBlock *LoopBB = InsPt->getParent();
3450 
3451  if (UseGPRIdxMode) {
3452  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3453  .addReg(SrcReg, RegState::Undef, SubReg)
3454  .addReg(SrcReg, RegState::Implicit)
3455  .addReg(AMDGPU::M0, RegState::Implicit);
3456  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3457  } else {
3458  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3459  .addReg(SrcReg, RegState::Undef, SubReg)
3460  .addReg(SrcReg, RegState::Implicit);
3461  }
3462 
3463  MI.eraseFromParent();
3464 
3465  return LoopBB;
3466 }
3467 
3468 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3469  const TargetRegisterClass *VecRC) {
3470  switch (TRI.getRegSizeInBits(*VecRC)) {
3471  case 32: // 4 bytes
3472  return AMDGPU::V_MOVRELD_B32_V1;
3473  case 64: // 8 bytes
3474  return AMDGPU::V_MOVRELD_B32_V2;
3475  case 128: // 16 bytes
3476  return AMDGPU::V_MOVRELD_B32_V4;
3477  case 256: // 32 bytes
3478  return AMDGPU::V_MOVRELD_B32_V8;
3479  case 512: // 64 bytes
3480  return AMDGPU::V_MOVRELD_B32_V16;
3481  default:
3482  llvm_unreachable("unsupported size for MOVRELD pseudos");
3483  }
3484 }
3485 
3487  MachineBasicBlock &MBB,
3488  const GCNSubtarget &ST) {
3489  const SIInstrInfo *TII = ST.getInstrInfo();
3490  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3491  MachineFunction *MF = MBB.getParent();
3493 
3494  Register Dst = MI.getOperand(0).getReg();
3495  const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3496  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3497  const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3498  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3499  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3500 
3501  // This can be an immediate, but will be folded later.
3502  assert(Val->getReg());
3503 
3504  unsigned SubReg;
3505  std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3506  SrcVec->getReg(),
3507  Offset);
3508  const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3509 
3510  if (Idx->getReg() == AMDGPU::NoRegister) {
3512  const DebugLoc &DL = MI.getDebugLoc();
3513 
3514  assert(Offset == 0);
3515 
3516  BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3517  .add(*SrcVec)
3518  .add(*Val)
3519  .addImm(SubReg);
3520 
3521  MI.eraseFromParent();
3522  return &MBB;
3523  }
3524 
3525  if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3527  const DebugLoc &DL = MI.getDebugLoc();
3528 
3529  if (UseGPRIdxMode) {
3530  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3531  .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3532  .add(*Val)
3533  .addReg(Dst, RegState::ImplicitDefine)
3534  .addReg(SrcVec->getReg(), RegState::Implicit)
3535  .addReg(AMDGPU::M0, RegState::Implicit);
3536 
3537  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3538  } else {
3539  const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3540 
3541  BuildMI(MBB, I, DL, MovRelDesc)
3542  .addReg(Dst, RegState::Define)
3543  .addReg(SrcVec->getReg())
3544  .add(*Val)
3545  .addImm(SubReg - AMDGPU::sub0);
3546  }
3547 
3548  MI.eraseFromParent();
3549  return &MBB;
3550  }
3551 
3552  if (Val->isReg())
3553  MRI.clearKillFlags(Val->getReg());
3554 
3555  const DebugLoc &DL = MI.getDebugLoc();
3556 
3557  Register PhiReg = MRI.createVirtualRegister(VecRC);
3558 
3559  auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3560  Offset, UseGPRIdxMode, false);
3561  MachineBasicBlock *LoopBB = InsPt->getParent();
3562 
3563  if (UseGPRIdxMode) {
3564  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3565  .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3566  .add(*Val) // src0
3568  .addReg(PhiReg, RegState::Implicit)
3569  .addReg(AMDGPU::M0, RegState::Implicit);
3570  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3571  } else {
3572  const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3573 
3574  BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3575  .addReg(Dst, RegState::Define)
3576  .addReg(PhiReg)
3577  .add(*Val)
3578  .addImm(SubReg - AMDGPU::sub0);
3579  }
3580 
3581  MI.eraseFromParent();
3582 
3583  return LoopBB;
3584 }
3585 
3587  MachineInstr &MI, MachineBasicBlock *BB) const {
3588 
3589  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3590  MachineFunction *MF = BB->getParent();
3592 
3593  if (TII->isMIMG(MI)) {
3594  if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3595  report_fatal_error("missing mem operand from MIMG instruction");
3596  }
3597  // Add a memoperand for mimg instructions so that they aren't assumed to
3598  // be ordered memory instuctions.
3599 
3600  return BB;
3601  }
3602 
3603  switch (MI.getOpcode()) {
3604  case AMDGPU::S_ADD_U64_PSEUDO:
3605  case AMDGPU::S_SUB_U64_PSEUDO: {
3607  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3608  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3609  const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3610  const DebugLoc &DL = MI.getDebugLoc();
3611 
3612  MachineOperand &Dest = MI.getOperand(0);
3613  MachineOperand &Src0 = MI.getOperand(1);
3614  MachineOperand &Src1 = MI.getOperand(2);
3615 
3616  Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3617  Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3618 
3619  MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3620  Src0, BoolRC, AMDGPU::sub0,
3621  &AMDGPU::SReg_32RegClass);
3622  MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3623  Src0, BoolRC, AMDGPU::sub1,
3624  &AMDGPU::SReg_32RegClass);
3625 
3626  MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3627  Src1, BoolRC, AMDGPU::sub0,
3628  &AMDGPU::SReg_32RegClass);
3629  MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3630  Src1, BoolRC, AMDGPU::sub1,
3631  &AMDGPU::SReg_32RegClass);
3632 
3633  bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3634 
3635  unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3636  unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3637  BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3638  .add(Src0Sub0)
3639  .add(Src1Sub0);
3640  BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3641  .add(Src0Sub1)
3642  .add(Src1Sub1);
3643  BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3644  .addReg(DestSub0)
3645  .addImm(AMDGPU::sub0)
3646  .addReg(DestSub1)
3647  .addImm(AMDGPU::sub1);
3648  MI.eraseFromParent();
3649  return BB;
3650  }
3651  case AMDGPU::SI_INIT_M0: {
3652  BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3653  TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3654  .add(MI.getOperand(0));
3655  MI.eraseFromParent();
3656  return BB;
3657  }
3658  case AMDGPU::SI_INIT_EXEC:
3659  // This should be before all vector instructions.
3660  BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3661  AMDGPU::EXEC)
3662  .addImm(MI.getOperand(0).getImm());
3663  MI.eraseFromParent();
3664  return BB;
3665 
3666  case AMDGPU::SI_INIT_EXEC_LO:
3667  // This should be before all vector instructions.
3668  BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3669  AMDGPU::EXEC_LO)
3670  .addImm(MI.getOperand(0).getImm());
3671  MI.eraseFromParent();
3672  return BB;
3673 
3674  case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3675  // Extract the thread count from an SGPR input and set EXEC accordingly.
3676  // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3677  //
3678  // S_BFE_U32 count, input, {shift, 7}
3679  // S_BFM_B64 exec, count, 0
3680  // S_CMP_EQ_U32 count, 64
3681  // S_CMOV_B64 exec, -1
3682  MachineInstr *FirstMI = &*BB->begin();
3684  Register InputReg = MI.getOperand(0).getReg();
3685  Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3686  bool Found = false;
3687 
3688  // Move the COPY of the input reg to the beginning, so that we can use it.
3689  for (auto I = BB->begin(); I != &MI; I++) {
3690  if (I->getOpcode() != TargetOpcode::COPY ||
3691  I->getOperand(0).getReg() != InputReg)
3692  continue;
3693 
3694  if (I == FirstMI) {
3695  FirstMI = &*++BB->begin();
3696  } else {
3697  I->removeFromParent();
3698  BB->insert(FirstMI, &*I);
3699  }
3700  Found = true;
3701  break;
3702  }
3703  assert(Found);
3704  (void)Found;
3705 
3706  // This should be before all vector instructions.
3707  unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3708  bool isWave32 = getSubtarget()->isWave32();
3709  unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3710  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3711  .addReg(InputReg)
3712  .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3713  BuildMI(*BB, FirstMI, DebugLoc(),
3714  TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3715  Exec)
3716  .addReg(CountReg)
3717  .addImm(0);
3718  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3719  .addReg(CountReg, RegState::Kill)
3721  BuildMI(*BB, FirstMI, DebugLoc(),
3722  TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3723  Exec)
3724  .addImm(-1);
3725  MI.eraseFromParent();
3726  return BB;
3727  }
3728 
3729  case AMDGPU::GET_GROUPSTATICSIZE: {
3730  assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3731  getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3732  DebugLoc DL = MI.getDebugLoc();
3733  BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3734  .add(MI.getOperand(0))
3735  .addImm(MFI->getLDSSize());
3736  MI.eraseFromParent();
3737  return BB;
3738  }
3739  case AMDGPU::SI_INDIRECT_SRC_V1:
3740  case AMDGPU::SI_INDIRECT_SRC_V2:
3741  case AMDGPU::SI_INDIRECT_SRC_V4:
3742  case AMDGPU::SI_INDIRECT_SRC_V8:
3743  case AMDGPU::SI_INDIRECT_SRC_V16:
3744  return emitIndirectSrc(MI, *BB, *getSubtarget());
3745  case AMDGPU::SI_INDIRECT_DST_V1:
3746  case AMDGPU::SI_INDIRECT_DST_V2:
3747  case AMDGPU::SI_INDIRECT_DST_V4:
3748  case AMDGPU::SI_INDIRECT_DST_V8:
3749  case AMDGPU::SI_INDIRECT_DST_V16:
3750  return emitIndirectDst(MI, *BB, *getSubtarget());
3751  case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3752  case AMDGPU::SI_KILL_I1_PSEUDO:
3753  return splitKillBlock(MI, BB);
3754  case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3756  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3757  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3758 
3759  Register Dst = MI.getOperand(0).getReg();
3760  Register Src0 = MI.getOperand(1).getReg();
3761  Register Src1 = MI.getOperand(2).getReg();
3762  const DebugLoc &DL = MI.getDebugLoc();
3763  Register SrcCond = MI.getOperand(3).getReg();
3764 
3765  Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3766  Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3767  const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3768  Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3769 
3770  BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3771  .addReg(SrcCond);
3772  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3773  .addImm(0)
3774  .addReg(Src0, 0, AMDGPU::sub0)
3775  .addImm(0)
3776  .addReg(Src1, 0, AMDGPU::sub0)
3777  .addReg(SrcCondCopy);
3778  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3779  .addImm(0)
3780  .addReg(Src0, 0, AMDGPU::sub1)
3781  .addImm(0)
3782  .addReg(Src1, 0, AMDGPU::sub1)
3783  .addReg(SrcCondCopy);
3784 
3785  BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3786  .addReg(DstLo)
3787  .addImm(AMDGPU::sub0)
3788  .addReg(DstHi)
3789  .addImm(AMDGPU::sub1);
3790  MI.eraseFromParent();
3791  return BB;
3792  }
3793  case AMDGPU::SI_BR_UNDEF: {
3794  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3795  const DebugLoc &DL = MI.getDebugLoc();
3796  MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3797  .add(MI.getOperand(0));
3798  Br->getOperand(1).setIsUndef(true); // read undef SCC
3799  MI.eraseFromParent();
3800  return BB;
3801  }
3802  case AMDGPU::ADJCALLSTACKUP:
3803  case AMDGPU::ADJCALLSTACKDOWN: {
3805  MachineInstrBuilder MIB(*MF, &MI);
3806 
3807  // Add an implicit use of the frame offset reg to prevent the restore copy
3808  // inserted after the call from being reorderd after stack operations in the
3809  // the caller's frame.
3810  MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3811  .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3812  .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3813  return BB;
3814  }
3815  case AMDGPU::SI_CALL_ISEL: {
3816  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3817  const DebugLoc &DL = MI.getDebugLoc();
3818 
3819  unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3820 
3821  MachineInstrBuilder MIB;
3822  MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3823 
3824  for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3825  MIB.add(MI.getOperand(I));
3826 
3827  MIB.cloneMemRefs(MI);
3828  MI.eraseFromParent();
3829  return BB;
3830  }
3831  case AMDGPU::V_ADD_I32_e32:
3832  case AMDGPU::V_SUB_I32_e32:
3833  case AMDGPU::V_SUBREV_I32_e32: {
3834  // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3835  const DebugLoc &DL = MI.getDebugLoc();
3836  unsigned Opc = MI.getOpcode();
3837 
3838  bool NeedClampOperand = false;
3839  if (TII->pseudoToMCOpcode(Opc) == -1) {
3840  Opc = AMDGPU::getVOPe64(Opc);
3841  NeedClampOperand = true;
3842  }
3843 
3844  auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3845  if (TII->isVOP3(*I)) {
3846  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3847  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3848  I.addReg(TRI->getVCC(), RegState::Define);
3849  }
3850  I.add(MI.getOperand(1))
3851  .add(MI.getOperand(2));
3852  if (NeedClampOperand)
3853  I.addImm(0); // clamp bit for e64 encoding
3854 
3855  TII->legalizeOperands(*I);
3856 
3857  MI.eraseFromParent();
3858  return BB;
3859  }
3860  case AMDGPU::DS_GWS_INIT:
3861  case AMDGPU::DS_GWS_SEMA_V:
3862  case AMDGPU::DS_GWS_SEMA_BR:
3863  case AMDGPU::DS_GWS_SEMA_P:
3864  case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3865  case AMDGPU::DS_GWS_BARRIER:
3866  // A s_waitcnt 0 is required to be the instruction immediately following.
3867  if (getSubtarget()->hasGWSAutoReplay()) {
3869  return BB;
3870  }
3871 
3872  return emitGWSMemViolTestLoop(MI, BB);
3873  default:
3875  }
3876 }
3877 
3879  return isTypeLegal(VT.getScalarType());
3880 }
3881 
3883  // This currently forces unfolding various combinations of fsub into fma with
3884  // free fneg'd operands. As long as we have fast FMA (controlled by
3885  // isFMAFasterThanFMulAndFAdd), we should perform these.
3886 
3887  // When fma is quarter rate, for f64 where add / sub are at best half rate,
3888  // most of these combines appear to be cycle neutral but save on instruction
3889  // count / code size.
3890  return true;
3891 }
3892 
3894  EVT VT) const {
3895  if (!VT.isVector()) {
3896  return MVT::i1;
3897  }
3898  return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3899 }
3900 
3902  // TODO: Should i16 be used always if legal? For now it would force VALU
3903  // shifts.
3904  return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3905 }
3906 
3907 // Answering this is somewhat tricky and depends on the specific device which
3908 // have different rates for fma or all f64 operations.
3909 //
3910 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3911 // regardless of which device (although the number of cycles differs between
3912 // devices), so it is always profitable for f64.
3913 //
3914 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3915 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3916 // which we can always do even without fused FP ops since it returns the same
3917 // result as the separate operations and since it is always full
3918 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3919 // however does not support denormals, so we do report fma as faster if we have
3920 // a fast fma device and require denormals.
3921 //
3923  EVT VT) const {
3924  VT = VT.getScalarType();
3925 
3926  switch (VT.getSimpleVT().SimpleTy) {
3927  case MVT::f32: {
3928  // This is as fast on some subtargets. However, we always have full rate f32
3929  // mad available which returns the same result as the separate operations
3930  // which we should prefer over fma. We can't use this if we want to support
3931  // denormals, so only report this in these cases.
3932  if (hasFP32Denormals(MF))
3933  return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3934 
3935  // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3936  return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3937  }
3938  case MVT::f64:
3939  return true;
3940  case MVT::f16:
3941  return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3942  default:
3943  break;
3944  }
3945 
3946  return false;
3947 }
3948 
3950  const SDNode *N) const {
3951  // TODO: Check future ftz flag
3952  // v_mad_f32/v_mac_f32 do not support denormals.
3953  EVT VT = N->getValueType(0);
3954  if (VT == MVT::f32)
3955  return !hasFP32Denormals(DAG.getMachineFunction());
3956  if (VT == MVT::f16) {
3957  return Subtarget->hasMadF16() &&
3959  }
3960 
3961  return false;
3962 }
3963 
3964 //===----------------------------------------------------------------------===//
3965 // Custom DAG Lowering Operations
3966 //===----------------------------------------------------------------------===//
3967 
3968 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3969 // wider vector type is legal.
3971  SelectionDAG &DAG) const {
3972  unsigned Opc = Op.getOpcode();
3973  EVT VT = Op.getValueType();
3974  assert(VT == MVT::v4f16);
3975 
3976  SDValue Lo, Hi;
3977  std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3978 
3979  SDLoc SL(Op);
3980  SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3981  Op->getFlags());
3982  SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3983  Op->getFlags());
3984 
3985  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3986 }
3987 
3988 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3989 // wider vector type is legal.
3991  SelectionDAG &DAG) const {
3992  unsigned Opc = Op.getOpcode();
3993  EVT VT = Op.getValueType();
3994  assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3995 
3996  SDValue Lo0, Hi0;
3997  std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3998  SDValue Lo1, Hi1;
3999  std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4000 
4001  SDLoc SL(Op);
4002 
4003  SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4004  Op->getFlags());
4005  SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4006  Op->getFlags());
4007 
4008  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4009 }
4010 
4012  SelectionDAG &DAG) const {
4013  unsigned Opc = Op.getOpcode();
4014  EVT VT = Op.getValueType();
4015  assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4016 
4017  SDValue Lo0, Hi0;
4018  std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4019  SDValue Lo1, Hi1;
4020  std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4021  SDValue Lo2, Hi2;
4022  std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4023 
4024  SDLoc SL(Op);
4025 
4026  SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4027  Op->getFlags());
4028  SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4029  Op->getFlags());
4030 
4031  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4032 }
4033 
4034 
4036  switch (Op.getOpcode()) {
4037  default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4038  case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4039  case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4040  case ISD::LOAD: {
4041  SDValue Result = LowerLOAD(Op, DAG);
4042  assert((!Result.getNode() ||
4043  Result.getNode()->getNumValues() == 2) &&
4044  "Load should return a value and a chain");
4045  return Result;
4046  }
4047 
4048  case ISD::FSIN:
4049  case ISD::FCOS:
4050  return LowerTrig(Op, DAG);
4051  case ISD::SELECT: return LowerSELECT(Op, DAG);
4052  case ISD::FDIV: return LowerFDIV(Op, DAG);
4053  case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4054  case ISD::STORE: return LowerSTORE(Op, DAG);
4055  case ISD::GlobalAddress: {
4056  MachineFunction &MF = DAG.getMachineFunction();
4058  return LowerGlobalAddress(MFI, Op, DAG);
4059  }
4060  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4061  case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4062  case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4063  case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4064  case ISD::INSERT_SUBVECTOR:
4065  return lowerINSERT_SUBVECTOR(Op, DAG);
4067  return lowerINSERT_VECTOR_ELT(Op, DAG);
4069  return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4070  case ISD::VECTOR_SHUFFLE:
4071  return lowerVECTOR_SHUFFLE(Op, DAG);
4072  case ISD::BUILD_VECTOR:
4073  return lowerBUILD_VECTOR(Op, DAG);
4074  case ISD::FP_ROUND:
4075  return lowerFP_ROUND(Op, DAG);
4076  case ISD::TRAP:
4077  return lowerTRAP(Op, DAG);
4078  case ISD::DEBUGTRAP:
4079  return lowerDEBUGTRAP(Op, DAG);
4080  case ISD::FABS:
4081  case ISD::FNEG:
4082  case ISD::FCANONICALIZE:
4083  return splitUnaryVectorOp(Op, DAG);
4084  case ISD::FMINNUM:
4085  case ISD::FMAXNUM:
4086  return lowerFMINNUM_FMAXNUM(Op, DAG);
4087  case ISD::FMA:
4088  return splitTernaryVectorOp(Op, DAG);
4089  case ISD::SHL:
4090  case ISD::SRA:
4091  case ISD::SRL:
4092  case ISD::ADD:
4093  case ISD::SUB:
4094  case ISD::MUL:
4095  case ISD::SMIN:
4096  case ISD::SMAX:
4097  case ISD::UMIN:
4098  case ISD::UMAX:
4099  case ISD::FADD:
4100  case ISD::FMUL:
4101  case ISD::FMINNUM_IEEE:
4102  case ISD::FMAXNUM_IEEE:
4103  return splitBinaryVectorOp(Op, DAG);
4104  }
4105  return SDValue();
4106 }
4107 
4109  const SDLoc &DL,
4110  SelectionDAG &DAG, bool Unpacked) {
4111  if (!LoadVT.isVector())
4112  return Result;
4113 
4114  if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4115  // Truncate to v2i16/v4i16.
4116  EVT IntLoadVT = LoadVT.changeTypeToInteger();
4117 
4118  // Workaround legalizer not scalarizing truncate after vector op
4119  // legalization byt not creating intermediate vector trunc.
4121  DAG.ExtractVectorElements(Result, Elts);
4122  for (SDValue &Elt : Elts)
4123  Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4124 
4125  Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4126 
4127  // Bitcast to original type (v2f16/v4f16).
4128  return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4129  }
4130 
4131  // Cast back to the original packed type.
4132  return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4133 }
4134 
4135 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4136  MemSDNode *M,
4137  SelectionDAG &DAG,
4138  ArrayRef<SDValue> Ops,
4139  bool IsIntrinsic) const {
4140  SDLoc DL(M);
4141 
4142  bool Unpacked = Subtarget->hasUnpackedD16VMem();
4143  EVT LoadVT = M->getValueType(0);
4144 
4145  EVT EquivLoadVT = LoadVT;
4146  if (Unpacked && LoadVT.isVector()) {
4147  EquivLoadVT = LoadVT.isVector() ?
4149  LoadVT.getVectorNumElements()) : LoadVT;
4150  }
4151 
4152  // Change from v4f16/v2f16 to EquivLoadVT.
4153  SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4154 
4155  SDValue Load
4156  = DAG.getMemIntrinsicNode(
4157  IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4158  VTList, Ops, M->getMemoryVT(),
4159  M->getMemOperand());
4160  if (!Unpacked) // Just adjusted the opcode.
4161  return Load;
4162 
4163  SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4164 
4165  return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4166 }
4167 
4168 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4169  SelectionDAG &DAG,
4170  ArrayRef<SDValue> Ops) const {
4171  SDLoc DL(M);
4172  EVT LoadVT = M->getValueType(0);
4173  EVT EltType = LoadVT.getScalarType();
4174  EVT IntVT = LoadVT.changeTypeToInteger();
4175 
4176  bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4177 
4178  unsigned Opc =
4180 
4181  if (IsD16) {
4182  return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4183  }
4184 
4185  // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4186  if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4187  return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4188 
4189  if (isTypeLegal(LoadVT)) {
4190  return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4191  M->getMemOperand(), DAG);
4192  }
4193 
4194  EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4195  SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4196  SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4197  M->getMemOperand(), DAG);
4198  return DAG.getMergeValues(
4199  {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4200  DL);
4201 }
4202 
4204  SDNode *N, SelectionDAG &DAG) {
4205  EVT VT = N->getValueType(0);
4206  const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4207  int CondCode = CD->getSExtValue();
4208  if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4209  CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4210  return DAG.getUNDEF(VT);
4211 
4212  ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4213 
4214  SDValue LHS = N->getOperand(1);
4215  SDValue RHS = N->getOperand(2);
4216 
4217  SDLoc DL(N);
4218 
4219  EVT CmpVT = LHS.getValueType();
4220  if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4221  unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4223  LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4224  RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4225  }
4226 
4227  ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4228 
4229  unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4231 
4232  SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4233  DAG.getCondCode(CCOpcode));
4234  if (VT.bitsEq(CCVT))
4235  return SetCC;
4236  return DAG.getZExtOrTrunc(SetCC, DL, VT);
4237 }
4238 
4240  SDNode *N, SelectionDAG &DAG) {
4241  EVT VT = N->getValueType(0);
4242  const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4243 
4244  int CondCode = CD->getSExtValue();
4245  if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4246  CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4247  return DAG.getUNDEF(VT);
4248  }
4249 
4250  SDValue Src0 = N->getOperand(1);
4251  SDValue Src1 = N->getOperand(2);
4252  EVT CmpVT = Src0.getValueType();
4253  SDLoc SL(N);
4254 
4255  if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4256  Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4257  Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4258  }
4259 
4260  FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4261  ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4262  unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4264  SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4265  Src1, DAG.getCondCode(CCOpcode));
4266  if (VT.bitsEq(CCVT))
4267  return SetCC;
4268  return DAG.getZExtOrTrunc(SetCC, SL, VT);
4269 }
4270 
4273  SelectionDAG &DAG) const {
4274  switch (N->getOpcode()) {
4275  case ISD::INSERT_VECTOR_ELT: {
4276  if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4277  Results.push_back(Res);
4278  return;
4279  }
4280  case ISD::EXTRACT_VECTOR_ELT: {
4281  if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4282  Results.push_back(Res);
4283  return;
4284  }
4285  case ISD::INTRINSIC_WO_CHAIN: {
4286  unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4287  switch (IID) {
4288  case Intrinsic::amdgcn_cvt_pkrtz: {
4289  SDValue Src0 = N->getOperand(1);
4290  SDValue Src1 = N->getOperand(2);
4291  SDLoc SL(N);
4293  Src0, Src1);
4294  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4295  return;
4296  }
4297  case Intrinsic::amdgcn_cvt_pknorm_i16:
4298  case Intrinsic::amdgcn_cvt_pknorm_u16:
4299  case Intrinsic::amdgcn_cvt_pk_i16:
4300  case Intrinsic::amdgcn_cvt_pk_u16: {
4301  SDValue Src0 = N->getOperand(1);
4302  SDValue Src1 = N->getOperand(2);
4303  SDLoc SL(N);
4304  unsigned Opcode;
4305 
4306  if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4308  else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4310  else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4311  Opcode = AMDGPUISD::CVT_PK_I16_I32;
4312  else
4313  Opcode = AMDGPUISD::CVT_PK_U16_U32;
4314 
4315  EVT VT = N->getValueType(0);
4316  if (isTypeLegal(VT))
4317  Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4318  else {
4319  SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4320  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4321  }
4322  return;
4323  }
4324  }
4325  break;
4326  }
4327  case ISD::INTRINSIC_W_CHAIN: {
4328  if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4329  if (Res.getOpcode() == ISD::MERGE_VALUES) {
4330  // FIXME: Hacky
4331  Results.push_back(Res.getOperand(0));
4332  Results.push_back(Res.getOperand(1));
4333  } else {
4334  Results.push_back(Res);
4335  Results.push_back(Res.getValue(1));
4336  }
4337  return;
4338  }
4339 
4340  break;
4341  }
4342  case ISD::SELECT: {
4343  SDLoc SL(N);
4344  EVT VT = N->getValueType(0);
4345  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4346  SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4347  SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4348 
4349  EVT SelectVT = NewVT;
4350  if (NewVT.bitsLT(MVT::i32)) {
4351  LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4352  RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4353  SelectVT = MVT::i32;
4354  }
4355 
4356  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4357  N->getOperand(0), LHS, RHS);
4358 
4359  if (NewVT != SelectVT)
4360  NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4361  Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4362  return;
4363  }
4364  case ISD::FNEG: {
4365  if (N->getValueType(0) != MVT::v2f16)
4366  break;
4367 
4368  SDLoc SL(N);
4369  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4370 
4371  SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4372  BC,
4373  DAG.getConstant(0x80008000, SL, MVT::i32));
4374  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4375  return;
4376  }
4377  case ISD::FABS: {
4378  if (N->getValueType(0) != MVT::v2f16)
4379  break;
4380 
4381  SDLoc SL(N);
4382  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4383 
4384  SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4385  BC,
4386  DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4387  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4388  return;
4389  }
4390  default:
4391  break;
4392  }
4393 }
4394 
4395 /// Helper function for LowerBRCOND
4396 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4397 
4398  SDNode *Parent = Value.getNode();
4399  for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4400  I != E; ++I) {
4401 
4402  if (I.getUse().get() != Value)
4403  continue;
4404 
4405  if (I->getOpcode() == Opcode)
4406  return *I;
4407  }
4408  return nullptr;
4409 }
4410 
4411 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4412  if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4413  switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4414  case Intrinsic::amdgcn_if:
4415  return AMDGPUISD::IF;
4416  case Intrinsic::amdgcn_else:
4417  return AMDGPUISD::ELSE;
4418  case Intrinsic::amdgcn_loop:
4419  return AMDGPUISD::LOOP;
4420  case Intrinsic::amdgcn_end_cf:
4421  llvm_unreachable("should not occur");
4422  default:
4423  return 0;
4424  }
4425  }
4426 
4427  // break, if_break, else_break are all only used as inputs to loop, not
4428  // directly as branch conditions.
4429  return 0;
4430 }
4431 
4434  return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4437 }
4438 
4440  // FIXME: Either avoid relying on address space here or change the default
4441  // address space for functions to avoid the explicit check.
4442  return (GV->getValueType()->isFunctionTy() ||
4446  !shouldEmitFixup(GV) &&
4448 }
4449 
4451  return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4452 }
4453 
4454 /// This transforms the control flow intrinsics to get the branch destination as
4455 /// last parameter, also switches branch target with BR if the need arise
4456 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4457  SelectionDAG &DAG) const {
4458  SDLoc DL(BRCOND);
4459 
4460  SDNode *Intr = BRCOND.getOperand(1).getNode();
4461  SDValue Target = BRCOND.getOperand(2);
4462  SDNode *BR = nullptr;
4463  SDNode *SetCC = nullptr;
4464 
4465  if (Intr->getOpcode() == ISD::SETCC) {
4466  // As long as we negate the condition everything is fine
4467  SetCC = Intr;
4468  Intr = SetCC->getOperand(0).getNode();
4469 
4470  } else {
4471  // Get the target from BR if we don't negate the condition
4472  BR = findUser(BRCOND, ISD::BR);
4473  Target = BR->getOperand(1);
4474  }
4475 
4476  // FIXME: This changes the types of the intrinsics instead of introducing new
4477  // nodes with the correct types.
4478  // e.g. llvm.amdgcn.loop
4479 
4480  // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4481  // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4482 
4483  unsigned CFNode = isCFIntrinsic(Intr);
4484  if (CFNode == 0) {
4485  // This is a uniform branch so we don't need to legalize.
4486  return BRCOND;
4487  }
4488 
4489  bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4490  Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4491 
4492  assert(!SetCC ||
4493  (SetCC->getConstantOperandVal(1) == 1 &&
4494  cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4495  ISD::SETNE));
4496 
4497  // operands of the new intrinsic call
4499  if (HaveChain)
4500  Ops.push_back(BRCOND.getOperand(0));
4501 
4502  Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
4503  Ops.push_back(Target);
4504 
4505  ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4506 
4507  // build the new intrinsic call
4508  SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4509 
4510  if (!HaveChain) {
4511  SDValue Ops[] = {
4512  SDValue(Result, 0),
4513  BRCOND.getOperand(0)
4514  };
4515 
4516  Result = DAG.getMergeValues(Ops, DL).getNode();
4517  }
4518 
4519  if (BR) {
4520  // Give the branch instruction our target
4521  SDValue Ops[] = {
4522  BR->getOperand(0),
4523  BRCOND.getOperand(2)
4524  };
4525  SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4526  DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4527  BR = NewBR.getNode();
4528  }
4529 
4530  SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4531 
4532  // Copy the intrinsic results to registers
4533  for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4535  if (!CopyToReg)
4536  continue;
4537 
4538  Chain = DAG.getCopyToReg(
4539  Chain, DL,
4540  CopyToReg->getOperand(1),
4541  SDValue(Result, i - 1),
4542  SDValue());
4543 
4544  DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4545  }
4546 
4547  // Remove the old intrinsic from the chain
4549  SDValue(Intr, Intr->getNumValues() - 1),
4550  Intr->getOperand(0));
4551 
4552  return Chain;
4553 }
4554 
4555 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4556  SelectionDAG &DAG) const {
4557  MVT VT = Op.getSimpleValueType();
4558  SDLoc DL(Op);
4559  // Checking the depth
4560  if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4561  return DAG.getConstant(0, DL, VT);
4562 
4563  MachineFunction &MF = DAG.getMachineFunction();
4565  // Check for kernel and shader functions
4566  if (Info->isEntryFunction())
4567  return DAG.getConstant(0, DL, VT);
4568 
4569  MachineFrameInfo &MFI = MF.getFrameInfo();
4570  // There is a call to @llvm.returnaddress in this function
4571  MFI.setReturnAddressIsTaken(true);
4572 
4574  // Get the return address reg and mark it as an implicit live-in
4575  unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4576 
4577  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4578 }
4579 
4580 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4581  SDValue Op,
4582  const SDLoc &DL,
4583  EVT VT) const {
4584  return Op.getValueType().bitsLE(VT) ?
4585  DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4586  DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4587 }
4588 
4589 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4590  assert(Op.getValueType() == MVT::f16 &&
4591  "Do not know how to custom lower FP_ROUND for non-f16 type");
4592 
4593  SDValue Src = Op.getOperand(0);
4594  EVT SrcVT = Src.getValueType();
4595  if (SrcVT != MVT::f64)
4596  return Op;
4597 
4598  SDLoc DL(Op);
4599 
4600  SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4601  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4602  return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4603 }
4604 
4605 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4606  SelectionDAG &DAG) const {
4607  EVT VT = Op.getValueType();
4608  const MachineFunction &MF = DAG.getMachineFunction();
4610  bool IsIEEEMode = Info->getMode().IEEE;
4611 
4612  // FIXME: Assert during eslection that this is only selected for
4613  // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4614  // mode functions, but this happens to be OK since it's only done in cases
4615  // where there is known no sNaN.
4616  if (IsIEEEMode)
4617  return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4618 
4619  if (VT == MVT::v4f16)
4620  return splitBinaryVectorOp(Op, DAG);
4621  return Op;
4622 }
4623 
4624 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4625  SDLoc SL(Op);
4626  SDValue Chain = Op.getOperand(0);
4627 
4628  if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4629  !Subtarget->isTrapHandlerEnabled())
4630  return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4631 
4632  MachineFunction &MF = DAG.getMachineFunction();
4634  unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4635  assert(UserSGPR != AMDGPU::NoRegister);
4636  SDValue QueuePtr = CreateLiveInRegister(
4637  DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4638  SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4639  SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4640  QueuePtr, SDValue());
4641  SDValue Ops[] = {
4642  ToReg,
4644  SGPR01,
4645  ToReg.getValue(1)
4646  };
4647  return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4648 }
4649 
4650 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4651  SDLoc SL(Op);
4652  SDValue Chain = Op.getOperand(0);
4653  MachineFunction &MF = DAG.getMachineFunction();
4654 
4655  if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4656  !Subtarget->isTrapHandlerEnabled()) {
4658  "debugtrap handler not supported",
4659  Op.getDebugLoc(),
4660  DS_Warning);
4661  LLVMContext &Ctx = MF.getFunction().getContext();
4662  Ctx.diagnose(NoTrap);
4663  return Chain;
4664  }
4665 
4666  SDValue Ops[] = {
4667  Chain,
4669  };
4670  return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4671 }
4672 
4673 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4674  SelectionDAG &DAG) const {
4675  // FIXME: Use inline constants (src_{shared, private}_base) instead.
4676  if (Subtarget->hasApertureRegs()) {
4677  unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4680  unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4683  unsigned Encoding =
4685  Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4686  WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4687 
4688  SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4689  SDValue ApertureReg = SDValue(
4690  DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4691  SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4692  return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4693  }
4694 
4695  MachineFunction &MF = DAG.getMachineFunction();
4697  unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4698  assert(UserSGPR != AMDGPU::NoRegister);
4699 
4700  SDValue QueuePtr = CreateLiveInRegister(
4701  DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4702 
4703  // Offset into amd_queue_t for group_segment_aperture_base_hi /
4704  // private_segment_aperture_base_hi.
4705  uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4706 
4707  SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4708 
4709  // TODO: Use custom target PseudoSourceValue.
4710  // TODO: We should use the value from the IR intrinsic call, but it might not
4711  // be available and how do we get it?
4713  return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4714  MinAlign(64, StructOffset),
4717 }
4718 
4719 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4720  SelectionDAG &DAG) const {
4721  SDLoc SL(Op);
4722  const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4723 
4724  SDValue Src = ASC->getOperand(0);
4725  SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4726 
4727  const AMDGPUTargetMachine &TM =
4728  static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4729 
4730  // flat -> local/private
4732  unsigned DestAS = ASC->getDestAddressSpace();
4733 
4734  if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4735  DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4736  unsigned NullVal = TM.getNullPointerValue(DestAS);
4737  SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4738  SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4739  SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4740 
4741  return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4742  NonNull, Ptr, SegmentNullPtr);
4743  }
4744  }
4745 
4746  // local/private -> flat
4748  unsigned SrcAS = ASC->getSrcAddressSpace();
4749 
4750  if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4751  SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4752  unsigned NullVal = TM.getNullPointerValue(SrcAS);
4753  SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4754 
4755  SDValue NonNull
4756  = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4757 
4758  SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4759  SDValue CvtPtr
4760  = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4761 
4762  return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4763  DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4764  FlatNullPtr);
4765  }
4766  }
4767 
4768  // global <-> flat are no-ops and never emitted.
4769 
4770  const MachineFunction &MF = DAG.getMachineFunction();
4771  DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4772  MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4773  DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4774 
4775  return DAG.getUNDEF(ASC->getValueType(0));
4776 }
4777 
4778 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4779 // the small vector and inserting them into the big vector. That is better than
4780 // the default expansion of doing it via a stack slot. Even though the use of
4781 // the stack slot would be optimized away afterwards, the stack slot itself
4782 // remains.
4783 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4784  SelectionDAG &DAG) const {
4785  SDValue Vec = Op.getOperand(0);
4786  SDValue Ins = Op.getOperand(1);
4787  SDValue Idx = Op.getOperand(2);
4788  EVT VecVT = Vec.getValueType();
4789  EVT InsVT = Ins.getValueType();
4790  EVT EltVT = VecVT.getVectorElementType();
4791  unsigned InsNumElts = InsVT.getVectorNumElements();
4792  unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4793  SDLoc SL(Op);
4794 
4795  for (unsigned I = 0; I != InsNumElts; ++I) {
4796  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4797  DAG.getConstant(I, SL, MVT::i32));
4798  Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4799  DAG.getConstant(IdxVal + I, SL, MVT::i32));
4800  }
4801  return Vec;
4802 }
4803 
4804 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4805  SelectionDAG &DAG) const {
4806  SDValue Vec = Op.getOperand(0);
4807  SDValue InsVal = Op.getOperand(1);
4808  SDValue Idx = Op.getOperand(2);
4809  EVT VecVT = Vec.getValueType();
4810  EVT EltVT = VecVT.getVectorElementType();
4811  unsigned VecSize = VecVT.getSizeInBits();
4812  unsigned EltSize = EltVT.getSizeInBits();
4813 
4814 
4815  assert(VecSize <= 64);
4816 
4817  unsigned NumElts = VecVT.getVectorNumElements();
4818  SDLoc SL(Op);
4819  auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4820 
4821  if (NumElts == 4 && EltSize == 16 && KIdx) {
4822  SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4823 
4824  SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4825  DAG.getConstant(0, SL, MVT::i32));
4826  SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4827  DAG.getConstant(1, SL, MVT::i32));
4828 
4829  SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4830  SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4831 
4832  unsigned Idx = KIdx->getZExtValue();
4833  bool InsertLo = Idx < 2;
4834  SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4835  InsertLo ? LoVec : HiVec,
4836  DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4837  DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4838 
4839  InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4840 
4841  SDValue Concat = InsertLo ?
4842  DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4843  DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4844 
4845  return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4846  }
4847 
4848  if (isa<ConstantSDNode>(Idx))
4849  return SDValue();
4850 
4851  MVT IntVT = MVT::getIntegerVT(VecSize);
4852 
4853  // Avoid stack access for dynamic indexing.
4854  // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4855 
4856  // Create a congruent vector with the target value in each element so that
4857  // the required element can be masked and ORed into the target vector.
4858  SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4859  DAG.getSplatBuildVector(VecVT, SL, InsVal));
4860 
4861  assert(isPowerOf2_32(EltSize));
4862  SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4863 
4864  // Convert vector index to bit-index.
4865  SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4866 
4867  SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4868  SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4869  DAG.getConstant(0xffff, SL, IntVT),
4870  ScaledIdx);
4871 
4872  SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4873  SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4874  DAG.getNOT(SL, BFM, IntVT), BCVec);
4875 
4876  SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4877  return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4878 }
4879 
4880 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4881  SelectionDAG &DAG) const {
4882  SDLoc SL(Op);
4883 
4884  EVT ResultVT = Op.getValueType();
4885  SDValue Vec = Op.getOperand(0);
4886  SDValue Idx = Op.getOperand(1);
4887  EVT VecVT = Vec.getValueType();
4888  unsigned VecSize = VecVT.getSizeInBits();
4889  EVT EltVT = VecVT.getVectorElementType();
4890  assert(VecSize <= 64);
4891 
4892  DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4893 
4894  // Make sure we do any optimizations that will make it easier to fold
4895  // source modifiers before obscuring it with bit operations.
4896 
4897  // XXX - Why doesn't this get called when vector_shuffle is expanded?
4898  if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4899  return Combined;
4900 
4901  unsigned EltSize = EltVT.getSizeInBits();
4902  assert(isPowerOf2_32(EltSize));
4903 
4904  MVT IntVT = MVT::getIntegerVT(VecSize);
4905  SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4906 
4907  // Convert vector index to bit-index (* EltSize)
4908  SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4909 
4910  SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4911  SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4912 
4913  if (ResultVT == MVT::f16) {
4914  SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4915  return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4916  }
4917 
4918  return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4919 }
4920 
4922  assert(Elt % 2 == 0);
4923  return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4924 }
4925 
4926 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4927  SelectionDAG &DAG) const {
4928  SDLoc SL(Op);
4929  EVT ResultVT = Op.getValueType();
4930  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4931 
4932  EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4933  EVT EltVT = PackVT.getVectorElementType();
4934  int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4935 
4936  // vector_shuffle <0,1,6,7> lhs, rhs
4937  // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4938  //
4939  // vector_shuffle <6,7,2,3> lhs, rhs
4940  // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4941  //
4942  // vector_shuffle <6,7,0,1> lhs, rhs
4943  // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4944 
4945  // Avoid scalarizing when both halves are reading from consecutive elements.
4946  SmallVector<SDValue, 4> Pieces;
4947  for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4948  if (elementPairIsContiguous(SVN->getMask(), I)) {
4949  const int Idx = SVN->getMaskElt(I);
4950  int VecIdx = Idx < SrcNumElts ? 0 : 1;
4951  int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4952  SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4953  PackVT, SVN->getOperand(VecIdx),
4954  DAG.getConstant(EltIdx, SL, MVT::i32));
4955  Pieces.push_back(SubVec);
4956  } else {
4957  const int Idx0 = SVN->getMaskElt(I);
4958  const int Idx1 = SVN->getMaskElt(I + 1);
4959  int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4960  int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4961  int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4962  int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4963 
4964  SDValue Vec0 = SVN->getOperand(VecIdx0);
4965  SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4966  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4967 
4968  SDValue Vec1 = SVN->getOperand(VecIdx1);
4969  SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4970  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4971  Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4972  }
4973  }
4974 
4975  return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4976 }
4977 
4978 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4979  SelectionDAG &DAG) const {
4980  SDLoc SL(Op);
4981  EVT VT = Op.getValueType();
4982 
4983  if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4985 
4986  // Turn into pair of packed build_vectors.
4987  // TODO: Special case for constants that can be materialized with s_mov_b64.
4988  SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4989  { Op.getOperand(0), Op.getOperand(1) });
4990  SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4991  { Op.getOperand(2), Op.getOperand(3) });
4992 
4993  SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4994  SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4995 
4996  SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4997  return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4998  }
4999 
5000  assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5001  assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5002 
5003  SDValue Lo = Op.getOperand(0);
5004  SDValue Hi = Op.getOperand(1);
5005 
5006  // Avoid adding defined bits with the zero_extend.
5007  if (Hi.isUndef()) {
5008  Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5009  SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5010  return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5011  }
5012 
5013  Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5014  Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5015 
5016  SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5017  DAG.getConstant(16, SL, MVT::i32));
5018  if (Lo.isUndef())
5019  return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5020 
5021  Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5022  Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5023 
5024  SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5025  return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5026 }
5027 
5028 bool
5030  // We can fold offsets for anything that doesn't require a GOT relocation.
5031  return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5034  !shouldEmitGOTReloc(GA->getGlobal());
5035 }
5036 
5037 static SDValue
5039  const SDLoc &DL, unsigned Offset, EVT PtrVT,
5040  unsigned GAFlags = SIInstrInfo::MO_NONE) {
5041  // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5042  // lowered to the following code sequence:
5043  //
5044  // For constant address space:
5045  // s_getpc_b64 s[0:1]
5046  // s_add_u32 s0, s0, $symbol
5047  // s_addc_u32 s1, s1, 0
5048  //
5049  // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5050  // a fixup or relocation is emitted to replace $symbol with a literal
5051  // constant, which is a pc-relative offset from the encoding of the $symbol
5052  // operand to the global variable.
5053  //
5054  // For global address space:
5055  // s_getpc_b64 s[0:1]
5056  // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5057  // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5058  //
5059  // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5060  // fixups or relocations are emitted to replace $symbol@*@lo and
5061  // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5062  // which is a 64-bit pc-relative offset from the encoding of the $symbol
5063  // operand to the global variable.
5064  //
5065  // What we want here is an offset from the value returned by s_getpc
5066  // (which is the address of the s_add_u32 instruction) to the global
5067  // variable, but since the encoding of $symbol starts 4 bytes after the start
5068  // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5069  // small. This requires us to add 4 to the global variable offset in order to
5070  // compute the correct address.
5071  SDValue PtrLo =
5072  DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5073  SDValue PtrHi;
5074  if (GAFlags == SIInstrInfo::MO_NONE) {
5075  PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5076  } else {
5077  PtrHi =
5078  DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5079  }
5080  return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5081 }
5082 
5083 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5084  SDValue Op,
5085  SelectionDAG &DAG) const {
5086  GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5087  const GlobalValue *GV = GSD->getGlobal();
5088  if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5089  (!GV->hasExternalLinkage() ||
5094  return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5095 
5096  SDLoc DL(GSD);
5097  EVT PtrVT = Op.getValueType();
5098 
5099  if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5100  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5102  return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5103  }
5104 
5105  if (shouldEmitFixup(GV))
5106  return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5107  else if (shouldEmitPCReloc(GV))
5108  return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5110 
5111  SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5113 
5114  Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5116  const DataLayout &DataLayout = DAG.getDataLayout();
5117  unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5118  MachinePointerInfo PtrInfo
5120 
5121  return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5124 }
5125 
5127  const SDLoc &DL, SDValue V) const {
5128  // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5129  // the destination register.
5130  //
5131  // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5132  // so we will end up with redundant moves to m0.
5133  //
5134  // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5135 
5136  // A Null SDValue creates a glue result.
5137  SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5138  V, Chain);
5139  return SDValue(M0, 0);
5140 }
5141 
5142 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5143  SDValue Op,
5144  MVT VT,
5145  unsigned Offset) const {
5146  SDLoc SL(Op);
5147  SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5148  DAG.getEntryNode(), Offset, 4, false);
5149  // The local size values will have the hi 16-bits as zero.
5150  return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5151  DAG.getValueType(VT));
5152 }
5153 
5155  EVT VT) {
5157  "non-hsa intrinsic with hsa target",
5158  DL.getDebugLoc());
5159  DAG.getContext()->diagnose(BadIntrin);
5160  return DAG.getUNDEF(VT);
5161 }
5162 
5164  EVT VT) {
5166  "intrinsic not supported on subtarget",
5167  DL.getDebugLoc());
5168  DAG.getContext()->diagnose(BadIntrin);
5169  return DAG.getUNDEF(VT);
5170 }
5171 
5173  ArrayRef<SDValue> Elts) {
5174  assert(!Elts.empty());
5175  MVT Type;
5176  unsigned NumElts;
5177 
5178  if (Elts.size() == 1) {
5179  Type = MVT::f32;
5180  NumElts = 1;
5181  } else if (Elts.size() == 2) {
5182  Type = MVT::v2f32;
5183  NumElts = 2;
5184  } else if (Elts.size() <= 4) {
5185  Type = MVT::v4f32;
5186  NumElts = 4;
5187  } else if (Elts.size() <= 8) {
5188  Type = MVT::v8f32;
5189  NumElts = 8;
5190  } else {
5191  assert(Elts.size() <= 16);
5192  Type = MVT::v16f32;
5193  NumElts = 16;
5194  }
5195 
5196  SmallVector<SDValue, 16> VecElts(NumElts);
5197  for (unsigned i = 0; i < Elts.size(); ++i) {
5198  SDValue Elt = Elts[i];
5199  if (Elt.getValueType() != MVT::f32)
5200  Elt = DAG.getBitcast(MVT::f32, Elt);
5201  VecElts[i] = Elt;
5202  }
5203  for (unsigned i = Elts.size(); i < NumElts; ++i)
5204  VecElts[i] = DAG.getUNDEF(MVT::f32);
5205 
5206  if (NumElts == 1)
5207  return VecElts[0];
5208  return DAG.getBuildVector(Type, DL, VecElts);
5209 }
5210 
5211 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5212  SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5213  auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5214 
5215  uint64_t Value = CachePolicyConst->getZExtValue();
5216  SDLoc DL(CachePolicy);
5217  if (GLC) {
5218  *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5219  Value &= ~(uint64_t)0x1;
5220  }
5221  if (SLC) {
5222  *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5223  Value &= ~(uint64_t)0x2;
5224  }
5225  if (DLC) {
5226  *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5227  Value &= ~(uint64_t)0x4;
5228  }
5229 
5230  return Value == 0;
5231 }
5232 
5233 // Re-construct the required return value for a image load intrinsic.
5234 // This is more complicated due to the optional use TexFailCtrl which means the required
5235 // return type is an aggregate
5237  MachineSDNode *Result,
5238  ArrayRef<EVT> ResultTypes,
5239  bool IsTexFail, bool Unpacked, bool IsD16,
5240  int DMaskPop, int NumVDataDwords,
5241  const SDLoc &DL, LLVMContext &Context) {
5242  // Determine the required return type. This is the same regardless of IsTexFail flag
5243  EVT ReqRetVT = ResultTypes[0];
5244  EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5245  int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5246  EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5247  EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5248  : AdjEltVT
5249  : ReqRetVT;
5250 
5251  // Extract data part of the result
5252  // Bitcast the result to the same type as the required return type
5253  int NumElts;
5254  if (IsD16 && !Unpacked)
5255  NumElts = NumVDataDwords << 1;
5256  else
5257  NumElts = NumVDataDwords;
5258 
5259  EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5260  : AdjEltVT;
5261 
5262  // Special case for v6f16. Rather than add support for this, use v3i32 to
5263  // extract the data elements
5264  bool V6F16Special = false;
5265  if (NumElts == 6) {
5266  CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5267  DMaskPop >>= 1;
5268  ReqRetNumElts >>= 1;
5269  V6F16Special = true;
5270  AdjVT = MVT::v2i32;
5271  }
5272 
5273  SDValue N = SDValue(Result, 0);
5274  SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5275 
5276  // Iterate over the result
5277  SmallVector<SDValue, 4> BVElts;
5278 
5279  if (CastVT.isVector()) {
5280  DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5281  } else {
5282  BVElts.push_back(CastRes);
5283  }
5284  int ExtraElts = ReqRetNumElts - DMaskPop;
5285  while(ExtraElts--)
5286  BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5287 
5288  SDValue PreTFCRes;
5289  if (ReqRetNumElts > 1) {
5290  SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5291  if (IsD16 && Unpacked)
5292  PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5293  else
5294  PreTFCRes = NewVec;
5295  } else {
5296  PreTFCRes = BVElts[0];
5297  }
5298 
5299  if (V6F16Special)
5300  PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5301 
5302  if (!IsTexFail) {
5303  if (Result->getNumValues() > 1)
5304  return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5305  else
5306  return PreTFCRes;
5307  }
5308 
5309  // Extract the TexFail result and insert into aggregate return
5310  SmallVector<SDValue, 1> TFCElt;
5311  DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5312  SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5313  return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5314 }
5315 
5316 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5317  SDValue *LWE, bool &IsTexFail) {
5318  auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5319 
5320  uint64_t Value = TexFailCtrlConst->getZExtValue();
5321  if (Value) {
5322  IsTexFail = true;
5323  }
5324 
5325  SDLoc DL(TexFailCtrlConst);
5326  *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5327  Value &= ~(uint64_t)0x1;
5328  *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5329  Value &= ~(uint64_t)0x2;
5330 
5331  return Value == 0;
5332 }
5333 
5334 SDValue SITargetLowering::lowerImage(SDValue Op,
5335  const AMDGPU::ImageDimIntrinsicInfo *Intr,
5336  SelectionDAG &DAG) const {
5337  SDLoc DL(Op);
5338  MachineFunction &MF = DAG.getMachineFunction();
5339  const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5340  const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5341  AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5342  const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5343  const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5344  AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5345  const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5346  AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5347  unsigned IntrOpcode = Intr->BaseOpcode;
5348  bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5349 
5350  SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5351  SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5352  bool IsD16 = false;
5353  bool IsA16 = false;
5354  SDValue VData;
5355  int NumVDataDwords;
5356  bool AdjustRetType = false;
5357 
5358  unsigned AddrIdx; // Index of first address argument
5359  unsigned DMask;
5360  unsigned DMaskLanes = 0;
5361 
5362  if (BaseOpcode->Atomic) {
5363  VData = Op.getOperand(2);
5364 
5365  bool Is64Bit = VData.getValueType() == MVT::i64;
5366  if (BaseOpcode->AtomicX2) {
5367  SDValue VData2 = Op.getOperand(3);
5368  VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5369  {VData, VData2});
5370  if (Is64Bit)
5371  VData = DAG.getBitcast(MVT::v4i32, VData);
5372 
5373  ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5374  DMask = Is64Bit ? 0xf : 0x3;
5375  NumVDataDwords = Is64Bit ? 4 : 2;
5376  AddrIdx = 4;
5377  } else {
5378  DMask = Is64Bit ? 0x3 : 0x1;
5379  NumVDataDwords = Is64Bit ? 2 : 1;
5380  AddrIdx = 3;
5381  }
5382  } else {
5383  unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5384  auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5385  DMask = DMaskConst->getZExtValue();
5386  DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5387 
5388  if (BaseOpcode->Store) {
5389  VData = Op.getOperand(2);
5390 
5391  MVT StoreVT = VData.getSimpleValueType();
5392  if (StoreVT.getScalarType() == MVT::f16) {
5393  if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5394  return Op; // D16 is unsupported for this instruction
5395 
5396  IsD16 = true;
5397  VData = handleD16VData(VData, DAG);
5398  }
5399 
5400  NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5401  } else {
5402  // Work out the num dwords based on the dmask popcount and underlying type
5403  // and whether packing is supported.
5404  MVT LoadVT = ResultTypes[0].getSimpleVT();
5405  if (LoadVT.getScalarType() == MVT::f16) {
5406  if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5407  return Op; // D16 is unsupported for this instruction
5408 
5409  IsD16 = true;
5410  }
5411 
5412  // Confirm that the return type is large enough for the dmask specified
5413  if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5414  (!LoadVT.isVector() && DMaskLanes > 1))
5415  return Op;
5416 
5417  if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5418  NumVDataDwords = (DMaskLanes + 1) / 2;
5419  else
5420  NumVDataDwords = DMaskLanes;
5421 
5422  AdjustRetType = true;
5423  }
5424 
5425  AddrIdx = DMaskIdx + 1;
5426  }
5427 
5428  unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5429  unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5430  unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5431  unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5432  NumCoords + NumLCM;
5433  unsigned NumMIVAddrs = NumVAddrs;
5434 
5435  SmallVector<SDValue, 4> VAddrs;
5436 
5437  // Optimize _L to _LZ when _L is zero
5438  if (LZMappingInfo) {
5439  if (auto ConstantLod =
5440  dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5441  if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5442  IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
5443  NumMIVAddrs--; // remove 'lod'
5444  }
5445  }
5446  }
5447 
5448  // Optimize _mip away, when 'lod' is zero
5449  if (MIPMappingInfo) {
5450  if (auto ConstantLod =
5451  dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5452  if (ConstantLod->isNullValue()) {
5453  IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
5454  NumMIVAddrs--; // remove 'lod'
5455  }
5456  }
5457  }
5458 
5459  // Check for 16 bit addresses and pack if true.
5460  unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5461  MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5462  const MVT VAddrScalarVT = VAddrVT.getScalarType();
5463  if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5464  ST->hasFeature(AMDGPU::FeatureR128A16)) {
5465  IsA16 = true;
5466  const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5467  for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5468  SDValue AddrLo, AddrHi;
5469  // Push back extra arguments.
5470  if (i < DimIdx) {
5471  AddrLo = Op.getOperand(i);
5472  } else {
5473  AddrLo = Op.getOperand(i);
5474  // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5475  // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5476  if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5477  ((NumGradients / 2) % 2 == 1 &&
5478  (i == DimIdx + (NumGradients / 2) - 1 ||
5479  i == DimIdx + NumGradients - 1))) {
5480  AddrHi = DAG.getUNDEF(MVT::f16);
5481  } else {
5482  AddrHi = Op.getOperand(i + 1);
5483  i++;
5484  }
5485  AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5486  {AddrLo, AddrHi});
5487  AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5488  }
5489  VAddrs.push_back(AddrLo);
5490  }
5491  } else {
5492  for (unsigned i = 0; i < NumMIVAddrs; ++i)
5493  VAddrs.push_back(Op.getOperand(AddrIdx + i));
5494  }
5495 
5496  // If the register allocator cannot place the address registers contiguously
5497  // without introducing moves, then using the non-sequential address encoding
5498  // is always preferable, since it saves VALU instructions and is usually a
5499  // wash in terms of code size or even better.
5500  //
5501  // However, we currently have no way of hinting to the register allocator that
5502  // MIMG addresses should be placed contiguously when it is possible to do so,
5503  // so force non-NSA for the common 2-address case as a heuristic.
5504  //
5505  // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5506  // allocation when possible.
5507  bool UseNSA =
5508  ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5509  SDValue VAddr;
5510  if (!UseNSA)
5511  VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5512 
5513  SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5514  SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5515  unsigned CtrlIdx; // Index of texfailctrl argument
5516  SDValue Unorm;
5517  if (!BaseOpcode->Sampler) {
5518  Unorm = True;
5519  CtrlIdx = AddrIdx + NumVAddrs + 1;
5520  } else {
5521  auto UnormConst =
5522  cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5523 
5524  Unorm = UnormConst->getZExtValue() ? True : False;
5525  CtrlIdx = AddrIdx + NumVAddrs + 3;
5526  }
5527 
5528  SDValue TFE;
5529  SDValue LWE;
5530  SDValue TexFail = Op.getOperand(CtrlIdx);
5531  bool IsTexFail = false;
5532  if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5533  return Op;
5534 
5535  if (IsTexFail) {
5536  if (!DMaskLanes) {
5537  // Expecting to get an error flag since TFC is on - and dmask is 0
5538  // Force dmask to be at least 1 otherwise the instruction will fail
5539  DMask = 0x1;
5540  DMaskLanes = 1;
5541  NumVDataDwords = 1;
5542  }
5543  NumVDataDwords += 1;
5544  AdjustRetType = true;
5545  }
5546 
5547  // Has something earlier tagged that the return type needs adjusting
5548  // This happens if the instruction is a load or has set TexFailCtrl flags
5549  if (AdjustRetType) {
5550  // NumVDataDwords reflects the true number of dwords required in the return type
5551  if (DMaskLanes == 0 && !BaseOpcode->Store) {
5552  // This is a no-op load. This can be eliminated
5553  SDValue Undef = DAG.getUNDEF(Op.getValueType());
5554  if (isa<MemSDNode>(Op))
5555  return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5556  return Undef;
5557  }
5558 
5559  EVT NewVT = NumVDataDwords > 1 ?
5560  EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5561  : MVT::f32;
5562 
5563  ResultTypes[0] = NewVT;
5564  if (ResultTypes.size() == 3) {
5565  // Original result was aggregate type used for TexFailCtrl results
5566  // The actual instruction returns as a vector type which has now been
5567  // created. Remove the aggregate result.
5568  ResultTypes.erase(&ResultTypes[1]);
5569  }
5570  }
5571 
5572  SDValue GLC;
5573  SDValue SLC;
5574  SDValue DLC;
5575  if (BaseOpcode->Atomic) {
5576  GLC = True; // TODO no-return optimization
5577  if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5578  IsGFX10 ? &DLC : nullptr))
5579  return Op;
5580  } else {
5581  if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5582  IsGFX10 ? &DLC : nullptr))
5583  return Op;
5584  }
5585 
5587  if (BaseOpcode->Store || BaseOpcode->Atomic)
5588  Ops.push_back(VData); // vdata
5589  if (UseNSA) {
5590  for (const SDValue &Addr : VAddrs)
5591  Ops.push_back(Addr);
5592  } else {
5593  Ops.push_back(VAddr);
5594  }
5595  Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5596  if (BaseOpcode->Sampler)
5597  Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5598  Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5599  if (IsGFX10)
5600  Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5601  Ops.push_back(Unorm);
5602  if (IsGFX10)
5603  Ops.push_back(DLC);
5604  Ops.push_back(GLC);
5605  Ops.push_back(SLC);
5606  Ops.push_back(IsA16 && // a16 or r128
5607  ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5608  Ops.push_back(TFE); // tfe
5609  Ops.push_back(LWE); // lwe
5610  if (!IsGFX10)
5611  Ops.push_back(DimInfo->DA ? True : False);
5612  if (BaseOpcode->HasD16)
5613  Ops.push_back(IsD16 ? True : False);
5614  if (isa<MemSDNode>(Op))
5615  Ops.push_back(Op.getOperand(0)); // chain
5616 
5617  int NumVAddrDwords =
5618  UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5619  int Opcode = -1;
5620 
5621  if (IsGFX10) {
5622  Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5623  UseNSA ? AMDGPU::MIMGEncGfx10NSA
5624  : AMDGPU::MIMGEncGfx10Default,
5625  NumVDataDwords, NumVAddrDwords);
5626  } else {
5628  Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5629  NumVDataDwords, NumVAddrDwords);
5630  if (Opcode == -1)
5631  Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5632  NumVDataDwords, NumVAddrDwords);
5633  }
5634  assert(Opcode != -1);
5635 
5636  MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5637  if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5638  MachineMemOperand *MemRef = MemOp->getMemOperand();
5639  DAG.setNodeMemRefs(NewNode, {MemRef});
5640  }
5641 
5642  if (BaseOpcode->AtomicX2) {
5644  DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5645  return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5646  } else if (!BaseOpcode->Store) {
5647  return constructRetValue(DAG, NewNode,
5648  OrigResultTypes, IsTexFail,
5649  Subtarget->hasUnpackedD16VMem(), IsD16,
5650  DMaskLanes, NumVDataDwords, DL,
5651  *DAG.getContext());
5652  }
5653 
5654  return SDValue(NewNode, 0);
5655 }
5656 
5657 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5658  SDValue Offset, SDValue GLC, SDValue DLC,
5659  SelectionDAG &DAG) const {
5660  MachineFunction &MF = DAG.getMachineFunction();
5661 
5662  const DataLayout &DataLayout = DAG.getDataLayout();
5663  unsigned Align =
5664  DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5665 
5670  VT.getStoreSize(), Align);
5671 
5672  if (!Offset->isDivergent()) {
5673  SDValue Ops[] = {
5674  Rsrc,
5675  Offset, // Offset
5676  GLC,
5677  DLC,
5678  };
5679 
5680  // Widen vec3 load to vec4.
5681  if (VT.isVector() && VT.getVectorNumElements() == 3) {
5682  EVT WidenedVT =
5684  auto WidenedOp = DAG.getMemIntrinsicNode(
5685  AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5686  MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5687  auto Subvector = DAG.getNode(
5688  ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5689  DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
5690  return Subvector;
5691  }
5692 
5694  DAG.getVTList(VT), Ops, VT, MMO);
5695  }
5696 
5697  // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5698  // assume that the buffer is unswizzled.
5700  unsigned NumLoads = 1;
5701  MVT LoadVT = VT.getSimpleVT();
5702  unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5703  assert((LoadVT.getScalarType() == MVT::i32 ||
5704  LoadVT.getScalarType() == MVT::f32));
5705 
5706  if (NumElts == 8 || NumElts == 16) {
5707  NumLoads = NumElts / 4;
5708  LoadVT = MVT::v4i32;
5709  }
5710 
5711  SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5712  unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5713  SDValue Ops[] = {
5714  DAG.getEntryNode(), // Chain
5715  Rsrc, // rsrc
5716  DAG.getConstant(0, DL, MVT::i32), // vindex
5717  {}, // voffset
5718  {}, // soffset
5719  {}, // offset
5720  DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5721  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
5722  };
5723 
5724  // Use the alignment to ensure that the required offsets will fit into the
5725  // immediate offsets.
5726  setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5727 
5728  uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5729  for (unsigned i = 0; i < NumLoads; ++i) {
5730  Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5731  Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5732  LoadVT, MMO, DAG));
5733  }
5734 
5735  if (VT == MVT::v8i32 || VT == MVT::v16i32)
5736  return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5737 
5738  return Loads[0];
5739 }
5740 
5741 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5742  SelectionDAG &DAG) const {
5743  MachineFunction &MF = DAG.getMachineFunction();
5744  auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5745 
5746  EVT VT = Op.getValueType();
5747  SDLoc DL(Op);
5748  unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5749 
5750  // TODO: Should this propagate fast-math-flags?
5751 
5752  switch (IntrinsicID) {
5753  case Intrinsic::amdgcn_implicit_buffer_ptr: {
5754  if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5755  return emitNonHSAIntrinsicError(DAG, DL, VT);
5756  return getPreloadedValue(DAG, *MFI, VT,
5758  }
5759  case Intrinsic::amdgcn_dispatch_ptr:
5760  case Intrinsic::amdgcn_queue_ptr: {
5761  if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5762  DiagnosticInfoUnsupported BadIntrin(
5763  MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5764  DL.getDebugLoc());
5765  DAG.getContext()->diagnose(BadIntrin);
5766  return DAG.getUNDEF(VT);
5767  }
5768 
5769  auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5771  return getPreloadedValue(DAG, *MFI, VT, RegID);
5772  }
5773  case Intrinsic::amdgcn_implicitarg_ptr: {
5774  if (MFI->isEntryFunction())
5775  return getImplicitArgPtr(DAG, DL);
5776  return getPreloadedValue(DAG, *MFI, VT,
5778  }
5779  case Intrinsic::amdgcn_kernarg_segment_ptr: {
5780  return getPreloadedValue(DAG, *MFI, VT,
5782  }
5783  case Intrinsic::amdgcn_dispatch_id: {
5784  return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5785  }
5786  case Intrinsic::amdgcn_rcp:
5787  return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5788  case Intrinsic::amdgcn_rsq:
5789  return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5790  case Intrinsic::amdgcn_rsq_legacy:
5792  return emitRemovedIntrinsicError(DAG, DL, VT);
5793 
5794  return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5795  case Intrinsic::amdgcn_rcp_legacy:
5797  return emitRemovedIntrinsicError(DAG, DL, VT);
5798  return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5799  case Intrinsic::amdgcn_rsq_clamp: {
5801  return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5802 
5803  Type *Type = VT.getTypeForEVT(*DAG.getContext());
5805  APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5806 
5807  SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5808  SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5809  DAG.getConstantFP(Max, DL, VT));
5810  return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5811  DAG.getConstantFP(Min, DL, VT));
5812  }
5813  case Intrinsic::r600_read_ngroups_x:
5814  if (Subtarget->isAmdHsaOS())
5815  return emitNonHSAIntrinsicError(DAG, DL, VT);
5816 
5817  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5819  case Intrinsic::r600_read_ngroups_y:
5820  if (Subtarget->isAmdHsaOS())
5821  return emitNonHSAIntrinsicError(DAG, DL, VT);
5822 
5823  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5825  case Intrinsic::r600_read_ngroups_z:
5826  if (Subtarget->isAmdHsaOS())
5827  return emitNonHSAIntrinsicError(DAG, DL, VT);
5828 
5829  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5831  case Intrinsic::r600_read_global_size_x:
5832  if (Subtarget->isAmdHsaOS())
5833  return emitNonHSAIntrinsicError(DAG, DL, VT);
5834 
5835  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5837  case Intrinsic::r600_read_global_size_y:
5838  if (Subtarget->isAmdHsaOS())
5839  return emitNonHSAIntrinsicError(DAG, DL, VT);
5840 
5841  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5843  case Intrinsic::r600_read_global_size_z:
5844  if (Subtarget->isAmdHsaOS())
5845  return emitNonHSAIntrinsicError(DAG, DL, VT);
5846 
5847  return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5849  case Intrinsic::r600_read_local_size_x:
5850  if (Subtarget->isAmdHsaOS())
5851  return emitNonHSAIntrinsicError(DAG, DL, VT);
5852 
5853  return lowerImplicitZextParam(DAG, Op, MVT::i16,
5855  case Intrinsic::r600_read_local_size_y:
5856  if (Subtarget->isAmdHsaOS())
5857  return emitNonHSAIntrinsicError(DAG, DL, VT);
5858 
5859  return lowerImplicitZextParam(DAG, Op, MVT::i16,
5861  case Intrinsic::r600_read_local_size_z:
5862  if (Subtarget->isAmdHsaOS())
5863  return emitNonHSAIntrinsicError(DAG, DL, VT);
5864 
5865  return lowerImplicitZextParam(DAG, Op, MVT::i16,
5867  case Intrinsic::amdgcn_workgroup_id_x:
5868  case Intrinsic::r600_read_tgid_x:
5869  return getPreloadedValue(DAG, *MFI, VT,
5871  case Intrinsic::amdgcn_workgroup_id_y:
5872  case Intrinsic::r600_read_tgid_y:
5873  return getPreloadedValue(DAG, *MFI, VT,
5875  case Intrinsic::amdgcn_workgroup_id_z:
5876  case Intrinsic::r600_read_tgid_z:
5877  return getPreloadedValue(DAG, *MFI, VT,
5879  case Intrinsic::amdgcn_workitem_id_x:
5880  case Intrinsic::r600_read_tidig_x:
5881  return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5882  SDLoc(DAG.getEntryNode()),
5883  MFI->getArgInfo().WorkItemIDX);
5884  case Intrinsic::amdgcn_workitem_id_y:
5885  case Intrinsic::r600_read_tidig_y:
5886  return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5887  SDLoc(DAG.getEntryNode()),
5888  MFI->getArgInfo().WorkItemIDY);
5889  case Intrinsic::amdgcn_workitem_id_z:
5890  case Intrinsic::r600_read_tidig_z:
5891  return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5892  SDLoc(DAG.getEntryNode()),
5893  MFI->getArgInfo().WorkItemIDZ);
5894  case Intrinsic::amdgcn_wavefrontsize:
5896  SDLoc(Op), MVT::i32);
5897  case Intrinsic::amdgcn_s_buffer_load: {
5898  bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5899  SDValue GLC;
5900  SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5901  if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5902  IsGFX10 ? &DLC : nullptr))
5903  return Op;
5904  return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5905  DAG);
5906  }
5907  case Intrinsic::amdgcn_fdiv_fast:
5908  return lowerFDIV_FAST(Op, DAG);
5909  case Intrinsic::amdgcn_interp_p1_f16: {
5910  SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0,
5911  Op.getOperand(5), SDValue());
5912  if (getSubtarget()->getLDSBankCount() == 16) {
5913  // 16 bank LDS
5914 
5915  // FIXME: This implicitly will insert a second CopyToReg to M0.
5916  SDValue S = DAG.getNode(
5918  DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32),
5919  DAG.getConstant(2, DL, MVT::i32), // P0
5920  Op.getOperand(2), // Attrchan
5921  Op.getOperand(3), // Attr
5922  Op.getOperand(5)); // m0
5923 
5924  SDValue Ops[] = {
5925  Op.getOperand(1), // Src0
5926  Op.getOperand(2), // Attrchan
5927  Op.getOperand(3), // Attr
5928  DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5929  S, // Src2 - holds two f16 values selected by high
5930  DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
5931  Op.getOperand(4), // high
5932  DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5933  DAG.getTargetConstant(0, DL, MVT::i32) // $omod
5934  };
5935  return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5936  } else {
5937  // 32 bank LDS
5938  SDValue Ops[] = {
5939  Op.getOperand(1), // Src0
5940  Op.getOperand(2), // Attrchan
5941  Op.getOperand(3), // Attr
5942  DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5943  Op.getOperand(4), // high
5944  DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5945  DAG.getTargetConstant(0, DL, MVT::i32), // $omod
5946  ToM0.getValue(1)
5947  };
5948  return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5949  }
5950  }
5951  case Intrinsic::amdgcn_sin:
5952  return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5953 
5954  case Intrinsic::amdgcn_cos:
5955  return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5956 
5957  case Intrinsic::amdgcn_mul_u24:
5958  return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5959  case Intrinsic::amdgcn_mul_i24:
5960  return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5961 
5962  case Intrinsic::amdgcn_log_clamp: {
5964  return SDValue();
5965 
5966  DiagnosticInfoUnsupported BadIntrin(
5967  MF.getFunction(), "intrinsic not supported on subtarget",
5968  DL.getDebugLoc());
5969  DAG.getContext()->diagnose(BadIntrin);
5970  return DAG.getUNDEF(VT);
5971  }
5972  case Intrinsic::amdgcn_ldexp:
5973  return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5974  Op.getOperand(1), Op.getOperand(2));
5975 
5976  case Intrinsic::amdgcn_fract:
5977  return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5978 
5979  case Intrinsic::amdgcn_class:
5980  return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5981  Op.getOperand(1), Op.getOperand(2));
5982  case Intrinsic::amdgcn_div_fmas:
5983  return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5984  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5985  Op.getOperand(4));
5986 
5987  case Intrinsic::amdgcn_div_fixup:
5988  return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5989  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5990 
5991  case Intrinsic::amdgcn_trig_preop:
5992  return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5993  Op.getOperand(1), Op.getOperand(2));
5994  case Intrinsic::amdgcn_div_scale: {
5995  const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5996 
5997  // Translate to the operands expected by the machine instruction. The
5998  // first parameter must be the same as the first instruction.
5999  SDValue Numerator = Op.getOperand(1);
6000  SDValue Denominator = Op.getOperand(2);
6001 
6002  // Note this order is opposite of the machine instruction's operations,
6003  // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6004  // intrinsic has the numerator as the first operand to match a normal
6005  // division operation.
6006 
6007  SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6008 
6009  return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6010  Denominator, Numerator);
6011  }
6012  case Intrinsic::amdgcn_icmp: {
6013  // There is a Pat that handles this variant, so return it as-is.
6014  if (Op.getOperand(1).getValueType() == MVT::i1 &&
6015  Op.getConstantOperandVal(2) == 0 &&
6016  Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6017  return Op;
6018  return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6019  }
6020  case Intrinsic::amdgcn_fcmp: {
6021  return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6022  }
6023  case Intrinsic::amdgcn_fmed3:
6024  return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6025  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6026  case Intrinsic::amdgcn_fdot2:
6027  return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6028  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6029  Op.getOperand(4));
6030  case Intrinsic::amdgcn_fmul_legacy:
6031  return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6032  Op.getOperand(1), Op.getOperand(2));
6033  case Intrinsic::amdgcn_sffbh:
6034  return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6035  case Intrinsic::amdgcn_sbfe:
6036  return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6037  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6038  case Intrinsic::amdgcn_ubfe:
6039  return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6040  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6041  case Intrinsic::amdgcn_cvt_pkrtz:
6042  case Intrinsic::amdgcn_cvt_pknorm_i16:
6043  case Intrinsic::amdgcn_cvt_pknorm_u16:
6044  case Intrinsic::amdgcn_cvt_pk_i16:
6045  case Intrinsic::amdgcn_cvt_pk_u16: {
6046  // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6047  EVT VT = Op.getValueType();
6048  unsigned Opcode;
6049 
6050  if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6052  else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6054  else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6056  else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6057  Opcode = AMDGPUISD::CVT_PK_I16_I32;
6058  else
6059  Opcode = AMDGPUISD::CVT_PK_U16_U32;
6060 
6061  if (isTypeLegal(VT))
6062  return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6063 
6064  SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6065  Op.getOperand(1), Op.getOperand(2));
6066  return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6067  }
6068  case Intrinsic::amdgcn_fmad_ftz:
6069  return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6070  Op.getOperand(2), Op.getOperand(3));
6071 
6072  case Intrinsic::amdgcn_if_break:
6073  return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6074  Op->getOperand(1), Op->getOperand(2)), 0);
6075 
6076  case Intrinsic::amdgcn_groupstaticsize: {
6078  if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6079  return Op;
6080 
6081  const Module *M = MF.getFunction().getParent();
6082  const GlobalValue *GV =
6083  M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6084  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6086  return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6087  }
6088  case Intrinsic::amdgcn_is_shared:
6089  case Intrinsic::amdgcn_is_private: {
6090  SDLoc SL(Op);
6091  unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6093  SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6094  SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6095  Op.getOperand(1));
6096 
6097  SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6098  DAG.getConstant(1, SL, MVT::i32));
6099  return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6100  }
6101  default:
6102  if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6103  AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6104  return lowerImage(Op, ImageDimIntr, DAG);
6105 
6106  return Op;
6107  }
6108 }
6109 
6110 // This function computes an appropriate offset to pass to
6111 // MachineMemOperand::setOffset() based on the offset inputs to
6112 // an intrinsic. If any of the offsets are non-contstant or
6113 // if VIndex is non-zero then this function returns 0. Otherwise,
6114 // it returns the sum of VOffset, SOffset, and Offset.
6115 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6116  SDValue SOffset,
6117  SDValue Offset,
6118  SDValue VIndex = SDValue()) {
6119 
6120  if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6121  !isa<ConstantSDNode>(Offset))
6122  return 0;
6123 
6124  if (VIndex) {
6125  if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6126  return 0;
6127  }
6128 
6129  return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6130  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6131  cast<ConstantSDNode>(Offset)->getSExtValue();
6132 }
6133 
6134 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6135  SelectionDAG &DAG) const {
6136  unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6137  SDLoc DL(Op);
6138 
6139  switch (IntrID) {
6140  case Intrinsic::amdgcn_ds_ordered_add:
6141  case Intrinsic::amdgcn_ds_ordered_swap: {
6142  MemSDNode *M = cast<MemSDNode>(Op);
6143  SDValue Chain = M->getOperand(0);
6144  SDValue M0 = M->getOperand(2);
6145  SDValue Value = M->getOperand(3);
6146  unsigned IndexOperand = M->getConstantOperandVal(7);
6147  unsigned WaveRelease = M->getConstantOperandVal(8);
6148  unsigned WaveDone = M->getConstantOperandVal(9);
6149  unsigned ShaderType;
6150  unsigned Instruction;
6151 
6152  unsigned OrderedCountIndex = IndexOperand & 0x3f;
6153  IndexOperand &= ~0x3f;
6154  unsigned CountDw = 0;
6155 
6156  if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6157  CountDw = (IndexOperand >> 24) & 0xf;
6158  IndexOperand &= ~(0xf << 24);
6159 
6160  if (CountDw < 1 || CountDw > 4) {
6162  "ds_ordered_count: dword count must be between 1 and 4");
6163  }
6164  }
6165 
6166  if (IndexOperand)
6167  report_fatal_error("ds_ordered_count: bad index operand");
6168 
6169  switch (IntrID) {
6170  case Intrinsic::amdgcn_ds_ordered_add:
6171  Instruction = 0;
6172  break;
6173  case Intrinsic::amdgcn_ds_ordered_swap:
6174  Instruction = 1;
6175  break;
6176  }
6177 
6178  if (WaveDone && !WaveRelease)
6179  report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6180 
6181  switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6184  ShaderType = 0;
6185  break;
6187  ShaderType = 1;
6188  break;
6190  ShaderType = 2;
6191  break;
6193  ShaderType = 3;
6194  break;
6195  default:
6196  report_fatal_error("ds_ordered_count unsupported for this calling conv");
6197  }
6198 
6199  unsigned Offset0 = OrderedCountIndex << 2;
6200  unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6201  (Instruction << 4);
6202 
6203  if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6204  Offset1 |= (CountDw - 1) << 6;
6205 
6206  unsigned Offset = Offset0 | (Offset1 << 8);
6207 
6208  SDValue Ops[] = {
6209  Chain,
6210  Value,
6211  DAG.getTargetConstant(Offset, DL, MVT::i16),
6212  copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6213  };
6215  M->getVTList(), Ops, M->getMemoryVT(),
6216  M->getMemOperand());
6217  }
6218  case Intrinsic::amdgcn_ds_fadd: {
6219  MemSDNode *M = cast<MemSDNode>(Op);
6220  unsigned Opc;
6221  switch (IntrID) {
6222  case Intrinsic::amdgcn_ds_fadd:
6223  Opc = ISD::ATOMIC_LOAD_FADD;
6224  break;
6225  }
6226 
6227  return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6228  M->getOperand(0), M->getOperand(2), M->getOperand(3),
6229  M->getMemOperand());
6230  }
6231  case Intrinsic::amdgcn_atomic_inc:
6232  case Intrinsic::amdgcn_atomic_dec:
6233  case Intrinsic::amdgcn_ds_fmin:
6234  case Intrinsic::amdgcn_ds_fmax: {
6235  MemSDNode *M = cast<MemSDNode>(Op);
6236  unsigned Opc;
6237  switch (IntrID) {
6238  case Intrinsic::amdgcn_atomic_inc:
6239  Opc = AMDGPUISD::ATOMIC_INC;
6240  break;
6241  case Intrinsic::amdgcn_atomic_dec:
6242  Opc = AMDGPUISD::ATOMIC_DEC;
6243  break;
6244  case Intrinsic::amdgcn_ds_fmin:
6246  break;
6247  case Intrinsic::amdgcn_ds_fmax:
6249  break;
6250  default:
6251  llvm_unreachable("Unknown intrinsic!");
6252  }
6253  SDValue Ops[] = {
6254  M->getOperand(0), // Chain
6255  M->getOperand(2), // Ptr
6256  M->getOperand(3) // Value
6257  };
6258 
6259  return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6260  M->getMemoryVT(), M->getMemOperand());
6261  }
6262  case Intrinsic::amdgcn_buffer_load:
6263  case Intrinsic::amdgcn_buffer_load_format: {
6264  unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6265  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6266  unsigned IdxEn = 1;
6267  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6268  IdxEn = Idx->getZExtValue() != 0;
6269  SDValue Ops[] = {
6270  Op.getOperand(0), // Chain
6271  Op.getOperand(2), // rsrc
6272  Op.getOperand(3), // vindex
6273  SDValue(), // voffset -- will be set by setBufferOffsets
6274  SDValue(), // soffset -- will be set by setBufferOffsets
6275  SDValue(), // offset -- will be set by setBufferOffsets
6276  DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6277  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6278  };
6279 
6280  unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6281  // We don't know the offset if vindex is non-zero, so clear it.
6282  if (IdxEn)
6283  Offset = 0;
6284 
6285  unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6287 
6288  EVT VT = Op.getValueType();
6289  EVT IntVT = VT.changeTypeToInteger();
6290  auto *M = cast<MemSDNode>(Op);
6291  M->getMemOperand()->setOffset(Offset);
6292  EVT LoadVT = Op.getValueType();
6293 
6294  if (LoadVT.getScalarType() == MVT::f16)
6295  return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6296  M, DAG, Ops);
6297 
6298  // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6299  if (LoadVT.getScalarType() == MVT::i8 ||
6300  LoadVT.getScalarType() == MVT::i16)
6301  return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6302 
6303  return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6304  M->getMemOperand(), DAG);
6305  }
6306  case Intrinsic::amdgcn_raw_buffer_load:
6307  case Intrinsic::amdgcn_raw_buffer_load_format: {
6308  const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6309 
6310  auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6311  SDValue Ops[] = {
6312  Op.getOperand(0), // Chain
6313  Op.getOperand(2), // rsrc
6314  DAG.getConstant(0, DL, MVT::i32), // vindex
6315  Offsets.first, // voffset
6316  Op.getOperand(4), // soffset
6317  Offsets.second, // offset
6318  Op.getOperand(5), // cachepolicy, swizzled buffer
6319  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6320  };
6321 
6322  auto *M = cast<MemSDNode>(Op);
6323  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6324  return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6325  }
6326  case Intrinsic::amdgcn_struct_buffer_load:
6327  case Intrinsic::amdgcn_struct_buffer_load_format: {
6328  const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6329 
6330  auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6331  SDValue Ops[] = {
6332  Op.getOperand(0), // Chain
6333  Op.getOperand(2), // rsrc
6334  Op.getOperand(3), // vindex
6335  Offsets.first, // voffset
6336  Op.getOperand(5), // soffset
6337  Offsets.second, // offset
6338  Op.getOperand(6), // cachepolicy, swizzled buffer
6339  DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6340  };
6341 
6342  auto *M = cast<MemSDNode>(Op);
6343  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6344  Ops[2]));
6345  return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6346  }
6347  case Intrinsic::amdgcn_tbuffer_load: {
6348  MemSDNode *M = cast<MemSDNode>(Op);
6349  EVT LoadVT = Op.getValueType();
6350 
6351  unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6352  unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6353  unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6354  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6355  unsigned IdxEn = 1;
6356  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6357  IdxEn = Idx->getZExtValue() != 0;
6358  SDValue Ops[] = {
6359  Op.getOperand(0), // Chain
6360  Op.getOperand(2), // rsrc
6361  Op.getOperand(3), // vindex
6362  Op.getOperand(4), // voffset
6363  Op.getOperand(5), // soffset
6364  Op.getOperand(6), // offset
6365  DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6366  DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6367  DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6368  };
6369 
6370  if (LoadVT.getScalarType() == MVT::f16)
6371  return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6372  M, DAG, Ops);
6373  return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6374  Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6375  DAG);
6376  }
6377  case Intrinsic::amdgcn_raw_tbuffer_load: {
6378  MemSDNode *M = cast<MemSDNode>(Op);
6379  EVT LoadVT = Op.getValueType();
6380  auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6381 
6382  SDValue Ops[] = {
6383  Op.getOperand(0), // Chain
6384  Op.getOperand(2), // rsrc
6385  DAG.getConstant(0, DL, MVT::i32), // vindex
6386  Offsets.first, // voffset
6387  Op.getOperand(4), // soffset
6388  Offsets.second, // offset
6389  Op.getOperand(5), // format
6390  Op.getOperand(6), // cachepolicy, swizzled buffer
6391  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6392  };
6393 
6394  if (LoadVT.getScalarType() == MVT::f16)
6395  return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6396  M, DAG, Ops);
6397  return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6398  Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6399  DAG);
6400  }
6401  case Intrinsic::amdgcn_struct_tbuffer_load: {
6402  MemSDNode *M = cast<MemSDNode>(Op);
6403  EVT LoadVT = Op.getValueType();
6404  auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6405 
6406  SDValue Ops[] = {
6407  Op.getOperand(0), // Chain
6408  Op.getOperand(2), // rsrc
6409  Op.getOperand(3), // vindex
6410  Offsets.first, // voffset
6411  Op.getOperand(5), // soffset
6412  Offsets.second, // offset
6413  Op.getOperand(6), // format
6414  Op.getOperand(7), // cachepolicy, swizzled buffer
6415  DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6416  };
6417 
6418  if (LoadVT.getScalarType() == MVT::f16)
6419  return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6420  M, DAG, Ops);
6421  return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6422  Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6423  DAG);
6424  }
6425  case Intrinsic::amdgcn_buffer_atomic_swap:
6426  case Intrinsic::amdgcn_buffer_atomic_add:
6427  case Intrinsic::amdgcn_buffer_atomic_sub:
6428  case Intrinsic::amdgcn_buffer_atomic_smin:
6429  case Intrinsic::amdgcn_buffer_atomic_umin:
6430  case Intrinsic::amdgcn_buffer_atomic_smax:
6431  case Intrinsic::amdgcn_buffer_atomic_umax:
6432  case Intrinsic::amdgcn_buffer_atomic_and:
6433  case Intrinsic::amdgcn_buffer_atomic_or:
6434  case Intrinsic::amdgcn_buffer_atomic_xor: {
6435  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6436  unsigned IdxEn = 1;
6437  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6438  IdxEn = Idx->getZExtValue() != 0;
6439  SDValue Ops[] = {
6440  Op.getOperand(0), // Chain
6441  Op.getOperand(2), // vdata
6442  Op.getOperand(3), // rsrc
6443  Op.getOperand(4), // vindex
6444  SDValue(), // voffset -- will be set by setBufferOffsets
6445  SDValue(), // soffset -- will be set by setBufferOffsets
6446  SDValue(), // offset -- will be set by setBufferOffsets
6447  DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6448  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6449  };
6450  unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6451  // We don't know the offset if vindex is non-zero, so clear it.
6452  if (IdxEn)
6453  Offset = 0;
6454  EVT VT = Op.getValueType();
6455 
6456  auto *M = cast<MemSDNode>(Op);
6457  M->getMemOperand()->setOffset(Offset);
6458  unsigned Opcode = 0;
6459 
6460  switch (IntrID) {
6461  case Intrinsic::amdgcn_buffer_atomic_swap:
6463  break;
6464  case Intrinsic::amdgcn_buffer_atomic_add:
6466  break;
6467  case Intrinsic::amdgcn_buffer_atomic_sub:
6469  break;
6470  case Intrinsic::amdgcn_buffer_atomic_smin:
6472  break;
6473  case Intrinsic::amdgcn_buffer_atomic_umin:
6475  break;
6476  case Intrinsic::amdgcn_buffer_atomic_smax:
6478  break;
6479  case Intrinsic::amdgcn_buffer_atomic_umax:
6481  break;
6482  case Intrinsic::amdgcn_buffer_atomic_and:
6484  break;
6485  case Intrinsic::amdgcn_buffer_atomic_or:
6486  Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6487  break;
6488  case Intrinsic::amdgcn_buffer_atomic_xor:
6490  break;
6491  default:
6492  llvm_unreachable("unhandled atomic opcode");
6493  }
6494 
6495  return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6496  M->getMemOperand());
6497  }
6498  case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6499  case Intrinsic::amdgcn_raw_buffer_atomic_add:
6500  case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6501  case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6502  case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6503  case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6504  case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6505  case Intrinsic::amdgcn_raw_buffer_atomic_and:
6506  case Intrinsic::amdgcn_raw_buffer_atomic_or:
6507  case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6508  case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6509  case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6510  auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6511  SDValue Ops[] = {
6512  Op.getOperand(0), // Chain
6513  Op.getOperand(2), // vdata
6514  Op.getOperand(3), // rsrc
6515  DAG.getConstant(0, DL, MVT::i32), // vindex
6516  Offsets.first, // voffset
6517  Op.getOperand(5), // soffset
6518  Offsets.second, // offset
6519  Op.getOperand(6), // cachepolicy
6520  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6521  };
6522  EVT VT = Op.getValueType();
6523 
6524  auto *M = cast<MemSDNode>(Op);
6525  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6526  unsigned Opcode = 0;
6527 
6528  switch (IntrID) {
6529  case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6531  break;
6532  case Intrinsic::amdgcn_raw_buffer_atomic_add:
6534  break;
6535  case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6537  break;
6538  case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6540  break;
6541  case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6543  break;
6544  case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6546  break;
6547  case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6549  break;
6550  case Intrinsic::amdgcn_raw_buffer_atomic_and:
6552  break;
6553  case Intrinsic::amdgcn_raw_buffer_atomic_or:
6554  Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6555  break;
6556  case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6558  break;
6559  case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6561  break;
6562  case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6564  break;
6565  default:
6566  llvm_unreachable("unhandled atomic opcode");
6567  }
6568 
6569  return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6570  M->getMemOperand());
6571  }
6572  case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6573  case Intrinsic::amdgcn_struct_buffer_atomic_add:
6574  case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6575  case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6576  case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6577  case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6578  case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6579  case Intrinsic::amdgcn_struct_buffer_atomic_and:
6580  case Intrinsic::amdgcn_struct_buffer_atomic_or:
6581  case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6582  case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6583  case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6584  auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6585  SDValue Ops[] = {
6586  Op.getOperand(0), // Chain
6587  Op.getOperand(2), // vdata
6588  Op.getOperand(3), // rsrc
6589  Op.getOperand(4), // vindex
6590  Offsets.first, // voffset
6591  Op.getOperand(6), // soffset
6592  Offsets.second, // offset
6593  Op.getOperand(7), // cachepolicy
6594  DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6595  };
6596  EVT VT = Op.getValueType();
6597 
6598  auto *M = cast<MemSDNode>(Op);
6599  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6600  Ops[3]));
6601  unsigned Opcode = 0;
6602 
6603  switch (IntrID) {
6604  case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6606  break;
6607  case Intrinsic::amdgcn_struct_buffer_atomic_add:
6609  break;
6610  case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6612  break;
6613  case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6615  break;
6616  case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6618  break;
6619  case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6621  break;
6622  case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6624  break;
6625  case Intrinsic::amdgcn_struct_buffer_atomic_and:
6627  break;
6628  case Intrinsic::amdgcn_struct_buffer_atomic_or:
6629  Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6630  break;
6631  case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6633  break;
6634  case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6636  break;
6637  case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6639  break;
6640  default:
6641  llvm_unreachable("unhandled atomic opcode");
6642  }
6643 
6644  return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6645  M->getMemOperand());
6646  }
6647  case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6648  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6649  unsigned IdxEn = 1;
6650  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6651  IdxEn = Idx->getZExtValue() != 0;
6652  SDValue Ops[] = {
6653  Op.getOperand(0), // Chain
6654  Op.getOperand(2), // src
6655  Op.getOperand(3), // cmp
6656  Op.getOperand(4), // rsrc
6657  Op.getOperand(5), // vindex
6658  SDValue(), // voffset -- will be set by setBufferOffsets
6659  SDValue(), // soffset -- will be set by setBufferOffsets
6660  SDValue(), // offset -- will be set by setBufferOffsets
6661  DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6662  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6663  };
6664  unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6665  // We don't know the offset if vindex is non-zero, so clear it.
6666  if (IdxEn)
6667  Offset = 0;
6668  EVT VT = Op.getValueType();
6669  auto *M = cast<MemSDNode>(Op);
6670  M->getMemOperand()->setOffset(Offset);
6671 
6673  Op->getVTList(), Ops, VT, M->getMemOperand());
6674  }
6675  case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6676  auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6677  SDValue Ops[] = {
6678  Op.getOperand(0), // Chain
6679  Op.getOperand(2), // src
6680  Op.getOperand(3), // cmp
6681  Op.getOperand(4), // rsrc
6682  DAG.getConstant(0, DL, MVT::i32), // vindex
6683  Offsets.first, // voffset
6684  Op.getOperand(6), // soffset
6685  Offsets.second, // offset
6686  Op.getOperand(7), // cachepolicy
6687  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6688  };
6689  EVT VT = Op.getValueType();
6690  auto *M = cast<MemSDNode>(Op);
6691  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6692 
6694  Op->getVTList(), Ops, VT, M->getMemOperand());
6695  }
6696  case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6697  auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6698  SDValue Ops[] = {
6699  Op.getOperand(0), // Chain
6700  Op.getOperand(2), // src
6701  Op.getOperand(3), // cmp
6702  Op.getOperand(4), // rsrc
6703  Op.getOperand(5), // vindex
6704  Offsets.first, // voffset
6705  Op.getOperand(7), // soffset
6706  Offsets.second, // offset
6707  Op.getOperand(8), // cachepolicy
6708  DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6709  };
6710  EVT VT = Op.getValueType();
6711  auto *M = cast<MemSDNode>(Op);
6712  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6713  Ops[4]));
6714 
6716  Op->getVTList(), Ops, VT, M->getMemOperand());
6717  }
6718 
6719  default:
6720  if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6722  return lowerImage(Op, ImageDimIntr, DAG);
6723 
6724  return SDValue();
6725  }
6726 }
6727 
6728 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6729 // dwordx4 if on SI.
6730 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6731  SDVTList VTList,
6732  ArrayRef<SDValue> Ops, EVT MemVT,
6733  MachineMemOperand *MMO,
6734  SelectionDAG &DAG) const {
6735  EVT VT = VTList.VTs[0];
6736  EVT WidenedVT = VT;
6737  EVT WidenedMemVT = MemVT;
6738  if (!Subtarget->hasDwordx3LoadStores() &&
6739  (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6740  WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6741  WidenedVT.getVectorElementType(), 4);
6742  WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6743  WidenedMemVT.getVectorElementType(), 4);
6744  MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6745  }
6746 
6747  assert(VTList.NumVTs == 2);
6748  SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6749 
6750  auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6751  WidenedMemVT, MMO);
6752  if (WidenedVT != VT) {
6753  auto Extract = DAG.getNode(
6754  ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6755  DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6756  NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6757  }
6758  return NewOp;
6759 }
6760 
6761 SDValue SITargetLowering::handleD16VData(SDValue VData,
6762  SelectionDAG &DAG) const {
6763  EVT StoreVT = VData.getValueType();
6764 
6765  // No change for f16 and legal vector D16 types.
6766  if (!StoreVT.isVector())
6767  return VData;
6768 
6769  SDLoc DL(VData);
6770  assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6771 
6772  if (Subtarget->hasUnpackedD16VMem()) {
6773  // We need to unpack the packed data to store.
6774  EVT IntStoreVT = StoreVT.changeTypeToInteger();
6775  SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6776 
6777  EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6778  StoreVT.getVectorNumElements());
6779  SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6780  return DAG.UnrollVectorOp(ZExt.getNode());
6781  }
6782 
6783  assert(isTypeLegal(StoreVT));
6784  return VData;
6785 }
6786 
6787 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6788  SelectionDAG &DAG) const {
6789  SDLoc DL(Op);
6790  SDValue Chain = Op.getOperand(0);
6791  unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6792  MachineFunction &MF = DAG.getMachineFunction();
6793 
6794  switch (IntrinsicID) {
6795  case Intrinsic::amdgcn_exp: {
6796  const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6797  const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6798  const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6799  const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6800 
6801  const SDValue Ops[] = {
6802  Chain,
6803  DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6804  DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6805  Op.getOperand(4), // src0
6806  Op.getOperand(5), // src1
6807  Op.getOperand(6), // src2
6808  Op.getOperand(7), // src3
6809  DAG.getTargetConstant(0, DL, MVT::i1), // compr
6810  DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6811  };
6812 
6813  unsigned Opc = Done->isNullValue() ?
6815  return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6816  }
6817  case Intrinsic::amdgcn_exp_compr: {
6818  const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6819  const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6820  SDValue Src0 = Op.getOperand(4);
6821  SDValue Src1 = Op.getOperand(5);
6822  const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6823  const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6824 
6825  SDValue Undef = DAG.getUNDEF(MVT::f32);
6826  const SDValue Ops[] = {
6827  Chain,
6828  DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6829  DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6830  DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6831  DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6832  Undef, // src2
6833  Undef, // src3
6834  DAG.getTargetConstant(1, DL, MVT::i1), // compr
6835  DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6836  };
6837 
6838  unsigned Opc = Done->isNullValue() ?
6840  return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6841  }
6842  case Intrinsic::amdgcn_s_barrier: {
6844  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6845  unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6846  if (WGSize <= ST.getWavefrontSize())
6847  return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6848  Op.getOperand(0)), 0);
6849  }
6850  return SDValue();
6851  };
6852  case Intrinsic::amdgcn_tbuffer_store: {
6853  SDValue VData = Op.getOperand(2);
6854  bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6855  if (IsD16)
6856  VData = handleD16VData(VData, DAG);
6857  unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6858  unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6859  unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6860  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6861  unsigned IdxEn = 1;
6862  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6863  IdxEn = Idx->getZExtValue() != 0;
6864  SDValue Ops[] = {
6865  Chain,
6866  VData, // vdata
6867  Op.getOperand(3), // rsrc
6868  Op.getOperand(4), // vindex
6869  Op.getOperand(5), // voffset
6870  Op.getOperand(6), // soffset
6871  Op.getOperand(7), // offset
6872  DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6873  DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6874  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6875  };
6876  unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6878  MemSDNode *M = cast<MemSDNode>(Op);
6879  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6880  M->getMemoryVT(), M->getMemOperand());
6881  }
6882 
6883  case Intrinsic::amdgcn_struct_tbuffer_store: {
6884  SDValue VData = Op.getOperand(2);
6885  bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6886  if (IsD16)
6887  VData = handleD16VData(VData, DAG);
6888  auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6889  SDValue Ops[] = {
6890  Chain,
6891  VData, // vdata
6892  Op.getOperand(3), // rsrc
6893  Op.getOperand(4), // vindex
6894  Offsets.first, // voffset
6895  Op.getOperand(6), // soffset
6896  Offsets.second, // offset
6897  Op.getOperand(7), // format
6898  Op.getOperand(8), // cachepolicy, swizzled buffer
6899  DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6900  };
6901  unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6903  MemSDNode *M = cast<MemSDNode>(Op);
6904  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6905  M->getMemoryVT(), M->getMemOperand());
6906  }
6907 
6908  case Intrinsic::amdgcn_raw_tbuffer_store: {
6909  SDValue VData = Op.getOperand(2);
6910  bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6911  if (IsD16)
6912  VData = handleD16VData(VData, DAG);
6913  auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6914  SDValue Ops[] = {
6915  Chain,
6916  VData, // vdata
6917  Op.getOperand(3), // rsrc
6918  DAG.getConstant(0, DL, MVT::i32), // vindex
6919  Offsets.first, // voffset
6920  Op.getOperand(5), // soffset
6921  Offsets.second, // offset
6922  Op.getOperand(6), // format
6923  Op.getOperand(7), // cachepolicy, swizzled buffer
6924  DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6925  };
6926  unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6928  MemSDNode *M = cast<MemSDNode>(Op);
6929  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6930  M->getMemoryVT(), M->getMemOperand());
6931  }
6932 
6933  case Intrinsic::amdgcn_buffer_store:
6934  case Intrinsic::amdgcn_buffer_store_format: {
6935  SDValue VData = Op.getOperand(2);
6936  bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6937  if (IsD16)
6938  VData = handleD16VData(VData, DAG);
6939  unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6940  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6941  unsigned IdxEn = 1;
6942  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6943  IdxEn = Idx->getZExtValue() != 0;
6944  SDValue Ops[] = {
6945  Chain,
6946  VData,
6947  Op.getOperand(3), // rsrc
6948  Op.getOperand(4), // vindex
6949  SDValue(), // voffset -- will be set by setBufferOffsets
6950  SDValue(), // soffset -- will be set by setBufferOffsets
6951  SDValue(), // offset -- will be set by setBufferOffsets
6952  DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6953  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6954  };
6955  unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6956  // We don't know the offset if vindex is non-zero, so clear it.
6957  if (IdxEn)
6958  Offset = 0;
6959  unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6961  Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6962  MemSDNode *M = cast<MemSDNode>(Op);
6963  M->getMemOperand()->setOffset(Offset);
6964 
6965  // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6966  EVT VDataType = VData.getValueType().getScalarType();
6967  if (VDataType == MVT::i8 || VDataType == MVT::i16)
6968  return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6969 
6970  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6971  M->getMemoryVT(), M->getMemOperand());
6972  }
6973 
6974  case Intrinsic::amdgcn_raw_buffer_store:
6975  case Intrinsic::amdgcn_raw_buffer_store_format: {
6976  const bool IsFormat =
6977  IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6978 
6979  SDValue VData = Op.getOperand(2);
6980  EVT VDataVT = VData.getValueType();
6981  EVT EltType = VDataVT.getScalarType();
6982  bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6983  if (IsD16)
6984  VData = handleD16VData(VData, DAG);
6985 
6986  if (!isTypeLegal(VDataVT)) {
6987  VData =
6988  DAG.getNode(ISD::BITCAST, DL,
6989  getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6990  }
6991 
6992  auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6993  SDValue Ops[] = {
6994  Chain,
6995  VData,
6996  Op.getOperand(3), // rsrc
6997  DAG.getConstant(0, DL, MVT::i32), // vindex
6998  Offsets.first, // voffset
6999  Op.getOperand(5), // soffset
7000  Offsets.second, // offset
7001  Op.getOperand(6), // cachepolicy, swizzled buffer
7002  DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7003  };
7004  unsigned Opc =
7006  Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7007  MemSDNode *M = cast<MemSDNode>(Op);
7008  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7009 
7010  // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7011  if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7012  return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7013 
7014  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7015  M->getMemoryVT(), M->getMemOperand());
7016  }
7017 
7018  case Intrinsic::amdgcn_struct_buffer_store:
7019  case Intrinsic::amdgcn_struct_buffer_store_format: {
7020  const bool IsFormat =
7021  IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7022 
7023  SDValue VData = Op.getOperand(2);
7024  EVT VDataVT = VData.getValueType();
7025  EVT EltType = VDataVT.getScalarType();
7026  bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7027 
7028  if (IsD16)
7029  VData = handleD16VData(VData, DAG);
7030 
7031  if (!isTypeLegal(VDataVT)) {
7032  VData =
7033  DAG.getNode(ISD::BITCAST, DL,
7034  getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7035  }
7036 
7037  auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7038  SDValue Ops[] = {
7039  Chain,
7040  VData,
7041  Op.getOperand(3), // rsrc
7042  Op.getOperand(4), // vindex
7043  Offsets.first, // voffset
7044  Op.getOperand(6), // soffset
7045  Offsets.second, // offset
7046  Op.getOperand(7), // cachepolicy, swizzled buffer
7047  DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7048  };
7049  unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7051  Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7052  MemSDNode *M = cast<MemSDNode>(Op);
7053  M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7054  Ops[3]));
7055 
7056  // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7057  EVT VDataType = VData.getValueType().getScalarType();
7058  if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7059  return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7060 
7061  return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7062  M->getMemoryVT(), M->getMemOperand());
7063  }
7064 
7065  case Intrinsic::amdgcn_buffer_atomic_fadd: {
7066  unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7067  unsigned IdxEn = 1;
7068  if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7069  IdxEn = Idx->getZExtValue() != 0;
7070  SDValue Ops[] = {
7071  Chain,
7072  Op.getOperand(2), // vdata
7073  Op.getOperand(3), // rsrc
7074  Op.getOperand(4), // vindex
7075  SDValue(), // voffset -- will be set by setBufferOffsets
7076  SDValue(), // soffset -- will be set by setBufferOffsets
7077  SDValue(), // offset -- will be set by setBufferOffsets
7078  DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7079  DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7080  };
7081  unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7082  // We don't know the offset if vindex is non-zero, so clear it.
7083  if (IdxEn)
7084  Offset = 0;
7085  EVT VT = Op.getOperand(2).getValueType();
7086 
7087  auto *M = cast<MemSDNode>(Op);
7088  M->getMemOperand()->setOffset(Offset);
7089  unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7091 
7092  return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7093  M->getMemOperand());
7094  }
7095 
7096  case Intrinsic::amdgcn_global_atomic_fadd: {
7097  SDValue Ops[] = {
7098  Chain,
7099  Op.getOperand(2), // ptr
7100  Op.getOperand(3) // vdata
7101  };
7102  EVT VT = Op.getOperand(3).getValueType();
7103 
7104  auto *M = cast<MemSDNode>(Op);
7105  if (VT.isVector()) {
7106  return DAG.getMemIntrinsicNode(
7107  AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7108  M->getMemOperand());
7109  }
7110 
7111  return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7112  DAG.getVTList(VT, MVT::Other), Ops,
7113  M->getMemOperand()).getValue(1);
7114  }
7115  case Intrinsic::amdgcn_end_cf:
7116  return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7117  Op->getOperand(2), Chain), 0);
7118 
7119  default: {
7120  if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7121  AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7122  return lowerImage(Op, ImageDimIntr, DAG);
7123 
7124  return Op;
7125  }
7126  }
7127 }
7128 
7129 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7130 // offset (the offset that is included in bounds checking and swizzling, to be
7131 // split between the instruction's voffset and immoffset fields) and soffset
7132 // (the offset that is excluded from bounds checking and swizzling, to go in
7133 // the instruction's soffset field). This function takes the first kind of
7134 // offset and figures out how to split it between voffset and immoffset.
7135 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7136  SDValue Offset, SelectionDAG &DAG) const {
7137  SDLoc DL(Offset);
7138  const unsigned MaxImm = 4095;
7139  SDValue N0 = Offset;
7140  ConstantSDNode *C1 = nullptr;
7141 
7142  if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7143  N0 = SDValue();
7144  else if (DAG.isBaseWithConstantOffset(N0)) {
7145  C1 = cast<ConstantSDNode>(N0.getOperand(1));
7146  N0 = N0.getOperand(0);
7147  }
7148 
7149  if (C1) {
7150  unsigned ImmOffset = C1->getZExtValue();
7151  // If the immediate value is too big for the immoffset field, put the value
7152  // and -4096 into the immoffset field so that the value that is copied/added
7153  // for the voffset field is a multiple of 4096, and it stands more chance
7154  // of being CSEd with the copy/add for another similar load/store.
7155  // However, do not do that rounding down to a multiple of 4096 if that is a
7156  // negative number, as it appears to be illegal to have a negative offset
7157  // in the vgpr, even if adding the immediate offset makes it positive.
7158  unsigned Overflow = ImmOffset & ~MaxImm;
7159  ImmOffset -= Overflow;
7160  if ((int32_t)Overflow < 0) {
7161  Overflow += ImmOffset;
7162  ImmOffset = 0;
7163  }
7164  C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7165  if (Overflow) {
7166  auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7167  if (!N0)
7168  N0 = OverflowVal;
7169  else {
7170  SDValue Ops[] = { N0, OverflowVal };
7171  N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7172  }
7173  }
7174  }
7175  if (!N0)
7176  N0 = DAG.getConstant(0, DL, MVT::i32);
7177  if (!C1)
7178  C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7179  return {N0, SDValue(C1, 0)};
7180 }
7181 
7182 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7183 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7184 // pointed to by Offsets.
7185 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7186  SelectionDAG &DAG, SDValue *Offsets,
7187  unsigned Align) const {
7188  SDLoc DL(CombinedOffset);
7189  if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7190  uint32_t Imm = C->getZExtValue();
7191  uint32_t SOffset, ImmOffset;
7192  if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7193  Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7194  Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7195  Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7196  return SOffset + ImmOffset;
7197  }
7198  }
7199  if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7200  SDValue N0 = CombinedOffset.getOperand(0);
7201  SDValue N1 = CombinedOffset.getOperand(1);
7202  uint32_t SOffset, ImmOffset;
7203  int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7204  if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7205  Subtarget, Align)) {
7206  Offsets[0] = N0;
7207  Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7208  Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7209  return 0;
7210  }
7211  }
7212  Offsets[0] = CombinedOffset;
7213  Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7214  Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7215  return 0;
7216 }
7217 
7218 // Handle 8 bit and 16 bit buffer loads
7219 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7220  EVT LoadVT, SDLoc DL,
7221  ArrayRef<SDValue> Ops,
7222  MemSDNode *M) const {
7223  EVT IntVT = LoadVT.changeTypeToInteger();
7224  unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7226 
7227  SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7228  SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7229  Ops, IntVT,
7230  M->getMemOperand());
7231  SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7232  LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7233 
7234  return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7235 }
7236 
7237 // Handle 8 bit and 16 bit buffer stores
7238 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7239  EVT VDataType, SDLoc DL,
7240  SDValue Ops[],
7241  MemSDNode *M) const {
7242  if (VDataType == MVT::f16)
7243  Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7244 
7245  SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7246  Ops[1] = BufferStoreExt;
7247  unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7249  ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7250  return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7251  M->getMemOperand());
7252 }
7253 
7256  const SDLoc &SL, EVT VT) {
7257  if (VT.bitsLT(Op.getValueType()))
7258  return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7259 
7260  switch (ExtType) {
7261  case ISD::SEXTLOAD:
7262  return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7263  case ISD::ZEXTLOAD:
7264  return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7265  case ISD::EXTLOAD:
7266  return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7267  case ISD::NON_EXTLOAD:
7268  return Op;
7269  }
7270 
7271  llvm_unreachable("invalid ext type");
7272 }
7273 
7274 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7275  SelectionDAG &DAG = DCI.DAG;
7276  if (Ld->getAlignment() < 4 || Ld->isDivergent())
7277  return SDValue();
7278 
7279  // FIXME: Constant loads should all be marked invariant.
7280  unsigned AS = Ld->getAddressSpace();
7281  if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7283  (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7284  return SDValue();
7285 
7286  // Don't do this early, since it may interfere with adjacent load merging for
7287  // illegal types. We can avoid losing alignment information for exotic types
7288  // pre-legalize.
7289  EVT MemVT = Ld->getMemoryVT();
7290  if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7291  MemVT.getSizeInBits() >= 32)
7292  return SDValue();
7293 
7294  SDLoc SL(Ld);
7295 
7296  assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7297  "unexpected vector extload");
7298 
7299  // TODO: Drop only high part of range.
7300  SDValue Ptr = Ld->getBasePtr();
7302  MVT::i32, SL, Ld->getChain(), Ptr,
7303  Ld->getOffset(),
7304  Ld->getPointerInfo(), MVT::i32,
7305  Ld->getAlignment(),
7306  Ld->getMemOperand()->getFlags(),
7307  Ld->getAAInfo(),
7308  nullptr); // Drop ranges
7309 
7310  EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7311  if (MemVT.isFloatingPoint()) {
7313  "unexpected fp extload");
7314  TruncVT = MemVT.changeTypeToInteger();
7315  }
7316 
7317  SDValue Cvt = NewLoad;
7318  if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7319  Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7320  DAG.getValueType(TruncVT));
7321  } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7323  Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7324  } else {
7326  }
7327 
7328  EVT VT = Ld->getValueType(0);
7329  EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7330 
7331  DCI.AddToWorklist(Cvt.getNode());
7332 
7333  // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7334  // the appropriate extension from the 32-bit load.
7335  Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7336  DCI.AddToWorklist(Cvt.getNode());
7337 
7338  // Handle conversion back to floating point if necessary.
7339  Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7340 
7341  return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7342 }
7343 
7344 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7345  SDLoc DL(Op);
7346  LoadSDNode *Load = cast<LoadSDNode>(Op);
7348  EVT MemVT = Load->getMemoryVT();
7349 
7350  if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7351  if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7352  return SDValue();
7353 
7354  // FIXME: Copied from PPC
7355  // First, load into 32 bits, then truncate to 1 bit.
7356 
7357  SDValue Chain = Load->getChain();
7358  SDValue BasePtr = Load->getBasePtr();
7359  MachineMemOperand *MMO = Load->getMemOperand();
7360 
7361  EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7362 
7363  SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7364  BasePtr, RealMemVT, MMO);
7365 
7366  if (!MemVT.isVector()) {
7367  SDValue Ops[] = {
7368  DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7369  NewLD.getValue(1)
7370  };
7371 
7372  return DAG.getMergeValues(Ops, DL);
7373  }
7374 
7376  for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7377  SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7378  DAG.getConstant(I, DL, MVT::i32));
7379 
7380  Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7381  }
7382 
7383  SDValue Ops[] = {
7384  DAG.getBuildVector(MemVT, DL, Elts),
7385  NewLD.getValue(1)
7386  };
7387 
7388  return DAG.getMergeValues(Ops, DL);
7389  }
7390 
7391  if (!MemVT.isVector())
7392  return SDValue();
7393 
7395  "Custom lowering for non-i32 vectors hasn't been implemented.");
7396 
7398  MemVT, *Load->getMemOperand())) {
7399  SDValue Ops[2];
7400  std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7401  return DAG.getMergeValues(Ops, DL);
7402  }
7403 
7404  unsigned Alignment = Load->getAlignment();
7405  unsigned AS = Load->getAddressSpace();
7406  if (Subtarget->hasLDSMisalignedBug() &&
7407  AS == AMDGPUAS::FLAT_ADDRESS &&
7408  Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7409  return SplitVectorLoad(Op, DAG);
7410  }
7411 
7412  MachineFunction &MF = DAG.getMachineFunction();
7414  // If there is a possibilty that flat instruction access scratch memory
7415  // then we need to use the same legalization rules we use for private.
7416  if (AS == AMDGPUAS::FLAT_ADDRESS)
7417  AS = MFI->hasFlatScratchInit() ?
7419 
7420  unsigned NumElements = MemVT.getVectorNumElements();
7421 
7422  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7424  if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7425  if (MemVT.isPow2VectorType())
7426  return SDValue();
7427  if (NumElements == 3)
7428  return WidenVectorLoad(Op, DAG);
7429  return SplitVectorLoad(Op, DAG);
7430  }
7431  // Non-uniform loads will be selected to MUBUF instructions, so they
7432  // have the same legalization requirements as global and private
7433  // loads.
7434  //
7435  }
7436 
7437  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7439  AS == AMDGPUAS::GLOBAL_ADDRESS) {
7440  if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7441  !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7442  Alignment >= 4 && NumElements < 32) {
7443  if (MemVT.isPow2VectorType())
7444  return SDValue();
7445  if (NumElements == 3)
7446  return WidenVectorLoad(Op, DAG);
7447  return SplitVectorLoad(Op, DAG);
7448  }
7449  // Non-uniform loads will be selected to MUBUF instructions, so they
7450  // have the same legalization requirements as global and private
7451  // loads.
7452  //
7453  }
7454  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7456  AS == AMDGPUAS::GLOBAL_ADDRESS ||
7457  AS == AMDGPUAS::FLAT_ADDRESS) {
7458  if (NumElements > 4)
7459  return SplitVectorLoad(Op, DAG);
7460  // v3 loads not supported on SI.
7461  if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7462  return WidenVectorLoad(Op, DAG);
7463  // v3 and v4 loads are supported for private and global memory.
7464  return SDValue();
7465  }
7466  if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7467  // Depending on the setting of the private_element_size field in the
7468  // resource descriptor, we can only make private accesses up to a certain
7469  // size.
7470  switch (Subtarget->getMaxPrivateElementSize()) {
7471  case 4: {
7472  SDValue Ops[2];
7473  std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7474  return DAG.getMergeValues(Ops, DL);
7475  }
7476  case 8:
7477  if (NumElements > 2)
7478  return SplitVectorLoad(Op, DAG);
7479  return SDValue();
7480  case 16:
7481  // Same as global/flat
7482  if (NumElements > 4)
7483  return SplitVectorLoad(Op, DAG);
7484  // v3 loads not supported on SI.
7485  if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7486  return WidenVectorLoad(Op, DAG);
7487  return SDValue();
7488  default:
7489  llvm_unreachable("unsupported private_element_size");
7490  }
7491  } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7492  // Use ds_read_b128 if possible.
7493  if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7494  MemVT.getStoreSize() == 16)
7495  return SDValue();
7496 
7497  if (NumElements > 2)
7498  return SplitVectorLoad(Op, DAG);
7499 
7500  // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7501  // address is negative, then the instruction is incorrectly treated as
7502  // out-of-bounds even if base + offsets is in bounds. Split vectorized
7503  // loads here to avoid emitting ds_read2_b32. We may re-combine the
7504  // load later in the SILoadStoreOptimizer.
7505  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7506  NumElements == 2 && MemVT.getStoreSize() == 8 &&
7507  Load->getAlignment() < 8) {
7508  return SplitVectorLoad(Op, DAG);
7509  }
7510  }
7511  return SDValue();
7512 }
7513 
7514 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7515  EVT VT = Op.getValueType();
7516  assert(VT.getSizeInBits() == 64);
7517 
7518  SDLoc DL(Op);
7519  SDValue Cond = Op.getOperand(0);
7520 
7521  SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7522  SDValue One = DAG.getConstant(1, DL, MVT::i32);
7523 
7524  SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7525  SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7526 
7527  SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7528  SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7529 
7530  SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7531 
7532  SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7533  SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7534 
7535  SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7536 
7537  SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7538  return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7539 }
7540 
7541 // Catch division cases where we can use shortcuts with rcp and rsq
7542 // instructions.
7543 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7544  SelectionDAG &DAG) const {
7545  SDLoc SL(Op);
7546  SDValue LHS = Op.getOperand(0);
7547  SDValue RHS = Op.getOperand(1);
7548  EVT VT = Op.getValueType();
7549  const SDNodeFlags Flags = Op->getFlags();
7550  bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7551 
7552  if (!Unsafe && VT == MVT::f32 && hasFP32Denormals(DAG.getMachineFunction()))
7553  return SDValue();
7554 
7555  if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7556  if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7557  if (CLHS->isExactlyValue(1.0)) {
7558  // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7559  // the CI documentation has a worst case error of 1 ulp.
7560  // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7561  // use it as long as we aren't trying to use denormals.
7562  //
7563  // v_rcp_f16 and v_rsq_f16 DO support denormals.
7564 
7565  // 1.0 / sqrt(x) -> rsq(x)
7566 
7567  // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7568  // error seems really high at 2^29 ULP.
7569  if (RHS.getOpcode() == ISD::FSQRT)
7570  return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7571 
7572  // 1.0 / x -> rcp(x)
7573  return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7574  }
7575 
7576  // Same as for 1.0, but expand the sign out of the constant.
7577  if (CLHS->isExactlyValue(-1.0)) {
7578  // -1.0 / x -> rcp (fneg x)
7579  SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7580  return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7581  }
7582  }
7583  }
7584 
7585  if (Unsafe) {
7586  // Turn into multiply by the reciprocal.
7587  // x / y -> x * (1.0 / y)
7588  SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7589  return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7590  }
7591 
7592  return SDValue();
7593 }
7594 
7595 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7596  EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7597  if (GlueChain->getNumValues() <= 1) {
7598  return DAG.getNode(Opcode, SL, VT, A, B);
7599  }
7600 
7601  assert(GlueChain->getNumValues() == 3);
7602 
7603  SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7604  switch (Opcode) {
7605  default: llvm_unreachable("no chain equivalent for opcode");
7606  case ISD::FMUL:
7607  Opcode = AMDGPUISD::FMUL_W_CHAIN;
7608  break;
7609  }
7610 
7611  return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7612  GlueChain.getValue(2));
7613 }
7614 
7615 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7616  EVT VT, SDValue A, SDValue B, SDValue C,
7617  SDValue GlueChain) {
7618  if (GlueChain->getNumValues() <= 1) {
7619  return DAG.getNode(Opcode, SL, VT, A, B, C);
7620  }
7621 
7622  assert(GlueChain->getNumValues() == 3);
7623 
7624  SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7625  switch (Opcode) {
7626  default: llvm_unreachable("no chain equivalent for opcode");
7627  case ISD::FMA:
7628  Opcode = AMDGPUISD::FMA_W_CHAIN;
7629  break;
7630  }
7631 
7632  return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7633  GlueChain.getValue(2));
7634 }
7635 
7636 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7637  if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7638  return FastLowered;
7639 
7640  SDLoc SL(Op);
7641  SDValue Src0 = Op.getOperand(0);
7642  SDValue Src1 = Op.getOperand(1);
7643 
7644  SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7645  SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7646 
7647  SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7648  SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7649 
7650  SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7651  SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7652 
7653  return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7654 }
7655 
7656 // Faster 2.5 ULP division that does not support denormals.
7657 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7658  SDLoc SL(Op);
7659  SDValue LHS = Op.getOperand(1);
7660  SDValue RHS = Op.getOperand(2);
7661 
7662  SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7663 
7664  const APFloat K0Val(BitsToFloat(0x6f800000));
7665  const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7666 
7667  const APFloat K1Val(BitsToFloat(0x2f800000));
7668  const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7669 
7670  const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7671 
7672  EVT SetCCVT =
7674 
7675  SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7676 
7677  SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7678 
7679  // TODO: Should this propagate fast-math-flags?
7680  r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7681 
7682  // rcp does not support denormals.
7683  SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7684 
7685  SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7686 
7687  return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7688 }
7689 
7690 // Returns immediate value for setting the F32 denorm mode when using the
7691 // S_DENORM_MODE instruction.
7692 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7693  const SDLoc &SL, const GCNSubtarget *ST) {
7694  assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7695  int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7698 
7699  int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7700  return DAG.getTargetConstant(Mode, SL, MVT::i32);
7701 }
7702 
7703 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7704  if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7705  return FastLowered;
7706 
7707  SDLoc SL(Op);
7708  SDValue LHS = Op.getOperand(0);
7709  SDValue RHS = Op.getOperand(1);
7710 
7711  const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7712 
7713  SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7714 
7715  SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7716  RHS, RHS, LHS);
7717  SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7718  LHS, RHS, LHS);
7719 
7720  // Denominator is scaled to not be denormal, so using rcp is ok.
7721  SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7722  DenominatorScaled);
7723  SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7724  DenominatorScaled);
7725 
7726  const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7729  const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7730 
7731  const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7732 
7733  if (!HasFP32Denormals) {
7734  SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7735 
7736  SDValue EnableDenorm;
7737  if (Subtarget->hasDenormModeInst()) {
7738  const SDValue EnableDenormValue =
7739  getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7740 
7741  EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7742  DAG.getEntryNode(), EnableDenormValue);
7743  } else {
7744  const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7745  SL, MVT::i32);
7746  EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7747  DAG.getEntryNode(), EnableDenormValue,
7748  BitField);
7749  }
7750 
7751  SDValue Ops[3] = {
7752  NegDivScale0,
7753  EnableDenorm.getValue(0),
7754  EnableDenorm.getValue(1)
7755  };
7756 
7757  NegDivScale0 = DAG.getMergeValues(Ops, SL);
7758  }
7759 
7760  SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7761  ApproxRcp, One, NegDivScale0);
7762 
7763  SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7764  ApproxRcp, Fma0);
7765 
7766  SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7767  Fma1, Fma1);
7768 
7769  SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7770  NumeratorScaled, Mul);
7771 
7772  SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7773 
7774  SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7775  NumeratorScaled, Fma3);
7776 
7777  if (!HasFP32Denormals) {
7778  SDValue DisableDenorm;
7779  if (Subtarget->hasDenormModeInst()) {
7780  const SDValue DisableDenormValue =
7782 
7783  DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7784  Fma4.getValue(1), DisableDenormValue,
7785  Fma4.getValue(2));
7786  } else {
7787  const SDValue DisableDenormValue =
7789 
7790  DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7791  Fma4.getValue(1), DisableDenormValue,
7792  BitField, Fma4.getValue(2));
7793  }
7794 
7795  SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7796  DisableDenorm, DAG.getRoot());
7797  DAG.setRoot(OutputChain);
7798  }
7799 
7800  SDValue Scale = NumeratorScaled.getValue(1);
7801  SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7802  Fma4, Fma1, Fma3, Scale);
7803 
7804  return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7805 }
7806 
7807 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7808  if (DAG.getTarget().Options.UnsafeFPMath)
7809  return lowerFastUnsafeFDIV(Op, DAG);
7810 
7811  SDLoc SL(Op);
7812  SDValue X = Op.getOperand(0);
7813  SDValue Y = Op.getOperand(1);
7814 
7815  const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7816 
7817  SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7818 
7819  SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7820 
7821  SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7822 
7823  SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7824 
7825  SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7826 
7827  SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7828 
7829  SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7830 
7831  SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7832 
7833  SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7834  SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7835 
7836  SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7837  NegDivScale0, Mul, DivScale1);
7838 
7839  SDValue Scale;
7840 
7841  if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7842  // Workaround a hardware bug on SI where the condition output from div_scale
7843  // is not usable.
7844 
7845  const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7846 
7847  // Figure out if the scale to use for div_fmas.
7848  SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7849  SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7850  SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7851  SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7852 
7853  SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7854  SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7855 
7856  SDValue Scale0Hi
7857  = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7858  SDValue Scale1Hi
7859  = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7860 
7861  SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7862  SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7863  Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7864  } else {
7865  Scale = DivScale1.getValue(1);
7866  }
7867 
7868  SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7869  Fma4, Fma3, Mul, Scale);
7870 
7871  return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7872 }
7873 
7874 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7875  EVT VT = Op.getValueType();
7876 
7877  if (VT == MVT::f32)
7878  return LowerFDIV32(Op, DAG);
7879 
7880  if (VT == MVT::f64)
7881  return LowerFDIV64(Op, DAG);
7882 
7883  if (VT == MVT::f16)
7884  return LowerFDIV16(Op, DAG);
7885 
7886  llvm_unreachable("Unexpected type for fdiv");
7887 }
7888 
7889 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7890  SDLoc DL(Op);
7891  StoreSDNode *Store = cast<StoreSDNode>(Op);
7892  EVT VT = Store->getMemoryVT();
7893 
7894  if (VT == MVT::i1) {
7895  return DAG.getTruncStore(Store->getChain(), DL,
7896  DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7897  Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7898  }
7899 
7900  assert(VT.isVector() &&
7901  Store->getValue().getValueType().getScalarType() == MVT::i32);
7902 
7904  VT, *Store->getMemOperand())) {
7905  return expandUnalignedStore(Store, DAG);
7906  }
7907 
7908  unsigned AS = Store->getAddressSpace();
7909  if (Subtarget->hasLDSMisalignedBug() &&
7910  AS == AMDGPUAS::FLAT_ADDRESS &&
7911  Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7912  return SplitVectorStore(Op, DAG);
7913  }
7914 
7915  MachineFunction &MF = DAG.getMachineFunction();
7917  // If there is a possibilty that flat instruction access scratch memory
7918  // then we need to use the same legalization rules we use for private.
7919  if (AS == AMDGPUAS::FLAT_ADDRESS)
7920  AS = MFI->hasFlatScratchInit() ?
7922 
7923  unsigned NumElements = VT.getVectorNumElements();
7924  if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7925  AS == AMDGPUAS::FLAT_ADDRESS) {
7926  if (NumElements > 4)
7927  return SplitVectorStore(Op, DAG);
7928  // v3 stores not supported on SI.
7929  if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7930  return SplitVectorStore(Op, DAG);
7931  return SDValue();
7932  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7933  switch (Subtarget->getMaxPrivateElementSize()) {
7934  case 4:
7935  return scalarizeVectorStore(Store, DAG);
7936  case 8:
7937  if (NumElements > 2)
7938  return SplitVectorStore(Op, DAG);
7939  return SDValue();
7940  case 16:
7941  if (NumElements > 4 || NumElements == 3)
7942  return SplitVectorStore(Op, DAG);
7943  return SDValue();
7944  default:
7945  llvm_unreachable("unsupported private_element_size");
7946  }
7947  } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7948  // Use ds_write_b128 if possible.
7949  if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7950  VT.getStoreSize() == 16 && NumElements != 3)
7951  return SDValue();
7952 
7953  if (NumElements > 2)
7954  return SplitVectorStore(Op, DAG);
7955 
7956  // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7957  // address is negative, then the instruction is incorrectly treated as
7958  // out-of-bounds even if base + offsets is in bounds. Split vectorized
7959  // stores here to avoid emitting ds_write2_b32. We may re-combine the
7960  // store later in the SILoadStoreOptimizer.
7961  if (!Subtarget->hasUsableDSOffset() &&
7962  NumElements == 2 && VT.getStoreSize() == 8 &&
7963  Store->getAlignment() < 8) {
7964  return SplitVectorStore(Op, DAG);
7965  }
7966 
7967  return SDValue();
7968  } else {
7969  llvm_unreachable("unhandled address space");
7970  }
7971 }
7972 
7973 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7974  SDLoc DL(Op);
7975  EVT VT = Op.getValueType();
7976  SDValue Arg = Op.getOperand(0);
7977  SDValue TrigVal;
7978 
7979  // TODO: Should this propagate fast-math-flags?
7980 
7981  SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7982 
7983  if (Subtarget->hasTrigReducedRange()) {
7984  SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7985  TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7986  } else {
7987  TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7988  }
7989 
7990  switch (Op.getOpcode()) {
7991  case ISD::FCOS:
7992  return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7993  case ISD::FSIN:
7994  return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7995  default:
7996  llvm_unreachable("Wrong trig opcode");
7997  }
7998 }
7999 
8000 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8001  AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8002  assert(AtomicNode->isCompareAndSwap());
8003  unsigned AS = AtomicNode->getAddressSpace();
8004 
8005  // No custom lowering required for local address space
8006  if (!isFlatGlobalAddrSpace(AS))
8007  return Op;
8008 
8009  // Non-local address space requires custom lowering for atomic compare
8010  // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8011  SDLoc DL(Op);
8012  SDValue ChainIn = Op.getOperand(0);
8013  SDValue Addr = Op.getOperand(1);
8014  SDValue Old = Op.getOperand(2);
8015  SDValue New = Op.getOperand(3);
8016  EVT VT = Op.getValueType();
8017  MVT SimpleVT = VT.getSimpleVT();
8018  MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8019 
8020  SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8021  SDValue Ops[] = { ChainIn, Addr, NewOld };
8022 
8024  Ops, VT, AtomicNode->getMemOperand());
8025 }
8026 
8027 //===----------------------------------------------------------------------===//
8028 // Custom DAG optimizations
8029 //===----------------------------------------------------------------------===//
8030 
8031 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8032  DAGCombinerInfo &DCI) const {
8033  EVT VT = N->getValueType(0);
8034  EVT ScalarVT = VT.getScalarType();
8035  if (ScalarVT != MVT::f32)
8036  return SDValue();
8037 
8038  SelectionDAG &DAG = DCI.DAG;
8039  SDLoc DL(N);
8040 
8041  SDValue Src = N->getOperand(0);
8042  EVT SrcVT = Src.getValueType();
8043 
8044  // TODO: We could try to match extracting the higher bytes, which would be
8045  // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8046  // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8047  // about in practice.
8048  if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8049  if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8050  SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
8051  DCI.AddToWorklist(Cvt.getNode());
8052  return Cvt;
8053  }
8054  }
8055 
8056  return SDValue();
8057 }
8058 
8059 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8060 
8061 // This is a variant of
8062 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8063 //
8064 // The normal DAG combiner will do this, but only if the add has one use since
8065 // that would increase the number of instructions.
8066 //
8067 // This prevents us from seeing a constant offset that can be folded into a
8068 // memory instruction's addressing mode. If we know the resulting add offset of
8069 // a pointer can be folded into an addressing offset, we can replace the pointer
8070 // operand with the add of new constant offset. This eliminates one of the uses,
8071 // and may allow the remaining use to also be simplified.
8072 //
8073 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8074  unsigned AddrSpace,
8075  EVT MemVT,
8076  DAGCombinerInfo &DCI) const {
8077  SDValue N0 = N->getOperand(0);
8078  SDValue N1 = N->getOperand(1);
8079 
8080  // We only do this to handle cases where it's profitable when there are
8081  // multiple uses of the add, so defer to the standard combine.
8082  if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8083  N0->hasOneUse())
8084  return SDValue();
8085 
8086  const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8087  if (!CN1)
8088  return SDValue();
8089 
8090  const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8091  if (!CAdd)
8092  return SDValue();
8093 
8094  // If the resulting offset is too large, we can't fold it into the addressing
8095  // mode offset.
8096  APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8097  Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8098 
8099  AddrMode AM;
8100  AM.HasBaseReg = true;
8101  AM.BaseOffs = Offset.getSExtValue();
8102  if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8103  return SDValue();
8104 
8105  SelectionDAG &DAG = DCI.DAG;
8106  SDLoc SL(N);
8107  EVT VT = N->getValueType(0);
8108 
8109  SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8110  SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8111 
8112  SDNodeFlags Flags;
8114  (N0.getOpcode() == ISD::OR ||
8115  N0->getFlags().hasNoUnsignedWrap()));
8116 
8117  return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8118 }
8119 
8120 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8121  DAGCombinerInfo &DCI) const {
8122  SDValue Ptr = N->getBasePtr();
8123  SelectionDAG &DAG = DCI.DAG;
8124  SDLoc SL(N);
8125 
8126  // TODO: We could also do this for multiplies.
8127  if (Ptr.getOpcode() == ISD::SHL) {
8128  SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
8129  N->getMemoryVT(), DCI);
8130  if (NewPtr) {
8131  SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8132 
8133  NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8134  return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8135  }
8136  }
8137 
8138  return SDValue();
8139 }
8140 
8141 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8142  return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8143  (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8144  (Opc == ISD::XOR && Val == 0);
8145 }
8146 
8147 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8148 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8149 // integer combine opportunities since most 64-bit operations are decomposed
8150 // this way. TODO: We won't want this for SALU especially if it is an inline
8151 // immediate.
8152 SDValue SITargetLowering::splitBinaryBitConstantOp(
8153  DAGCombinerInfo &DCI,
8154  const SDLoc &SL,
8155  unsigned Opc, SDValue LHS,
8156  const ConstantSDNode *CRHS) const {
8157  uint64_t Val = CRHS->getZExtValue();
8158  uint32_t ValLo = Lo_32(Val);
8159  uint32_t ValHi = Hi_32(Val);
8160  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8161 
8162  if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8163  bitOpWithConstantIsReducible(Opc, ValHi)) ||
8164  (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8165  // If we need to materialize a 64-bit immediate, it will be split up later
8166  // anyway. Avoid creating the harder to understand 64-bit immediate
8167  // materialization.
8168  return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8169  }
8170 
8171  return SDValue();
8172 }
8173 
8174 // Returns true if argument is a boolean value which is not serialized into
8175 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8176 static bool isBoolSGPR(SDValue V) {
8177  if (V.getValueType() != MVT::i1)
8178  return false;
8179  switch (V.getOpcode()) {
8180  default: break;
8181  case ISD::SETCC:
8182  case ISD::AND:
8183  case ISD::OR:
8184  case ISD::XOR:
8185  case AMDGPUISD::FP_CLASS:
8186  return true;
8187  }
8188  return false;
8189 }
8190 
8191 // If a constant has all zeroes or all ones within each byte return it.
8192 // Otherwise return 0.
8194  // 0xff for any zero byte in the mask
8195  uint32_t ZeroByteMask = 0;
8196  if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8197  if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8198  if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8199  if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8200  uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8201  if ((NonZeroByteMask & C) != NonZeroByteMask)
8202  return 0; // Partial bytes selected.
8203  return C;
8204 }
8205 
8206 // Check if a node selects whole bytes from its operand 0 starting at a byte
8207 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8208 // or -1 if not succeeded.
8209 // Note byte select encoding:
8210 // value 0-3 selects corresponding source byte;
8211 // value 0xc selects zero;
8212 // value 0xff selects 0xff.
8214  assert(V.getValueSizeInBits() == 32);
8215 
8216  if (V.getNumOperands() != 2)
8217  return ~0;
8218 
8220  if (!N1)
8221  return ~0;
8222 
8223  uint32_t C = N1->getZExtValue();
8224 
8225  switch (V.getOpcode()) {
8226  default:
8227  break;
8228  case ISD::AND:
8229  if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8230  return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8231  }
8232  break;
8233 
8234  case ISD::OR:
8235  if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8236  return (0x03020100 & ~ConstMask) | ConstMask;
8237  }
8238  break;
8239 
8240  case ISD::SHL:
8241  if (C % 8)
8242  return ~0;
8243 
8244  return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8245 
8246  case ISD::SRL:
8247  if (C % 8)
8248  return ~0;
8249 
8250  return uint32_t(0x0c0c0c0c03020100ull >> C);
8251  }
8252 
8253  return ~0;
8254 }
8255 
8256 SDValue SITargetLowering::performAndCombine(SDNode *N,
8257  DAGCombinerInfo &DCI) const {
8258  if (DCI.isBeforeLegalize())
8259  return SDValue();
8260 
8261  SelectionDAG &DAG = DCI.DAG;
8262  EVT VT = N->getValueType(0);
8263  SDValue LHS = N->getOperand(0);
8264  SDValue RHS = N->getOperand(1);
8265 
8266 
8267  const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8268  if (VT == MVT::i64 && CRHS) {
8269  if (SDValue Split
8270  = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8271  return Split;
8272  }
8273 
8274  if (CRHS && VT == MVT::i32) {
8275  // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8276  // nb = number of trailing zeroes in mask
8277  // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8278  // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8279  uint64_t Mask = CRHS->getZExtValue();
8280  unsigned Bits = countPopulation(Mask);
8281  if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8282  (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8283  if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8284  unsigned Shift = CShift->getZExtValue();
8285  unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8286  unsigned Offset = NB + Shift;
8287  if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8288  SDLoc SL(N);
8289  SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8290  LHS->getOperand(0),
8291  DAG.getConstant(Offset, SL, MVT::i32),
8292  DAG.getConstant(Bits, SL, MVT::i32));
8293  EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8294  SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8295  DAG.getValueType(NarrowVT));
8296  SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8297  DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8298  return Shl;
8299  }
8300  }
8301  }
8302 
8303  // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8304  if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8305  isa<ConstantSDNode>(LHS.getOperand(2))) {
8306  uint32_t Sel = getConstantPermuteMask(Mask);
8307  if (!Sel)
8308  return SDValue();
8309 
8310  // Select 0xc for all zero bytes
8311  Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8312  SDLoc DL(N);
8313  return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8314  LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8315  }
8316  }
8317 
8318  // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8319  // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8320  if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8321  ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8322  ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8323 
8324  SDValue X = LHS.getOperand(0);
8325  SDValue Y = RHS.getOperand(0);
8326  if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8327  return SDValue();
8328 
8329  if (LCC == ISD::SETO) {
8330  if (X != LHS.getOperand(1))
8331  return SDValue();
8332 
8333  if (RCC == ISD::SETUNE) {
8335  if (!C1 || !C1->isInfinity() || C1->isNegative())
8336  return SDValue();
8337 
8344 
8345  static_assert(((~(SIInstrFlags::S_NAN |
8348  SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8349  "mask not equal");
8350 
8351  SDLoc DL(N);
8352  return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8353  X, DAG.getConstant(Mask, DL, MVT::i32));
8354  }
8355  }
8356  }
8357 
8358  if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8359  std::swap(LHS, RHS);
8360 
8361  if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8362  RHS.hasOneUse()) {
8363  ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8364  // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8365  // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8367  if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8368  (RHS.getOperand(0) == LHS.getOperand(0) &&
8369  LHS.getOperand(0) == LHS.getOperand(1))) {
8370  const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8371  unsigned NewMask = LCC == ISD::SETO ?
8372  Mask->getZExtValue() & ~OrdMask :
8373  Mask->getZExtValue() & OrdMask;
8374 
8375  SDLoc DL(N);
8376  return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8377  DAG.getConstant(NewMask, DL, MVT::i32));
8378  }
8379  }
8380 
8381  if (VT == MVT::i32 &&
8382  (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8383  // and x, (sext cc from i1) => select cc, x, 0
8384  if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8385  std::swap(LHS, RHS);
8386  if (isBoolSGPR(RHS.getOperand(0)))
8387  return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8388  LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8389  }
8390 
8391  // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8392  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8393  if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8394  N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8395  uint32_t LHSMask = getPermuteMask(DAG, LHS);
8396  uint32_t RHSMask = getPermuteMask(DAG, RHS);
8397  if (LHSMask != ~0u && RHSMask != ~0u) {
8398  // Canonicalize the expression in an attempt to have fewer unique masks
8399  // and therefore fewer registers used to hold the masks.
8400  if (LHSMask > RHSMask) {
8401  std::swap(LHSMask, RHSMask);
8402  std::swap(LHS, RHS);
8403  }
8404 
8405  // Select 0xc for each lane used from source operand. Zero has 0xc mask
8406  // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8407  uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8408  uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8409 
8410  // Check of we need to combine values from two sources within a byte.
8411  if (!(LHSUsedLanes & RHSUsedLanes) &&
8412  // If we select high and lower word keep it for SDWA.
8413  // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8414  !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8415  // Each byte in each mask is either selector mask 0-3, or has higher
8416  // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8417  // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8418  // mask which is not 0xff wins. By anding both masks we have a correct
8419  // result except that 0x0c shall be corrected to give 0x0c only.
8420  uint32_t Mask = LHSMask & RHSMask;
8421  for (unsigned I = 0; I < 32; I += 8) {
8422  uint32_t ByteSel = 0xff << I;
8423  if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8424  Mask &= (0x0c << I) & 0xffffffff;
8425  }
8426 
8427  // Add 4 to each active LHS lane. It will not affect any existing 0xff
8428  // or 0x0c.
8429  uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8430  SDLoc DL(N);
8431 
8432  return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8433  LHS.getOperand(0), RHS.getOperand(0),
8434  DAG.getConstant(Sel, DL, MVT::i32));
8435  }
8436  }
8437  }
8438 
8439  return SDValue();
8440 }
8441 
8442 SDValue SITargetLowering::performOrCombine(SDNode *N,
8443  DAGCombinerInfo &DCI) const {
8444  SelectionDAG &DAG = DCI.DAG;
8445  SDValue LHS = N->getOperand(0);
8446  SDValue RHS = N->getOperand(1);
8447 
8448  EVT VT = N->getValueType(0);
8449  if (VT == MVT::i1) {
8450  // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8451  if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8452  RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8453  SDValue Src = LHS.getOperand(0);
8454  if (Src != RHS.getOperand(0))
8455  return SDValue();
8456 
8457  const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8458  const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8459  if (!CLHS || !CRHS)
8460  return SDValue();
8461 
8462  // Only 10 bits are used.
8463  static const uint32_t MaxMask = 0x3ff;
8464 
8465  uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8466  SDLoc DL(N);
8467  return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8468  Src, DAG.getConstant(NewMask, DL, MVT::i32));
8469  }
8470 
8471  return SDValue();
8472  }
8473 
8474  // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8475  if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8476  LHS.getOpcode() == AMDGPUISD::PERM &&
8477  isa<ConstantSDNode>(LHS.getOperand(2))) {
8479  if (!Sel)
8480  return SDValue();
8481 
8482  Sel |= LHS.getConstantOperandVal(2);
8483  SDLoc DL(N);
8484  return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8485  LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8486  }
8487 
8488  // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8489  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8490  if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8491  N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8492  uint32_t LHSMask = getPermuteMask(DAG, LHS);
8493  uint32_t RHSMask = getPermuteMask(DAG, RHS);
8494  if (LHSMask != ~0u && RHSMask != ~0u) {
8495  // Canonicalize the expression in an attempt to have fewer unique masks
8496  // and therefore fewer registers used to hold the masks.
8497  if (LHSMask > RHSMask) {
8498  std::swap(LHSMask, RHSMask);
8499  std::swap(LHS, RHS);
8500  }
8501 
8502  // Select 0xc for each lane used from source operand. Zero has 0xc mask
8503  // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8504  uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8505  uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8506 
8507  // Check of we need to combine values from two sources within a byte.
8508  if (!(LHSUsedLanes & RHSUsedLanes) &&
8509  // If we select high and lower word keep it for SDWA.
8510  // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8511  !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8512  // Kill zero bytes selected by other mask. Zero value is 0xc.
8513  LHSMask &= ~RHSUsedLanes;
8514  RHSMask &= ~LHSUsedLanes;
8515  // Add 4 to each active LHS lane
8516  LHSMask |= LHSUsedLanes & 0x04040404;
8517  // Combine masks
8518  uint32_t Sel = LHSMask | RHSMask;
8519  SDLoc DL(N);
8520 
8521  return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8522  LHS.getOperand(0), RHS.getOperand(0),
8523  DAG.getConstant(Sel, DL, MVT::i32));
8524  }
8525  }
8526  }
8527 
8528  if (VT != MVT::i64)
8529  return SDValue();
8530 
8531  // TODO: This could be a generic combine with a predicate for extracting the
8532  // high half of an integer being free.
8533 
8534  // (or i64:x, (zero_extend i32:y)) ->
8535  // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8536  if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8537  RHS.getOpcode() != ISD::ZERO_EXTEND)
8538  std::swap(LHS, RHS);
8539 
8540  if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8541  SDValue ExtSrc = RHS.getOperand(0);
8542  EVT SrcVT = ExtSrc.getValueType();
8543  if (SrcVT == MVT::i32) {
8544  SDLoc SL(N);
8545  SDValue LowLHS, HiBits;
8546  std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8547  SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8548 
8549  DCI.AddToWorklist(LowOr.getNode());
8550  DCI.AddToWorklist(HiBits.getNode());
8551 
8553  LowOr, HiBits);
8554  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8555  }
8556  }
8557 
8558  const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8559  if (CRHS) {
8560  if (SDValue Split
8561  = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8562  return Split;
8563  }
8564 
8565  return SDValue();
8566 }
8567 
8568 SDValue SITargetLowering::performXorCombine(SDNode *N,
8569  DAGCombinerInfo &DCI) const {
8570  EVT VT = N->getValueType(0);
8571  if (VT != MVT::i64)
8572  return SDValue();
8573 
8574  SDValue LHS = N->getOperand(0);
8575  SDValue RHS = N->getOperand(1);
8576 
8577  const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8578  if (CRHS) {
8579  if (SDValue Split
8580  = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8581  return Split;
8582  }
8583 
8584  return SDValue();
8585 }
8586 
8587 // Instructions that will be lowered with a final instruction that zeros the
8588 // high result bits.
8589 // XXX - probably only need to list legal operations.
8590 static bool fp16SrcZerosHighBits(unsigned Opc) {
8591  switch (Opc) {
8592  case ISD::FADD:
8593  case ISD::FSUB:
8594  case ISD::FMUL:
8595  case ISD::FDIV:
8596  case ISD::FREM:
8597  case ISD::FMA:
8598  case ISD::FMAD:
8599  case ISD::FCANONICALIZE:
8600  case ISD::FP_ROUND:
8601  case ISD::UINT_TO_FP:
8602  case ISD::SINT_TO_FP:
8603  case ISD::FABS:
8604  // Fabs is lowered to a bit operation, but it's an and which will clear the
8605  // high bits anyway.
8606  case ISD::FSQRT:
8607  case ISD::FSIN:
8608  case ISD::FCOS:
8609  case ISD::FPOWI:
8610  case ISD::FPOW:
8611  case ISD::FLOG:
8612  case ISD::FLOG2:
8613  case ISD::FLOG10:
8614  case ISD::FEXP:
8615  case ISD::FEXP2:
8616  case ISD::FCEIL:
8617  case ISD::FTRUNC:
8618  case ISD::FRINT:
8619  case ISD::FNEARBYINT:
8620  case ISD::FROUND:
8621  case ISD::FFLOOR:
8622  case ISD::FMINNUM:
8623  case ISD::FMAXNUM:
8624  case AMDGPUISD::FRACT:
8625  case AMDGPUISD::CLAMP:
8626  case AMDGPUISD::COS_HW:
8627  case AMDGPUISD::SIN_HW:
8628  case AMDGPUISD::FMIN3:
8629  case AMDGPUISD::FMAX3:
8630  case AMDGPUISD::FMED3:
8631  case AMDGPUISD::FMAD_FTZ:
8632  case AMDGPUISD::RCP:
8633  case AMDGPUISD::RSQ:
8634  case AMDGPUISD::RCP_IFLAG:
8635  case AMDGPUISD::LDEXP:
8636  return true;
8637  default:
8638  // fcopysign, select and others may be lowered to 32-bit bit operations
8639  // which don't zero the high bits.
8640  return false;
8641  }
8642 }
8643 
8644 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8645  DAGCombinerInfo &DCI) const {
8646  if (!Subtarget->has16BitInsts() ||
8647  DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8648  return SDValue();
8649 
8650  EVT VT = N->getValueType(0);
8651  if (VT != MVT::i32)
8652  return SDValue();
8653 
8654  SDValue Src = N->getOperand(0);
8655  if (Src.getValueType() != MVT::i16)
8656  return SDValue();
8657 
8658  // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8659  // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8660  if (Src.getOpcode() == ISD::BITCAST) {
8661  SDValue BCSrc = Src.getOperand(0);
8662  if (BCSrc.getValueType() == MVT::f16 &&
8664  return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8665  }
8666 
8667  return SDValue();
8668 }
8669 
8670 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8671  DAGCombinerInfo &DCI)
8672  const {
8673  SDValue Src = N->getOperand(0);
8674  auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8675 
8676  if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8677  VTSign->getVT() == MVT::i8) ||
8679  VTSign->getVT() == MVT::i16)) &&
8680  Src.hasOneUse()) {
8681  auto *M = cast<MemSDNode>(Src);
8682  SDValue Ops[] = {
8683  Src.getOperand(0), // Chain
8684  Src.getOperand(1), // rsrc
8685  Src.getOperand(2), // vindex
8686  Src.getOperand(3), // voffset
8687  Src.getOperand(4), // soffset
8688  Src.getOperand(5), // offset
8689  Src.getOperand(6),
8690  Src.getOperand(7)
8691  };
8692  // replace with BUFFER_LOAD_BYTE/SHORT
8693  SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8694  Src.getOperand(0).getValueType());
8695  unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8697  SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8698  ResList,
8699  Ops, M->getMemoryVT(),
8700  M->getMemOperand());
8701  return DCI.DAG.getMergeValues({BufferLoadSignExt,
8702  BufferLoadSignExt.getValue(1)}, SDLoc(N));
8703  }
8704  return SDValue();
8705 }
8706 
8707 SDValue SITargetLowering::performClassCombine(SDNode *N,
8708  DAGCombinerInfo &DCI) const {
8709  SelectionDAG &DAG = DCI.DAG;
8710  SDValue Mask = N->getOperand(1);
8711 
8712  // fp_class x, 0 -> false
8713  if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8714  if (CMask->isNullValue())
8715  return DAG.getConstant(0, SDLoc(N), MVT::i1);
8716  }
8717 
8718  if (N->getOperand(0).isUndef())
8719  return DAG.getUNDEF(MVT::i1);
8720 
8721  return SDValue();
8722 }
8723 
8724 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8725  DAGCombinerInfo &DCI) const {
8726  EVT VT = N->getValueType(0);
8727  SDValue N0 = N->getOperand(0);
8728 
8729  if (N0.isUndef())
8730  return N0;
8731 
8732  if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8733  N0.getOpcode() == ISD::SINT_TO_FP)) {
8734  return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8735  N->getFlags());
8736  }
8737 
8739 }
8740 
8742  unsigned MaxDepth) const {
8743  unsigned Opcode = Op.getOpcode();
8744  if (Opcode == ISD::FCANONICALIZE)
8745  return true;
8746 
8747  if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8748  auto F = CFP->getValueAPF();
8749  if (F.isNaN() && F.isSignaling())
8750  return false;
8751  return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8752  }
8753 
8754  // If source is a result of another standard FP operation it is already in
8755  // canonical form.
8756  if (MaxDepth == 0)
8757  return false;
8758 
8759  switch (Opcode) {
8760  // These will flush denorms if required.
8761  case ISD::FADD:
8762  case ISD::FSUB:
8763  case ISD::FMUL:
8764  case ISD::FCEIL:
8765  case ISD::FFLOOR:
8766  case ISD::FMA:
8767  case ISD::FMAD:
8768  case ISD::FSQRT:
8769  case ISD::FDIV:
8770  case ISD::FREM:
8771  case ISD::FP_ROUND:
8772  case ISD::FP_EXTEND:
8774  case AMDGPUISD::FMAD_FTZ:
8775  case AMDGPUISD::RCP:
8776  case AMDGPUISD::RSQ:
8777  case AMDGPUISD::RSQ_CLAMP:
8778  case AMDGPUISD::RCP_LEGACY:
8779  case AMDGPUISD::RSQ_LEGACY:
8780  case AMDGPUISD::RCP_IFLAG:
8781  case AMDGPUISD::TRIG_PREOP:
8782  case AMDGPUISD::DIV_SCALE:
8783  case AMDGPUISD::DIV_FMAS:
8784  case AMDGPUISD::DIV_FIXUP:
8785  case AMDGPUISD::FRACT:
8786  case AMDGPUISD::LDEXP:
8792  return true;
8793 
8794  // It can/will be lowered or combined as a bit operation.
8795  // Need to check their input recursively to handle.
8796  case ISD::FNEG:
8797  case ISD::FABS:
8798  case ISD::FCOPYSIGN:
8799  return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8800 
8801  case ISD::FSIN:
8802  case ISD::FCOS:
8803  case ISD::FSINCOS:
8804  return Op.getValueType().getScalarType() != MVT::f16;
8805 
8806  case ISD::FMINNUM:
8807  case ISD::FMAXNUM:
8808  case ISD::FMINNUM_IEEE:
8809  case ISD::FMAXNUM_IEEE:
8810  case AMDGPUISD::CLAMP:
8811  case AMDGPUISD::FMED3:
8812  case AMDGPUISD::FMAX3:
8813  case AMDGPUISD::FMIN3: {
8814  // FIXME: Shouldn't treat the generic operations different based these.
8815  // However, we aren't really required to flush the result from
8816  // minnum/maxnum..
8817 
8818  // snans will be quieted, so we only need to worry about denormals.
8819  if (Subtarget->supportsMinMaxDenormModes() ||
8821  return true;
8822 
8823  // Flushing may be required.
8824  // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8825  // targets need to check their input recursively.
8826 
8827  // FIXME: Does this apply with clamp? It's implemented with max.
8828  for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8829  if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8830  return false;
8831  }
8832 
8833  return true;
8834  }
8835  case ISD::SELECT: {
8836  return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8837  isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8838  }
8839  case ISD::BUILD_VECTOR: {
8840  for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8841  SDValue SrcOp = Op.getOperand(i);
8842  if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8843  return false;
8844  }
8845 
8846  return true;
8847  }
8849  case ISD::EXTRACT_SUBVECTOR: {
8850  return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8851  }
8852  case ISD::INSERT_VECTOR_ELT: {
8853  return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8854  isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8855  }
8856  case ISD::UNDEF:
8857  // Could be anything.
8858  return false;
8859 
8860  case ISD::BITCAST: {
8861  // Hack round the mess we make when legalizing extract_vector_elt
8862  SDValue Src = Op.getOperand(0);
8863  if (Src.getValueType() == MVT::i16 &&
8864  Src.getOpcode() == ISD::TRUNCATE) {
8865  SDValue TruncSrc = Src.getOperand(0);
8866  if (TruncSrc.getValueType() == MVT::i32 &&
8867  TruncSrc.getOpcode() == ISD::BITCAST &&
8868  TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8869  return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8870  }
8871  }
8872 
8873  return false;
8874  }
8875  case ISD::INTRINSIC_WO_CHAIN: {
8876  unsigned IntrinsicID
8877  = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8878  // TODO: Handle more intrinsics
8879  switch (IntrinsicID) {
8880  case Intrinsic::amdgcn_cvt_pkrtz:
8881  case Intrinsic::amdgcn_cubeid:
8882  case Intrinsic::amdgcn_frexp_mant:
8883  case Intrinsic::amdgcn_fdot2:
8884  return true;
8885  default:
8886  break;
8887  }
8888 
8890  }
8891  default:
8892  return denormalsEnabledForType(DAG, Op.getValueType()) &&
8893  DAG.isKnownNeverSNaN(Op);
8894  }
8895 
8896  llvm_unreachable("invalid operation");
8897 }
8898 
8899 // Constant fold canonicalize.
8900 SDValue SITargetLowering::getCanonicalConstantFP(
8901  SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8902  // Flush denormals to 0 if not enabled.
8903  if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8904  return DAG.getConstantFP(0.0, SL, VT);
8905 
8906  if (C.isNaN()) {
8907  APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8908  if (C.isSignaling()) {
8909  // Quiet a signaling NaN.
8910  // FIXME: Is this supposed to preserve payload bits?
8911  return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8912  }
8913 
8914  // Make sure it is the canonical NaN bitpattern.
8915  //
8916  // TODO: Can we use -1 as the canonical NaN value since it's an inline
8917  // immediate?
8918  if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8919  return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8920  }
8921 
8922  // Already canonical.
8923  return DAG.getConstantFP(C, SL, VT);
8924 }
8925 
8927  return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8928 }
8929 
8930 SDValue SITargetLowering::performFCanonicalizeCombine(
8931  SDNode *N,
8932  DAGCombinerInfo &DCI) const {
8933  SelectionDAG &DAG = DCI.DAG;
8934  SDValue N0 = N->getOperand(0);
8935  EVT VT = N->getValueType(0);
8936 
8937  // fcanonicalize undef -> qnan
8938  if (N0.isUndef()) {
8940  return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8941  }
8942 
8943  if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8944  EVT VT = N->getValueType(0);
8945  return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8946  }
8947 
8948  // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8949  // (fcanonicalize k)
8950  //
8951  // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8952 
8953  // TODO: This could be better with wider vectors that will be split to v2f16,
8954  // and to consider uses since there aren't that many packed operations.
8955  if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8957  SDLoc SL(N);
8958  SDValue NewElts[2];
8959  SDValue Lo = N0.getOperand(0);
8960  SDValue Hi = N0.getOperand(1);
8961  EVT EltVT = Lo.getValueType();
8962 
8964  for (unsigned I = 0; I != 2; ++I) {
8965  SDValue Op = N0.getOperand(I);
8966  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8967  NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8968  CFP->getValueAPF());
8969  } else if (Op.isUndef()) {
8970  // Handled below based on what the other operand is.
8971  NewElts[I] = Op;
8972  } else {
8973  NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8974  }
8975  }
8976 
8977  // If one half is undef, and one is constant, perfer a splat vector rather
8978  // than the normal qNaN. If it's a register, prefer 0.0 since that's
8979  // cheaper to use and may be free with a packed operation.
8980  if (NewElts[0].isUndef()) {
8981  if (isa<ConstantFPSDNode>(NewElts[1]))
8982  NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8983  NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8984  }
8985 
8986  if (NewElts[1].isUndef()) {
8987  NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8988  NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8989  }
8990 
8991  return DAG.getBuildVector(VT, SL, NewElts);
8992  }
8993  }
8994 
8995  unsigned SrcOpc = N0.getOpcode();
8996 
8997  // If it's free to do so, push canonicalizes further up the source, which may
8998  // find a canonical source.
8999  //
9000  // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9001  // sNaNs.
9002  if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9003  auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9004  if (CRHS && N0.hasOneUse()) {
9005  SDLoc SL(N);
9006  SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9007  N0.getOperand(0));
9008  SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9009  DCI.AddToWorklist(Canon0.getNode());
9010 
9011  return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9012  }
9013  }
9014 
9015  return isCanonicalized(DAG, N0) ? N0 : SDValue();
9016 }
9017 
9018 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9019  switch (Opc) {
9020  case ISD::FMAXNUM:
9021  case ISD::FMAXNUM_IEEE:
9022  return AMDGPUISD::FMAX3;
9023  case ISD::SMAX:
9024  return AMDGPUISD::SMAX3;
9025  case ISD::UMAX:
9026  return AMDGPUISD::UMAX3;
9027  case ISD::FMINNUM:
9028  case ISD::FMINNUM_IEEE:
9029  return AMDGPUISD::FMIN3;
9030  case ISD::SMIN:
9031  return AMDGPUISD::SMIN3;
9032  case ISD::UMIN:
9033  return AMDGPUISD::UMIN3;
9034  default:
9035  llvm_unreachable("Not a min/max opcode");
9036  }
9037 }
9038 
9039 SDValue SITargetLowering::performIntMed3ImmCombine(
9040  SelectionDAG &DAG, const SDLoc &SL,
9041  SDValue Op0, SDValue Op1, bool Signed) const {
9043  if (!K1)
9044  return SDValue();
9045 
9047  if (!K0)
9048  return SDValue();
9049 
9050  if (Signed) {
9051  if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9052  return SDValue();
9053  } else {
9054  if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9055  return SDValue();
9056  }
9057 
9058  EVT VT = K0->getValueType(0);
9059  unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9060  if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9061  return DAG.getNode(Med3Opc, SL, VT,
9062  Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9063  }
9064 
9065  // If there isn't a 16-bit med3 operation, convert to 32-bit.
9066  MVT NVT = MVT::i32;
9067  unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9068 
9069  SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9070  SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9071  SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9072 
9073  SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9074  return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9075 }
9076 
9078  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9079  return C;
9080 
9081  if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9082  if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9083  return C;
9084  }
9085 
9086  return nullptr;
9087 }
9088 
9089 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9090  const SDLoc &SL,
9091  SDValue Op0,
9092  SDValue Op1) const {
9094  if (!K1)
9095  return SDValue();
9096 
9098  if (!K0)
9099  return SDValue();
9100 
9101  // Ordered >= (although NaN inputs should have folded away by now).
9103  if (Cmp == APFloat::cmpGreaterThan)
9104  return SDValue();
9105 
9106  const MachineFunction &MF = DAG.getMachineFunction();
9108 
9109  // TODO: Check IEEE bit enabled?
9110  EVT VT = Op0.getValueType();
9111  if (Info->getMode().DX10Clamp) {
9112  // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9113  // hardware fmed3 behavior converting to a min.
9114  // FIXME: Should this be allowing -0.0?
9115  if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9116  return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9117  }
9118 
9119  // med3 for f16 is only available on gfx9+, and not available for v2f16.
9120  if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9121  // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9122  // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9123  // then give the other result, which is different from med3 with a NaN
9124  // input.
9125  SDValue Var = Op0.getOperand(0);
9126  if (!DAG.isKnownNeverSNaN(Var))
9127  return SDValue();
9128 
9129  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9130 
9131  if ((!K0->hasOneUse() ||
9132  TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9133  (!K1->hasOneUse() ||
9134  TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9135  return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9136  Var, SDValue(K0, 0), SDValue(K1, 0));
9137  }
9138  }
9139 
9140  return SDValue();
9141 }
9142 
9143 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9144  DAGCombinerInfo &DCI) const {
9145  SelectionDAG &DAG = DCI.DAG;
9146 
9147  EVT VT = N->getValueType(0);
9148  unsigned Opc = N->getOpcode();
9149  SDValue Op0 = N->getOperand(0);
9150  SDValue Op1 = N->getOperand(1);
9151 
9152  // Only do this if the inner op has one use since this will just increases
9153  // register pressure for no benefit.
9154 
9155  if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9156  !VT.isVector() &&
9157  (VT == MVT::i32 || VT == MVT::f32 ||
9158  ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9159  // max(max(a, b), c) -> max3(a, b, c)
9160  // min(min(a, b), c) -> min3(a, b, c)
9161  if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9162  SDLoc DL(N);
9163  return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9164  DL,
9165  N->getValueType(0),
9166  Op0.getOperand(0),
9167  Op0.getOperand(1),
9168  Op1);
9169  }
9170 
9171  // Try commuted.
9172  // max(a, max(b, c)) -> max3(a, b, c)
9173  // min(a, min(b, c)) -> min3(a, b, c)
9174  if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9175  SDLoc DL(N);
9176  return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9177  DL,
9178  N->getValueType(0),
9179  Op0,
9180  Op1.getOperand(0),
9181  Op1.getOperand(1));
9182  }
9183  }
9184 
9185  // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9186  if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9187  if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9188  return Med3;
9189  }
9190 
9191  if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9192  if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9193  return Med3;
9194  }
9195 
9196  // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9197  if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9198  (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9199  (Opc == AMDGPUISD::FMIN_LEGACY &&
9200  Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9201  (VT == MVT::f32 || VT == MVT::f64 ||
9202  (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9203  (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9204  Op0.hasOneUse()) {
9205  if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9206  return Res;
9207  }
9208 
9209  return SDValue();
9210 }
9211 
9213  if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9214  if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9215  // FIXME: Should this be allowing -0.0?
9216  return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9217  (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9218  }
9219  }
9220 
9221  return false;
9222 }
9223 
9224 // FIXME: Should only worry about snans for version with chain.
9225 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9226  DAGCombinerInfo &DCI) const {
9227  EVT VT = N->getValueType(0);
9228  // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9229  // NaNs. With a NaN input, the order of the operands may change the result.
9230 
9231  SelectionDAG &DAG = DCI.DAG;
9232  SDLoc SL(N);
9233 
9234  SDValue Src0 = N->getOperand(0);
9235  SDValue Src1 = N->getOperand(1);
9236  SDValue Src2 = N->getOperand(2);
9237 
9238  if (isClampZeroToOne(Src0, Src1)) {
9239  // const_a, const_b, x -> clamp is safe in all cases including signaling
9240  // nans.
9241  // FIXME: Should this be allowing -0.0?
9242  return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9243  }
9244 
9245  const MachineFunction &MF = DAG.getMachineFunction();
9247 
9248  // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9249  // handling no dx10-clamp?
9250  if (Info->getMode().DX10Clamp) {
9251  // If NaNs is clamped to 0, we are free to reorder the inputs.
9252 
9253  if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9254  std::swap(Src0, Src1);
9255 
9256  if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9257  std::swap(Src1, Src2);
9258 
9259  if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9260  std::swap(Src0, Src1);
9261 
9262  if (isClampZeroToOne(Src1, Src2))
9263  return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9264  }
9265 
9266  return SDValue();
9267 }
9268 
9269 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9270  DAGCombinerInfo &DCI) const {
9271  SDValue Src0 = N->getOperand(0);
9272  SDValue Src1 = N->getOperand(1);
9273  if (Src0.isUndef() && Src1.isUndef())
9274  return DCI.DAG.getUNDEF(N->getValueType(0));
9275  return SDValue();
9276 }
9277 
9278 SDValue SITargetLowering::performExtractVectorEltCombine(
9279  SDNode *N, DAGCombinerInfo &DCI) const {
9280  SDValue Vec = N->getOperand(0);
9281  SelectionDAG &DAG = DCI.DAG;
9282 
9283  EVT VecVT = Vec.getValueType();
9284  EVT EltVT = VecVT.getVectorElementType();
9285 
9286  if ((Vec.getOpcode() == ISD::FNEG ||
9287  Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9288  SDLoc SL(N);
9289  EVT EltVT = N->getValueType(0);
9290  SDValue Idx = N->getOperand(1);
9291  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9292  Vec.getOperand(0), Idx);
9293  return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9294  }
9295 
9296  // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9297  // =>
9298  // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9299  // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9300  // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9301  if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9302  SDLoc SL(N);
9303  EVT EltVT = N->getValueType(0);
9304  SDValue Idx = N->getOperand(1);
9305  unsigned Opc = Vec.getOpcode();
9306 
9307  switch(Opc) {
9308  default:
9309  break;
9310  // TODO: Support other binary operations.
9311  case ISD::FADD:
9312  case ISD::FSUB:
9313  case ISD::FMUL:
9314  case ISD::ADD:
9315  case ISD::UMIN:
9316  case ISD::UMAX:
9317  case ISD::SMIN:
9318  case ISD::SMAX:
9319  case ISD::FMAXNUM:
9320  case ISD::FMINNUM:
9321  case ISD::FMAXNUM_IEEE:
9322  case ISD::FMINNUM_IEEE: {
9323  SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9324  Vec.getOperand(0), Idx);
9325  SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9326  Vec.getOperand(1), Idx);
9327 
9328  DCI.AddToWorklist(Elt0.getNode());
9329  DCI.AddToWorklist(Elt1.getNode());
9330  return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9331  }
9332  }
9333  }
9334 
9335  unsigned VecSize = VecVT.getSizeInBits();
9336  unsigned EltSize = EltVT.getSizeInBits();
9337 
9338  // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9339  // This elminates non-constant index and subsequent movrel or scratch access.
9340  // Sub-dword vectors of size 2 dword or less have better implementation.
9341  // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9342  // instructions.
9343  if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9344  !isa<ConstantSDNode>(N->getOperand(1))) {
9345  SDLoc SL(N);
9346  SDValue Idx = N->getOperand(1);
9347  EVT IdxVT = Idx.getValueType();
9348  SDValue V;
9349  for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9350  SDValue IC = DAG.getConstant(I, SL, IdxVT);
9351  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9352  if (I == 0)
9353  V = Elt;
9354  else
9355  V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9356  }
9357  return V;
9358  }
9359 
9360  if (!DCI.isBeforeLegalize())
9361  return SDValue();
9362 
9363  // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9364  // elements. This exposes more load reduction opportunities by replacing
9365  // multiple small extract_vector_elements with a single 32-bit extract.
9366  auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9367  if (isa<MemSDNode>(Vec) &&
9368  EltSize <= 16 &&
9369  EltVT.isByteSized() &&
9370  VecSize > 32 &&
9371  VecSize % 32 == 0 &&
9372  Idx) {
9373  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9374 
9375  unsigned BitIndex = Idx->getZExtValue() * EltSize;
9376  unsigned EltIdx = BitIndex / 32;
9377  unsigned LeftoverBitIdx = BitIndex % 32;
9378  SDLoc SL(N);
9379 
9380  SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9381  DCI.AddToWorklist(Cast.getNode());
9382 
9383  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9384  DAG.getConstant(EltIdx, SL, MVT::i32));
9385  DCI.AddToWorklist(Elt.getNode());
9386  SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9387  DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9388  DCI.AddToWorklist(Srl.getNode());
9389 
9390  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9391  DCI.AddToWorklist(Trunc.getNode());
9392  return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9393  }
9394 
9395  return SDValue();
9396 }
9397 
9398 SDValue
9399 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9400  DAGCombinerInfo &DCI) const {
9401  SDValue Vec = N->getOperand(0);
9402  SDValue Idx = N->getOperand(2);
9403  EVT VecVT = Vec.getValueType();
9404  EVT EltVT = VecVT.getVectorElementType();
9405  unsigned VecSize = VecVT.getSizeInBits();
9406  unsigned EltSize = EltVT.getSizeInBits();
9407 
9408  // INSERT_VECTOR_ELT (<n x e>, var-idx)
9409  // => BUILD_VECTOR n x select (e, const-idx)
9410  // This elminates non-constant index and subsequent movrel or scratch access.
9411  // Sub-dword vectors of size 2 dword or less have better implementation.
9412  // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9413  // instructions.
9414  if (isa<ConstantSDNode>(Idx) ||
9415  VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9416  return SDValue();
9417 
9418  SelectionDAG &DAG = DCI.DAG;
9419  SDLoc SL(N);
9420  SDValue Ins = N->getOperand(1);
9421  EVT IdxVT = Idx.getValueType();
9422 
9424  for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9425  SDValue IC = DAG.getConstant(I, SL, IdxVT);
9426  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9427  SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9428  Ops.push_back(V);
9429  }
9430 
9431  return DAG.getBuildVector(VecVT, SL, Ops);
9432 }
9433 
9434 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9435  const SDNode *N0,
9436  const SDNode *N1) const {
9437  EVT VT = N0->getValueType(0);
9438 
9439  // Only do this if we are not trying to support denormals. v_mad_f32 does not
9440  // support denormals ever.
9441  if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9442  (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9443  getSubtarget()->hasMadF16())) &&
9445  return ISD::FMAD;
9446 
9447  const TargetOptions &Options = DAG.getTarget().Options;
9448  if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9449  (N0->getFlags().hasAllowContract() &&
9450  N1->getFlags().hasAllowContract())) &&
9452  return ISD::FMA;
9453  }
9454 
9455  return 0;
9456 }
9457 
9458 // For a reassociatable opcode perform:
9459 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9460 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9461  SelectionDAG &DAG) const {
9462  EVT VT = N->getValueType(0);
9463  if (VT != MVT::i32 && VT != MVT::i64)
9464  return SDValue();
9465 
9466  unsigned Opc = N->getOpcode();
9467  SDValue Op0 = N->getOperand(0);
9468  SDValue Op1 = N->getOperand(1);
9469 
9470  if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9471  return SDValue();
9472 
9473  if (Op0->isDivergent())
9474  std::swap(Op0, Op1);
9475 
9476  if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9477  return SDValue();
9478 
9479  SDValue Op2 = Op1.getOperand(1);
9480  Op1 = Op1.getOperand(0);
9481  if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9482  return SDValue();
9483 
9484  if (Op1->isDivergent())
9485  std::swap(Op1, Op2);
9486 
9487  // If either operand is constant this will conflict with
9488  // DAGCombiner::ReassociateOps().
9491  return SDValue();
9492 
9493  SDLoc SL(N);
9494  SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9495  return DAG.getNode(Opc, SL, VT, Add1, Op2);
9496 }
9497 
9498 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9499  EVT VT,
9500  SDValue N0, SDValue N1, SDValue N2,
9501  bool Signed) {
9502  unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9503  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9504  SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9505  return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9506 }
9507 
9508 SDValue SITargetLowering::performAddCombine(SDNode *N,
9509  DAGCombinerInfo &DCI) const {
9510  SelectionDAG &DAG = DCI.DAG;
9511  EVT VT = N->getValueType(0);
9512  SDLoc SL(N);
9513  SDValue LHS = N->getOperand(0);
9514  SDValue RHS = N->getOperand(1);
9515 
9516  if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9517  && Subtarget->hasMad64_32() &&
9518  !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9519  VT.getScalarSizeInBits() <= 64) {
9520  if (LHS.getOpcode() != ISD::MUL)
9521  std::swap(LHS, RHS);
9522 
9523  SDValue MulLHS = LHS.getOperand(0);
9524  SDValue MulRHS = LHS.getOperand(1);
9525  SDValue AddRHS = RHS;
9526 
9527  // TODO: Maybe restrict if SGPR inputs.
9528  if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9529  numBitsUnsigned(MulRHS, DAG) <= 32) {
9530  MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9531  MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9532  AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9533  return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9534  }
9535 
9536  if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9537  MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9538  MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9539  AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9540  return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9541  }
9542 
9543  return SDValue();
9544  }
9545 
9546  if (SDValue V = reassociateScalarOps(N, DAG)) {
9547  return V;
9548  }
9549 
9550  if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9551  return SDValue();
9552 
9553  // add x, zext (setcc) => addcarry x, 0, setcc
9554  // add x, sext (setcc) => subcarry x, 0, setcc
9555  unsigned Opc = LHS.getOpcode();
9556  if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9557  Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9558  std::swap(RHS, LHS);
9559 
9560  Opc = RHS.getOpcode();
9561  switch (Opc) {
9562  default: break;
9563  case ISD::ZERO_EXTEND:
9564  case ISD::SIGN_EXTEND:
9565  case ISD::ANY_EXTEND: {
9566  auto Cond = RHS.getOperand(0);
9567  // If this won't be a real VOPC output, we would still need to insert an
9568  // extra instruction anyway.
9569  if (!isBoolSGPR(Cond))
9570  break;
9571  SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9572  SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9573  Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9574  return DAG.getNode(Opc, SL, VTList, Args);
9575  }
9576  case ISD::ADDCARRY: {
9577  // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9578  auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9579  if (!C || C->getZExtValue() != 0) break;
9580  SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9581  return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9582  }
9583  }
9584  return SDValue();
9585 }
9586 
9587 SDValue SITargetLowering::performSubCombine(SDNode *N,
9588  DAGCombinerInfo &DCI) const {
9589  SelectionDAG &DAG = DCI.DAG;
9590  EVT VT = N->getValueType(0);
9591 
9592  if (VT != MVT::i32)
9593  return SDValue();
9594 
9595  SDLoc SL(N);
9596  SDValue LHS = N->getOperand(0);
9597  SDValue RHS = N->getOperand(1);
9598 
9599  // sub x, zext (setcc) => subcarry x, 0, setcc
9600  // sub x, sext (setcc) => addcarry x, 0, setcc
9601  unsigned Opc = RHS.getOpcode();
9602  switch (Opc) {
9603  default: break;
9604  case ISD::ZERO_EXTEND:
9605  case ISD::SIGN_EXTEND:
9606  case ISD::ANY_EXTEND: {
9607  auto Cond = RHS.getOperand(0);
9608  // If this won't be a real VOPC output, we would still need to insert an
9609  // extra instruction anyway.
9610  if (!isBoolSGPR(Cond))
9611  break;
9612  SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9613  SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9614  Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9615  return DAG.getNode(Opc, SL, VTList, Args);
9616  }
9617  }
9618 
9619  if (LHS.getOpcode() == ISD::SUBCARRY) {
9620  // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9621  auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9622  if (!C || !C->isNullValue())
9623  return SDValue();
9624  SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9625  return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9626  }
9627  return SDValue();
9628 }
9629 
9630 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9631  DAGCombinerInfo &DCI) const {
9632 
9633  if (N->getValueType(0) != MVT::i32)
9634  return SDValue();
9635 
9636  auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9637  if (!C || C->getZExtValue() != 0)
9638  return SDValue();
9639 
9640  SelectionDAG &DAG = DCI.DAG;
9641  SDValue LHS = N->getOperand(0);
9642 
9643  // addcarry (add x, y), 0, cc => addcarry x, y, cc
9644  // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9645  unsigned LHSOpc = LHS.getOpcode();
9646  unsigned Opc = N->getOpcode();
9647  if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9648  (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9649  SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9650  return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9651  }
9652  return SDValue();
9653 }
9654 
9655 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9656  DAGCombinerInfo &DCI) const {
9657  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9658  return SDValue();
9659 
9660  SelectionDAG &DAG = DCI.DAG;
9661  EVT VT = N->getValueType(0);
9662 
9663  SDLoc SL(N);
9664  SDValue LHS = N->getOperand(0);
9665  SDValue RHS = N->getOperand(1);
9666 
9667  // These should really be instruction patterns, but writing patterns with
9668  // source modiifiers is a pain.
9669 
9670  // fadd (fadd (a, a), b) -> mad 2.0, a, b
9671  if (LHS.getOpcode() == ISD::FADD) {
9672  SDValue A = LHS.getOperand(0);
9673  if (A == LHS.getOperand(1)) {
9674  unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9675  if (FusedOp != 0) {
9676  const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9677  return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9678  }
9679  }
9680  }
9681 
9682  // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9683  if (RHS.getOpcode() == ISD::FADD) {
9684  SDValue A = RHS.getOperand(0);
9685  if (A == RHS.getOperand(1)) {
9686  unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9687  if (FusedOp != 0) {
9688  const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9689  return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9690  }
9691  }
9692  }
9693 
9694  return SDValue();
9695 }
9696 
9697 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9698  DAGCombinerInfo &DCI) const {
9699  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9700  return SDValue();
9701 
9702  SelectionDAG &DAG = DCI.DAG;
9703  SDLoc SL(N);
9704  EVT VT = N->getValueType(0);
9705  assert(!VT.isVector());
9706 
9707  // Try to get the fneg to fold into the source modifier. This undoes generic
9708  // DAG combines and folds them into the mad.
9709  //
9710  // Only do this if we are not trying to support denormals. v_mad_f32 does
9711  // not support denormals ever.
9712  SDValue LHS = N->getOperand(0);
9713  SDValue RHS = N->getOperand(1);
9714  if (LHS.getOpcode() == ISD::FADD) {
9715  // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9716  SDValue A = LHS.getOperand(0);
9717  if (A == LHS.getOperand(1)) {
9718  unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9719  if (FusedOp != 0){
9720  const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9721  SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9722 
9723  return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9724  }
9725  }
9726  }
9727 
9728  if (RHS.getOpcode() == ISD::FADD) {
9729  // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9730 
9731  SDValue A = RHS.getOperand(0);
9732  if (A == RHS.getOperand(1)) {
9733  unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9734  if (FusedOp != 0){
9735  const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9736  return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9737  }
9738  }
9739  }
9740 
9741  return SDValue();
9742 }
9743 
9744 SDValue SITargetLowering::performFMACombine(SDNode *N,
9745  DAGCombinerInfo &DCI) const {
9746  SelectionDAG &DAG = DCI.DAG;
9747  EVT VT = N->getValueType(0);
9748  SDLoc SL(N);
9749 
9750  if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9751  return SDValue();
9752 
9753  // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9754  // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9755  SDValue Op1 = N->getOperand(0);
9756  SDValue Op2 = N->getOperand(1);
9757  SDValue FMA = N->getOperand(2);
9758 
9759  if (FMA.getOpcode() != ISD::FMA ||
9760  Op1.getOpcode() != ISD::FP_EXTEND ||
9761  Op2.getOpcode() != ISD::FP_EXTEND)
9762  return SDValue();
9763 
9764  // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9765  // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9766  // is sufficient to allow generaing fdot2.
9767  const TargetOptions &Options = DAG.getTarget().Options;
9768  if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9769  (N->getFlags().hasAllowContract() &&
9770  FMA->getFlags().hasAllowContract())) {
9771  Op1 = Op1.getOperand(0);
9772  Op2 = Op2.getOperand(0);
9773  if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9775  return SDValue();
9776 
9777  SDValue Vec1 = Op1.getOperand(0);
9778  SDValue Idx1 = Op1.getOperand(1);
9779  SDValue Vec2 = Op2.getOperand(0);
9780 
9781  SDValue FMAOp1 = FMA.getOperand(0);
9782  SDValue FMAOp2 = FMA.getOperand(1);
9783  SDValue FMAAcc = FMA.getOperand(2);
9784 
9785  if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9786  FMAOp2.getOpcode() != ISD::FP_EXTEND)
9787  return SDValue();
9788 
9789  FMAOp1 = FMAOp1.getOperand(0);
9790  FMAOp2 = FMAOp2.getOperand(0);
9791  if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9792  FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9793  return SDValue();
9794 
9795  SDValue Vec3 = FMAOp1.getOperand(0);
9796  SDValue Vec4 = FMAOp2.getOperand(0);
9797  SDValue Idx2 = FMAOp1.getOperand(1);
9798 
9799  if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9800  // Idx1 and Idx2 cannot be the same.
9801  Idx1 == Idx2)
9802  return SDValue();
9803 
9804  if (Vec1 == Vec2 || Vec3 == Vec4)
9805  return SDValue();
9806 
9807  if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9808  return SDValue();
9809 
9810  if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9811  (Vec1 == Vec4 && Vec2 == Vec3)) {
9812  return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9813  DAG.getTargetConstant(0, SL, MVT::i1));
9814  }
9815  }
9816  return SDValue();
9817 }
9818 
9819 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9820  DAGCombinerInfo &DCI) const {
9821  SelectionDAG &DAG = DCI.DAG;
9822  SDLoc SL(N);
9823 
9824  SDValue LHS = N->getOperand(0);
9825  SDValue RHS = N->getOperand(1);
9826  EVT VT = LHS.getValueType();
9827  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9828 
9829  auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9830  if (!CRHS) {
9831  CRHS = dyn_cast<ConstantSDNode>(LHS);
9832  if (CRHS) {
9833  std::swap(LHS, RHS);
9834  CC = getSetCCSwappedOperands(CC);
9835  }
9836  }
9837 
9838  if (CRHS) {
9839  if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9840  isBoolSGPR(LHS.getOperand(0))) {
9841  // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9842  // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9843  // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
9844  // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
9845  if ((CRHS->isAllOnesValue() &&
9846  (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9847  (CRHS->isNullValue() &&
9848  (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9849  return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9850  DAG.getConstant(-1, SL, MVT::i1));
9851  if ((CRHS->isAllOnesValue() &&
9852  (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9853  (CRHS->isNullValue() &&
9854  (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9855  return LHS.getOperand(0);
9856  }
9857 
9858  uint64_t CRHSVal = CRHS->getZExtValue();
9859  if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9860  LHS.getOpcode() == ISD::SELECT &&
9861  isa<ConstantSDNode>(LHS.getOperand(1)) &&
9862  isa<ConstantSDNode>(LHS.getOperand(2)) &&
9863  LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9864  isBoolSGPR(LHS.getOperand(0))) {
9865  // Given CT != FT:
9866  // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9867  // setcc (select cc, CT, CF), CF, ne => cc
9868  // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9869  // setcc (select cc, CT, CF), CT, eq => cc
9870  uint64_t CT = LHS.getConstantOperandVal(1);
9871  uint64_t CF = LHS.getConstantOperandVal(2);
9872 
9873  if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9874  (CT == CRHSVal && CC == ISD::SETNE))
9875  return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9876  DAG.getConstant(-1, SL, MVT::i1));
9877  if ((CF == CRHSVal && CC == ISD::SETNE) ||
9878  (CT == CRHSVal && CC == ISD::SETEQ))
9879  return LHS.getOperand(0);
9880  }
9881  }
9882 
9883  if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9884  VT != MVT::f16))
9885  return SDValue();
9886 
9887  // Match isinf/isfinite pattern
9888  // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9889  // (fcmp one (fabs x), inf) -> (fp_class x,
9890  // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9891  if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9892  const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9893  if (!CRHS)
9894  return SDValue();
9895 
9896  const APFloat &APF = CRHS->getValueAPF();
9897  if (APF.isInfinity() && !APF.isNegative()) {
9898  const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9900  const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9906  unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9907  return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9908  DAG.getConstant(Mask, SL, MVT::i32));
9909  }
9910  }
9911 
9912  return SDValue();
9913 }
9914 
9915 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9916  DAGCombinerInfo &DCI) const {
9917  SelectionDAG &DAG = DCI.DAG;
9918  SDLoc SL(N);
9919  unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9920 
9921  SDValue Src = N->getOperand(0);
9922  SDValue Srl = N->getOperand(0);
9923  if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9924  Srl = Srl.getOperand(0);
9925 
9926  // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9927  if (Srl.getOpcode() == ISD::SRL) {
9928  // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9929  // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9930  // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9931 
9932  if (const ConstantSDNode *C =
9933  dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9934  Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9935  EVT(MVT::i32));
9936 
9937  unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9938  if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9939  return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9940  MVT::f32, Srl);
9941  }
9942  }
9943  }
9944 
9945  APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9946 
9947  KnownBits Known;
9948  TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9949  !DCI.isBeforeLegalizeOps());
9950  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9951  if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9952  DCI.CommitTargetLoweringOpt(TLO);
9953  }
9954 
9955  return SDValue();
9956 }
9957 
9958 SDValue SITargetLowering::performClampCombine(SDNode *N,
9959  DAGCombinerInfo &DCI) const {
9961  if (!CSrc)
9962  return SDValue();
9963 
9964  const MachineFunction &MF = DCI.DAG.getMachineFunction();
9965  const APFloat &F = CSrc->getValueAPF();
9967  APFloat::cmpResult Cmp0 = F.compare(Zero);
9968  if (Cmp0 == APFloat::cmpLessThan ||
9969  (Cmp0 == APFloat::cmpUnordered &&
9971  return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9972  }
9973 
9974  APFloat One(F.getSemantics(), "1.0");
9975  APFloat::cmpResult Cmp1 = F.compare(One);
9976  if (Cmp1 == APFloat::cmpGreaterThan)
9977  return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9978 
9979  return SDValue(CSrc, 0);
9980 }
9981 
9982 
9984  DAGCombinerInfo &DCI) const {
9985  if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9986  return SDValue();
9987  switch (N->getOpcode()) {
9988  default:
9990  case ISD::ADD:
9991  return performAddCombine(N, DCI);
9992  case ISD::SUB:
9993  return performSubCombine(N, DCI);
9994  case ISD::ADDCARRY:
9995  case ISD::SUBCARRY:
9996  return performAddCarrySubCarryCombine(N, DCI);
9997  case ISD::FADD:
9998  return performFAddCombine(N, DCI);
9999  case ISD::FSUB:
10000  return performFSubCombine(N, DCI);
10001  case ISD::SETCC:
10002  return performSetCCCombine(N, DCI);
10003  case ISD::FMAXNUM:
10004  case ISD::FMINNUM:
10005  case ISD::FMAXNUM_IEEE:
10006  case ISD::FMINNUM_IEEE:
10007  case ISD::SMAX:
10008  case ISD::SMIN:
10009  case ISD::UMAX:
10010  case ISD::UMIN:
10013  return performMinMaxCombine(N, DCI);
10014  case ISD::FMA:
10015  return performFMACombine(N, DCI);
10016  case ISD::LOAD: {
10017  if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10018  return Widended;
10020  }
10021  case ISD::STORE:
10022  case ISD::ATOMIC_LOAD:
10023  case ISD::ATOMIC_STORE:
10024  case ISD::ATOMIC_CMP_SWAP:
10026  case ISD::ATOMIC_SWAP:
10027  case ISD::ATOMIC_LOAD_ADD:
10028  case ISD::ATOMIC_LOAD_SUB:
10029  case ISD::ATOMIC_LOAD_AND:
10030  case ISD::ATOMIC_LOAD_OR:
10031  case ISD::ATOMIC_LOAD_XOR:
10032  case ISD::ATOMIC_LOAD_NAND:
10033  case ISD::ATOMIC_LOAD_MIN:
10034  case ISD::ATOMIC_LOAD_MAX:
10035  case ISD::ATOMIC_LOAD_UMIN:
10036  case ISD::ATOMIC_LOAD_UMAX:
10037  case ISD::ATOMIC_LOAD_FADD:
10038  case AMDGPUISD::ATOMIC_INC:
10039  case AMDGPUISD::ATOMIC_DEC:
10041  case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10042  if (DCI.isBeforeLegalize())
10043  break;
10044  return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10045  case ISD::AND:
10046  return performAndCombine(N, DCI);
10047  case ISD::OR:
10048  return performOrCombine(N, DCI);
10049  case ISD::XOR:
10050  return performXorCombine(N, DCI);
10051  case ISD::ZERO_EXTEND:
10052  return performZeroExtendCombine(N, DCI);
10054  return performSignExtendInRegCombine(N , DCI);
10055  case AMDGPUISD::FP_CLASS:
10056  return performClassCombine(N, DCI);
10057  case ISD::FCANONICALIZE:
10058  return performFCanonicalizeCombine(N, DCI);
10059  case AMDGPUISD::RCP:
10060  return performRcpCombine(N, DCI);
10061  case AMDGPUISD::FRACT:
10062  case AMDGPUISD::RSQ:
10063  case AMDGPUISD::RCP_LEGACY:
10064  case AMDGPUISD::RSQ_LEGACY:
10065  case AMDGPUISD::RCP_IFLAG:
10066  case AMDGPUISD::RSQ_CLAMP:
10067  case AMDGPUISD::LDEXP: {
10068  SDValue Src = N->getOperand(0);
10069  if (Src.isUndef())
10070  return Src;
10071  break;
10072  }
10073  case ISD::SINT_TO_FP:
10074  case ISD::UINT_TO_FP:
10075  return performUCharToFloatCombine(N, DCI);
10080  return performCvtF32UByteNCombine(N, DCI);
10081  case AMDGPUISD::FMED3:
10082  return performFMed3Combine(N, DCI);
10084  return performCvtPkRTZCombine(N, DCI);
10085  case AMDGPUISD::CLAMP:
10086  return performClampCombine(N, DCI);
10087  case ISD::SCALAR_TO_VECTOR: {
10088  SelectionDAG &DAG = DCI.DAG;
10089  EVT VT = N->getValueType(0);
10090 
10091  // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10092  if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10093  SDLoc SL(N);
10094  SDValue Src = N->getOperand(0);
10095  EVT EltVT = Src.getValueType();
10096  if (EltVT == MVT::f16)
10097  Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10098 
10099  SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10100  return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10101  }
10102 
10103  break;
10104  }
10106  return performExtractVectorEltCombine(N, DCI);
10108  return performInsertVectorEltCombine(N, DCI);
10109  }
10111 }
10112 
10113 /// Helper function for adjustWritemask
10114 static unsigned SubIdx2Lane(unsigned Idx) {
10115  switch (Idx) {
10116  default: return 0;
10117  case AMDGPU::sub0: return 0;
10118  case AMDGPU::sub1: return 1;
10119  case AMDGPU::sub2: return 2;
10120  case AMDGPU::sub3: return 3;
10121  case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10122  }
10123 }
10124 
10125 /// Adjust the writemask of MIMG instructions
10126 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10127  SelectionDAG &DAG) const {
10128  unsigned Opcode = Node->getMachineOpcode();
10129 
10130  // Subtract 1 because the vdata output is not a MachineSDNode operand.
10131  int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10132  if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10133  return Node; // not implemented for D16
10134 
10135  SDNode *Users[5] = { nullptr };
10136  unsigned Lane = 0;
10137  unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10138  unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10139  unsigned NewDmask = 0;
10140  unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10141  unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10142  bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10143  Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10144  unsigned TFCLane = 0;
10145  bool HasChain = Node->getNumValues() > 1;
10146 
10147  if (OldDmask == 0) {
10148  // These are folded out, but on the chance it happens don't assert.
10149  return Node;
10150  }
10151 
10152  unsigned OldBitsSet = countPopulation(OldDmask);
10153  // Work out which is the TFE/LWE lane if that is enabled.
10154  if (UsesTFC) {
10155  TFCLane = OldBitsSet;
10156  }
10157 
10158  // Try to figure out the used register components
10159  for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10160  I != E; ++I) {
10161 
10162  // Don't look at users of the chain.
10163  if (I.getUse().getResNo() != 0)
10164  continue;
10165 
10166  // Abort if we can't understand the usage
10167  if (!I->isMachineOpcode() ||
10168  I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10169  return Node;
10170 
10171  // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10172  // Note that subregs are packed, i.e. Lane==0 is the first bit set
10173  // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10174  // set, etc.
10175  Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10176 
10177  // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10178  if (UsesTFC && Lane == TFCLane) {
10179  Users[Lane] = *I;
10180  } else {
10181  // Set which texture component corresponds to the lane.
10182  unsigned Comp;
10183  for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10184  Comp = countTrailingZeros(Dmask);
10185  Dmask &= ~(1 << Comp);
10186  }
10187 
10188  // Abort if we have more than one user per component.
10189  if (Users[Lane])
10190  return Node;
10191 
10192  Users[Lane] = *I;
10193  NewDmask |= 1 << Comp;
10194  }
10195  }
10196 
10197  // Don't allow 0 dmask, as hardware assumes one channel enabled.
10198  bool NoChannels = !NewDmask;
10199  if (NoChannels) {
10200  if (!UsesTFC) {
10201  // No uses of the result and not using TFC. Then do nothing.
10202  return Node;
10203  }
10204  // If the original dmask has one channel - then nothing to do
10205  if (OldBitsSet == 1)
10206  return Node;
10207  // Use an arbitrary dmask - required for the instruction to work
10208  NewDmask = 1;
10209  }
10210  // Abort if there's no change
10211  if (NewDmask == OldDmask)
10212  return Node;
10213 
10214  unsigned BitsSet = countPopulation(NewDmask);
10215 
10216  // Check for TFE or LWE - increase the number of channels by one to account
10217  // for the extra return value
10218  // This will need adjustment for D16 if this is also included in
10219  // adjustWriteMask (this function) but at present D16 are excluded.
10220  unsigned NewChannels = BitsSet + UsesTFC;
10221 
10222  int NewOpcode =
10223  AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10224  assert(NewOpcode != -1 &&
10225  NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10226  "failed to find equivalent MIMG op");
10227 
10228  // Adjust the writemask in the node
10230  Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10231  Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10232  Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10233 
10234  MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10235 
10236  MVT ResultVT = NewChannels == 1 ?
10237  SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10238  NewChannels == 5 ? 8 : NewChannels);
10239  SDVTList NewVTList = HasChain ?
10240  DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10241 
10242 
10243  MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10244  NewVTList, Ops);
10245 
10246  if (HasChain) {
10247  // Update chain.
10248  DAG.setNodeMemRefs(NewNode, Node->memoperands());
10249  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10250  }
10251 
10252  if (NewChannels == 1) {
10253  assert(Node->hasNUsesOfValue(1, 0));
10254  SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10255  SDLoc(Node), Users[Lane]->getValueType(0),
10256  SDValue(NewNode, 0));
10257  DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10258  return nullptr;
10259  }
10260 
10261  // Update the users of the node with the new indices
10262  for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10263  SDNode *User = Users[i];
10264  if (!User) {
10265  // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10266  // Users[0] is still nullptr because channel 0 doesn't really have a use.
10267  if (i || !NoChannels)
10268  continue;
10269  } else {
10270  SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10271  DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10272  }
10273 
10274  switch (Idx) {
10275  default: break;
10276  case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10277  case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10278  case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10279  case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10280  }
10281  }
10282 
10283  DAG.RemoveDeadNode(Node);
10284  return nullptr;
10285 }
10286 
10287 static bool isFrameIndexOp(SDValue Op) {
10288  if (Op.getOpcode() == ISD::AssertZext)
10289  Op = Op.getOperand(0);
10290 
10291  return isa<FrameIndexSDNode>(Op);
10292 }
10293 
10294 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10295 /// with frame index operands.
10296 /// LLVM assumes that inputs are to these instructions are registers.
10298  SelectionDAG &DAG) const {
10299  if (Node->getOpcode() == ISD::CopyToReg) {
10300  RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10301  SDValue SrcVal = Node->getOperand(2);
10302 
10303  // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10304  // to try understanding copies to physical registers.
10305  if (SrcVal.getValueType() == MVT::i1 &&
10306  Register::isPhysicalRegister(DestReg->getReg())) {
10307  SDLoc SL(Node);
10309  SDValue VReg = DAG.getRegister(
10310  MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10311 
10312  SDNode *Glued = Node->getGluedNode();
10313  SDValue ToVReg
10314  = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10315  SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10316  SDValue ToResultReg
10317  = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10318  VReg, ToVReg.getValue(1));
10319  DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10320  DAG.RemoveDeadNode(Node);
10321  return ToResultReg.getNode();
10322  }
10323  }
10324 
10326  for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10327  if (!isFrameIndexOp(Node->getOperand(i))) {
10328  Ops.push_back(Node->getOperand(i));
10329  continue;
10330  }
10331 
10332  SDLoc DL(Node);
10333  Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10334  Node->getOperand(i).getValueType(),
10335  Node->getOperand(i)), 0));
10336  }
10337 
10338  return DAG.UpdateNodeOperands(Node, Ops);
10339 }
10340 
10341 /// Fold the instructions after selecting them.
10342 /// Returns null if users were already updated.
10344  SelectionDAG &DAG) const {
10345  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10346  unsigned Opcode = Node->getMachineOpcode();
10347 
10348  if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10349  !TII->isGather4(Opcode)) {
10350  return adjustWritemask(Node, DAG);
10351  }
10352 
10353  if (Opcode == AMDGPU::INSERT_SUBREG ||
10354  Opcode == AMDGPU::REG_SEQUENCE) {
10355  legalizeTargetIndependentNode(Node, DAG);
10356  return Node;
10357  }
10358 
10359  switch (Opcode) {
10360  case AMDGPU::V_DIV_SCALE_F32:
10361  case AMDGPU::V_DIV_SCALE_F64: {
10362  // Satisfy the operand register constraint when one of the inputs is
10363  // undefined. Ordinarily each undef value will have its own implicit_def of
10364  // a vreg, so force these to use a single register.
10365  SDValue Src0 = Node->getOperand(0);
10366  SDValue Src1 = Node->getOperand(1);
10367  SDValue Src2 = Node->getOperand(2);
10368 
10369  if ((Src0.isMachineOpcode() &&
10370  Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10371  (Src0 == Src1 || Src0 == Src2))
10372  break;
10373 
10374  MVT VT = Src0.getValueType().getSimpleVT();
10375  const TargetRegisterClass *RC =
10376  getRegClassFor(VT, Src0.getNode()->isDivergent());
10377 
10379  SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10380 
10381  SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10382  UndefReg, Src0, SDValue());
10383 
10384  // src0 must be the same register as src1 or src2, even if the value is
10385  // undefined, so make sure we don't violate this constraint.
10386  if (Src0.isMachineOpcode() &&
10387  Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10388  if (Src1.isMachineOpcode() &&
10389  Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10390  Src0 = Src1;
10391  else if (Src2.isMachineOpcode() &&
10392  Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10393  Src0 = Src2;
10394  else {
10395  assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10396  Src0 = UndefReg;
10397  Src1 = UndefReg;
10398  }
10399  } else
10400  break;
10401 
10402  SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10403  for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10404  Ops.push_back(Node->getOperand(I));
10405 
10406  Ops.push_back(ImpDef.getValue(1));
10407  return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10408  }
10409  case AMDGPU::V_PERMLANE16_B32:
10410  case AMDGPU::V_PERMLANEX16_B32: {
10411  ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
10412  ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
10413  if (!FI->getZExtValue() && !BC->getZExtValue())
10414  break;
10415  SDValue VDstIn = Node->getOperand(6);
10416  if (VDstIn.isMachineOpcode()
10417  && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
10418  break;
10419  MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
10420  SDLoc(Node), MVT::i32);
10421  SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
10422  SDValue(BC, 0), Node->getOperand(3),
10423  Node->getOperand(4), Node->getOperand(5),
10424  SDValue(ImpDef, 0), Node->getOperand(7) };
10425  return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10426  }
10427  default:
10428  break;
10429  }
10430 
10431  return Node;
10432 }
10433 
10434 /// Assign the register class depending on the number of
10435 /// bits set in the writemask
10437  SDNode *Node) const {
10438  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10439 
10441 
10442  if (TII->isVOP3(MI.getOpcode())) {
10443  // Make sure constant bus requirements are respected.
10444  TII->legalizeOperandsVOP3(MRI, MI);
10445 
10446  // Prefer VGPRs over AGPRs in mAI instructions where possible.
10447  // This saves a chain-copy of registers and better ballance register
10448  // use between vgpr and agpr as agpr tuples tend to be big.
10449  if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10450  unsigned Opc = MI.getOpcode();
10451  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10452  for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10453  AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10454  if (I == -1)
10455  break;
10456  MachineOperand &Op = MI.getOperand(I);
10457  if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10458  OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10460  !TRI->isAGPR(MRI, Op.getReg()))
10461  continue;
10462  auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10463  if (!Src || !Src->isCopy() ||
10464  !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10465  continue;
10466  auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10467  auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10468  // All uses of agpr64 and agpr32 can also accept vgpr except for
10469  // v_accvgpr_read, but we do not produce agpr reads during selection,
10470  // so no use checks are needed.
10471  MRI.setRegClass(Op.getReg(), NewRC);
10472  }
10473  }
10474 
10475  return;
10476  }
10477 
10478  // Replace unused atomics with the no return version.
10479  int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10480  if (NoRetAtomicOp != -1) {
10481  if (!Node->hasAnyUseOfValue(0)) {
10482  MI.setDesc(TII->get(NoRetAtomicOp));
10483  MI.RemoveOperand(0);
10484  return;
10485  }
10486 
10487  // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10488  // instruction, because the return type of these instructions is a vec2 of
10489  // the memory type, so it can be tied to the input operand.
10490  // This means these instructions always have a use, so we need to add a
10491  // special case to check if the atomic has only one extract_subreg use,
10492  // which itself has no uses.
10493  if ((Node->hasNUsesOfValue(1, 0) &&
10494  Node->use_begin()->isMachineOpcode() &&
10495  Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10496  !Node->use_begin()->hasAnyUseOfValue(0))) {
10497  Register Def = MI.getOperand(0).getReg();
10498 
10499  // Change this into a noret atomic.
10500  MI.setDesc(TII->get(NoRetAtomicOp));
10501  MI.RemoveOperand(0);
10502 
10503  // If we only remove the def operand from the atomic instruction, the
10504  // extract_subreg will be left with a use of a vreg without a def.
10505  // So we need to insert an implicit_def to avoid machine verifier
10506  // errors.
10507  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10508  TII->get(AMDGPU::IMPLICIT_DEF), Def);
10509  }
10510  return;
10511  }
10512 }
10513 
10514 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10515  uint64_t Val) {
10516  SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10517  return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10518 }
10519 
10521  const SDLoc &DL,
10522  SDValue Ptr) const {
10523  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10524 
10525  // Build the half of the subregister with the constants before building the
10526  // full 128-bit register. If we are building multiple resource descriptors,
10527  // this will allow CSEing of the 2-component register.
10528  const SDValue Ops0[] = {
10529  DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10530  buildSMovImm32(DAG, DL, 0),
10531  DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10532  buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10533  DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10534  };
10535 
10536  SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10537  MVT::v2i32, Ops0), 0);
10538 
10539  // Combine the constants and the pointer.
10540  const SDValue Ops1[] = {
10541  DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10542  Ptr,
10543  DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10544  SubRegHi,
10545  DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10546  };
10547 
10548  return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10549 }
10550 
10551 /// Return a resource descriptor with the 'Add TID' bit enabled
10552 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10553 /// of the resource descriptor) to create an offset, which is added to
10554 /// the resource pointer.
10556  SDValue Ptr, uint32_t RsrcDword1,
10557  uint64_t RsrcDword2And3) const {
10558  SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10559  SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10560  if (RsrcDword1) {
10561  PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10562  DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10563  0);
10564  }
10565 
10566  SDValue DataLo = buildSMovImm32(DAG, DL,
10567  RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10568  SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10569 
10570  const SDValue Ops[] = {
10571  DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10572  PtrLo,
10573  DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10574  PtrHi,
10575  DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10576  DataLo,
10577  DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10578  DataHi,
10579  DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10580  };
10581 
10582  return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10583 }
10584 
10585 //===----------------------------------------------------------------------===//
10586 // SI Inline Assembly Support
10587 //===----------------------------------------------------------------------===//
10588 
10589 std::pair<unsigned, const TargetRegisterClass *>
10591  StringRef Constraint,
10592  MVT VT) const {
10593  const TargetRegisterClass *RC = nullptr;
10594  if (Constraint.size() == 1) {
10595  switch (Constraint[0]) {
10596  default:
10597  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10598  case 's':
10599  case 'r':
10600  switch (VT.getSizeInBits()) {
10601  default:
10602  return std::make_pair(0U, nullptr);
10603  case 32:
10604  case 16:
10605  RC = &AMDGPU::SReg_32RegClass;
10606  break;
10607  case 64:
10608  RC = &AMDGPU::SGPR_64RegClass;
10609  break;
10610  case 96:
10611  RC = &AMDGPU::SReg_96RegClass;
10612  break;
10613  case 128:
10614  RC = &AMDGPU::SGPR_128RegClass;
10615  break;
10616  case 160:
10617  RC = &AMDGPU::SReg_160RegClass;
10618  break;
10619  case 256:
10620  RC = &AMDGPU::SReg_256RegClass;
10621  break;
10622  case 512:
10623  RC = &AMDGPU::SReg_512RegClass;
10624  break;
10625  }
10626  break;
10627  case 'v':
10628  switch (VT.getSizeInBits()) {
10629  default:
10630  return std::make_pair(0U, nullptr);
10631  case 32:
10632  case 16:
10633  RC = &AMDGPU::VGPR_32RegClass;
10634  break;
10635  case 64:
10636  RC = &AMDGPU::VReg_64RegClass;
10637  break;
10638  case 96:
10639  RC = &AMDGPU::VReg_96RegClass;
10640  break;
10641  case 128:
10642  RC = &AMDGPU::VReg_128RegClass;
10643  break;
10644  case 160:
10645  RC = &AMDGPU::VReg_160RegClass;
10646  break;
10647  case 256:
10648  RC = &AMDGPU::VReg_256RegClass;
10649  break;
10650  case 512:
10651  RC = &AMDGPU::VReg_512RegClass;
10652  break;
10653  }
10654  break;
10655  case 'a':
10656  if (!Subtarget->hasMAIInsts())
10657  break;
10658  switch (VT.getSizeInBits()) {
10659  default:
10660  return std::make_pair(0U, nullptr);
10661  case 32:
10662  case 16:
10663  RC = &AMDGPU::AGPR_32RegClass;
10664  break;
10665  case 64:
10666  RC = &AMDGPU::AReg_64RegClass;
10667  break;
10668  case 128:
10669  RC = &AMDGPU::AReg_128RegClass;
10670  break;
10671  case 512:
10672  RC = &AMDGPU::AReg_512RegClass;
10673  break;
10674  case 1024:
10675  RC = &AMDGPU::AReg_1024RegClass;
10676  // v32 types are not legal but we support them here.
10677  return std::make_pair(0U, RC);
10678  }
10679  break;
10680  }
10681  // We actually support i128, i16 and f16 as inline parameters
10682  // even if they are not reported as legal
10683  if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10684  VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10685  return std::make_pair(0U, RC);
10686  }
10687 
10688  if (Constraint.size() > 1) {
10689  if (Constraint[1] == 'v') {
10690  RC = &AMDGPU::VGPR_32RegClass;
10691  } else if (Constraint[1] == 's') {
10692  RC = &AMDGPU::SGPR_32RegClass;
10693  } else if (Constraint[1] == 'a') {
10694  RC = &AMDGPU::AGPR_32RegClass;
10695  }
10696 
10697  if (RC) {
10698  uint32_t Idx;
10699  bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10700  if (!Failed && Idx < RC->getNumRegs())
10701  return std::make_pair(RC->getRegister(Idx), RC);
10702  }
10703  }
10704  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10705 }
10706 
10709  if (Constraint.size() == 1) {
10710  switch (Constraint[0]) {
10711  default: break;
10712  case 's':
10713  case 'v':
10714  case 'a':
10715  return C_RegisterClass;
10716  }
10717  }
10718  return TargetLowering::getConstraintType(Constraint);
10719 }
10720 
10721 // Figure out which registers should be reserved for stack access. Only after
10722 // the function is legalized do we know all of the non-spill stack objects or if
10723 // calls are present.
10727  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10728  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10729 
10730  if (Info->isEntryFunction()) {
10731  // Callable functions have fixed registers used for stack access.
10732  reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10733  }
10734 
10735  assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10736  Info->getStackPtrOffsetReg()));
10737  if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10738  MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10739 
10740  // We need to worry about replacing the default register with itself in case
10741  // of MIR testcases missing the MFI.
10742  if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10743  MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10744 
10745  if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10746  MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10747 
10748  if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10749  MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10750  Info->getScratchWaveOffsetReg());
10751  }
10752 
10753  Info->limitOccupancy(MF);
10754 
10755  if (ST.isWave32() && !MF.empty()) {
10756  // Add VCC_HI def because many instructions marked as imp-use VCC where
10757  // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10758  // having a use of undef.
10759 
10760  const SIInstrInfo *TII = ST.getInstrInfo();
10761  DebugLoc DL;
10762 
10763  MachineBasicBlock &MBB = MF.front();
10765  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10766 
10767  for (auto &MBB : MF) {
10768  for (auto &MI : MBB) {
10769  TII->fixImplicitOperands(MI);
10770  }
10771  }
10772  }
10773 
10775 }
10776 
10778  KnownBits &Known,
10779  const APInt &DemandedElts,
10780  const SelectionDAG &DAG,
10781  unsigned Depth) const {
10782  TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10783  DAG, Depth);
10784 
10785  // Set the high bits to zero based on the maximum allowed scratch size per
10786  // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10787  // calculation won't overflow, so assume the sign bit is never set.
10788  Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10789 }
10790 
10792  const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10793  const Align CacheLineAlign = Align(64);
10794 
10795  // Pre-GFX10 target did not benefit from loop alignment
10796  if (!ML || DisableLoopAlignment ||
10797  (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10798  getSubtarget()->hasInstFwdPrefetchBug())
10799  return PrefAlign;
10800 
10801  // On GFX10 I$ is 4 x 64 bytes cache lines.
10802  // By default prefetcher keeps one cache line behind and reads two ahead.
10803  // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10804  // behind and one ahead.
10805  // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10806  // If loop fits 64 bytes it always spans no more than two cache lines and
10807  // does not need an alignment.
10808  // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10809  // Else if loop is less or equal 192 bytes we need two lines behind.
10810 
10811  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10812  const MachineBasicBlock *Header = ML->getHeader();
10813  if (Header->getAlignment() != PrefAlign)
10814  return Header->getAlignment(); // Already processed.
10815 
10816  unsigned LoopSize = 0;
10817  for (const MachineBasicBlock *MBB : ML->blocks()) {
10818  // If inner loop block is aligned assume in average half of the alignment
10819  // size to be added as nops.
10820  if (MBB != Header)
10821  LoopSize += MBB->getAlignment().value() / 2;
10822 
10823  for (const MachineInstr &MI : *MBB) {
10824  LoopSize += TII->getInstSizeInBytes(MI);
10825  if (LoopSize > 192)
10826  return PrefAlign;
10827  }
10828  }
10829 
10830  if (LoopSize <= 64)
10831  return PrefAlign;
10832 
10833  if (LoopSize <= 128)
10834  return CacheLineAlign;
10835 
10836  // If any of parent loops is surrounded by prefetch instructions do not
10837  // insert new for inner loop, which would reset parent's settings.
10838  for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10839  if (MachineBasicBlock *Exit = P->getExitBlock()) {
10840  auto I = Exit->getFirstNonDebugInstr();
10841  if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10842  return CacheLineAlign;
10843  }
10844  }
10845 
10846  MachineBasicBlock *Pre = ML->getLoopPreheader();
10847  MachineBasicBlock *Exit = ML->getExitBlock();
10848 
10849  if (Pre && Exit) {
10850  BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10851  TII->get(AMDGPU::S_INST_PREFETCH))
10852  .addImm(1); // prefetch 2 lines behind PC
10853 
10854  BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10855  TII->get(AMDGPU::S_INST_PREFETCH))
10856  .addImm(2); // prefetch 1 line behind PC
10857  }
10858 
10859  return CacheLineAlign;
10860 }
10861 
10863 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10865  do {
10866  // Follow the chain until we find an INLINEASM node.
10867  N = N->getOperand(0).getNode();
10868  if (N->getOpcode() == ISD::INLINEASM ||
10869  N->getOpcode() == ISD::INLINEASM_BR)
10870  return true;
10871  } while (N->getOpcode() == ISD::CopyFromReg);
10872  return false;
10873 }
10874 
10877 {
10878  switch (N->getOpcode()) {
10879  case ISD::CopyFromReg:
10880  {
10881  const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10882  const MachineFunction * MF = FLI->MF;
10883  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10884  const MachineRegisterInfo &MRI = MF->getRegInfo();
10886  unsigned Reg = R->getReg();
10888  return !TRI.isSGPRReg(MRI, Reg);
10889 
10890  if (MRI.isLiveIn(Reg)) {
10891  // workitem.id.x workitem.id.y workitem.id.z
10892  // Any VGPR formal argument is also considered divergent
10893  if (!TRI.isSGPRReg(MRI, Reg))
10894  return true;
10895  // Formal arguments of non-entry functions
10896  // are conservatively considered divergent
10897  else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10898  return true;
10899  return false;
10900  }
10901  const Value *V = FLI->getValueFromVirtualReg(Reg);
10902  if (V)
10903  return KDA->isDivergent(V);
10904  assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10905  return !TRI.isSGPRReg(MRI, Reg);
10906  }
10907  break;
10908  case ISD::LOAD: {
10909  const LoadSDNode *L = cast<LoadSDNode>(N);
10910  unsigned AS = L->getAddressSpace();
10911  // A flat load may access private memory.
10912  return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10913  } break;
10914  case ISD::CALLSEQ_END:
10915  return true;
10916  break;
10918  {
10919 
10920  }
10922  cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10925  cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10926  }
10927  return false;
10928 }
10929 
10931  EVT VT) const {
10932  switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10933  case MVT::f32:
10934  return hasFP32Denormals(DAG.getMachineFunction());
10935  case MVT::f64:
10936  case MVT::f16:
10938  default:
10939  return false;
10940  }
10941 }
10942 
10944  const SelectionDAG &DAG,
10945  bool SNaN,
10946  unsigned Depth) const {
10947  if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10948  const MachineFunction &MF = DAG.getMachineFunction();
10950 
10951  if (Info->getMode().DX10Clamp)
10952  return true; // Clamped to 0.
10953  return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10954  }
10955 
10957  SNaN, Depth);
10958 }
10959 
10962  switch (RMW->getOperation()) {
10963  case AtomicRMWInst::FAdd: {
10964  Type *Ty = RMW->getType();
10965 
10966  // We don't have a way to support 16-bit atomics now, so just leave them
10967  // as-is.
10968  if (Ty->isHalfTy())
10970 
10971  if (!Ty->isFloatTy())
10973 
10974  // TODO: Do have these for flat. Older targets also had them for buffers.
10975  unsigned AS = RMW->getPointerAddressSpace();
10976 
10977  if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10978  return RMW->use_empty() ? AtomicExpansionKind::None :
10980  }
10981 
10982  return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10984  }
10985  default:
10986  break;
10987  }
10988 
10990 }
10991 
10992 const TargetRegisterClass *
10993 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10995  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10996  if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10997  return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10998  : &AMDGPU::SReg_32RegClass;
10999  if (!TRI->isSGPRClass(RC) && !isDivergent)
11000  return TRI->getEquivalentSGPRClass(RC);
11001  else if (TRI->isSGPRClass(RC) && isDivergent)
11002  return TRI->getEquivalentVGPRClass(RC);
11003 
11004  return RC;
11005 }
11006 
11007 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) {
11008  if (!isa<Instruction>(V))
11009  return false;
11010  if (!Visited.insert(V).second)
11011  return false;
11012  bool Result = false;
11013  for (auto U : V->users()) {
11014  if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11015  if (V == U->getOperand(1)) {
11016  switch (Intrinsic->getIntrinsicID()) {
11017  default:
11018  Result = false;
11019  break;
11020  case Intrinsic::amdgcn_if_break:
11021  case Intrinsic::amdgcn_if:
11022  case Intrinsic::amdgcn_else:
11023  Result = true;
11024  break;
11025  }
11026  }
11027  if (V == U->getOperand(0)) {
11028  switch (Intrinsic->getIntrinsicID()) {
11029  default:
11030  Result = false;
11031  break;
11032  case Intrinsic::amdgcn_end_cf:
11033  case Intrinsic::amdgcn_loop:
11034  Result = true;
11035  break;
11036  }
11037  }
11038  } else {
11039  Result = hasCFUser(U, Visited);
11040  }
11041  if (Result)
11042  break;
11043  }
11044  return Result;
11045 }
11046 
11048  const Value *V) const {
11049  if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
11050  switch (Intrinsic->getIntrinsicID()) {
11051  default:
11052  return false;
11053  case Intrinsic::amdgcn_if_break:
11054  return true;
11055  }
11056  }
11057  if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
11058  if (const IntrinsicInst *Intrinsic =
11059  dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
11060  switch (Intrinsic->getIntrinsicID()) {
11061  default:
11062  return false;
11063  case Intrinsic::amdgcn_if:
11064  case Intrinsic::amdgcn_else: {
11065  ArrayRef<unsigned> Indices = ExtValue->getIndices();
11066  if (Indices.size() == 1 && Indices[0] == 1) {
11067  return true;
11068  }
11069  }
11070  }
11071  }
11072  }
11073  if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11074  if (isa<InlineAsm>(CI->getCalledValue())) {
11075  const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11076  ImmutableCallSite CS(CI);
11078  MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
11079  for (auto &TC : TargetConstraints) {
11080  if (TC.Type == InlineAsm::isOutput) {
11082  unsigned AssignedReg;
11083  const TargetRegisterClass *RC;
11084  std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11085  SIRI, TC.ConstraintCode, TC.ConstraintVT);
11086  if (RC) {
11088  if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11089  return true;
11090  else if (SIRI->isSGPRClass(RC))
11091  return true;
11092  }
11093  }
11094  }
11095  }
11096  }
11098  return hasCFUser(V, Visited);
11099 }
bool hasBCNT(unsigned Size) const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
unsigned addImplicitBufferPtr(const SIRegisterInfo &TRI)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
void setWorkItemIDX(ArgDescriptor Arg)
uint64_t CallInst * C
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:625
bool isInvariant() const
constexpr bool isUInt< 32 >(uint64_t x)
Definition: MathExtras.h:385
X = FP_ROUND(Y, TRUNC) - Rounding &#39;Y&#39; from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:599
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set, or Regs.size() if they are all allocated.
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array...
static MVT getIntegerVT(unsigned BitWidth)
void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
bool hasLDSMisalignedBug() const
const MachineInstrBuilder & add(const MachineOperand &MO) const
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:598
bool hasUsableDSOffset() const
True if the offset field of DS instructions works as expected.
BUILTIN_OP_END - This must be the last enum value in this list.
Definition: ISDOpcodes.h:943
static void r3(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition: SHA1.cpp:61
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:641
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition: Analysis.cpp:238
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:652
BitVector & set()
Definition: BitVector.h:397
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isLegalGlobalAddressingMode(const AddrMode &AM) const
Interface definition for SIRegisterInfo.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
void setFuncArgInfo(const Function &F, const AMDGPUFunctionArgInfo &ArgInfo)
static void r2(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition: SHA1.cpp:55
Register getRegister() const
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const SDValue & getOffset() const
bool shouldEmitFixup(const GlobalValue *GV) const
bool isUndef() const
static LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
unsigned reservedPrivateSegmentBufferReg(const MachineFunction &MF) const
Return the end register initially reserved for the scratch buffer in case spilling is needed...
uint64_t encodeHwreg(uint64_t Id, uint64_t Offset, uint64_t Width)
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
const GlobalValue * getGlobal() const
This instruction extracts a struct member or array element value from an aggregate value...
bool hasApertureRegs() const
bool isDivergent(const Value *V) const
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVMContext & Context
Diagnostic information for unsupported feature in backend.
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition: ValueTypes.h:374
SDValue CreateLiveInRegister(SelectionDAG &DAG, const TargetRegisterClass *RC, unsigned Reg, EVT VT, const SDLoc &SL, bool RawReg=false) const
Helper function that adds Reg to the LiveIn list of the DAG&#39;s MachineFunction.
AMDGPU specific subclass of TargetSubtarget.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
bool isPSInputAllocated(unsigned Index) const
SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
bool useDS128() const
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it&#39;s not CSE&#39;d)...
Definition: SelectionDAG.h:895
static ConstantFPSDNode * getSplatConstantFP(SDValue Op)
SI Whole Quad Mode
void allocateHSAUserSGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
bool hasFlatScrRegister() const
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR (an vector value) starting with the ...
Definition: ISDOpcodes.h:412
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
BR_CC - Conditional branch.
Definition: ISDOpcodes.h:708
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &, MachineFunction &MF, unsigned IntrinsicID) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
Address space for 160-bit buffer fat pointers.
Definition: AMDGPU.h:281
Register getLocReg() const
bool hasUsableDivScaleConditionOutput() const
Condition output from div_scale is usable.
void analyzeFormalArgumentsCompute(CCState &State, const SmallVectorImpl< ISD::InputArg > &Ins) const
The SelectionDAGBuilder will automatically promote function arguments with illegal types...
value_iterator value_end() const
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:140
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
bool isCompareAndSwap() const
Returns true if this SDNode represents cmpxchg atomic operation, false otherwise. ...
static MVT getVectorVT(MVT VT, unsigned NumElements)
bool supportSplitCSR(MachineFunction *MF) const override
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
uint64_t getDefaultRsrcDataFormat() const
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition: ISDOpcodes.h:421
iterator begin() const
begin/end - Return all of the registers in this class.
static bool isBoolSGPR(SDValue V)
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition: ValueTypes.h:262
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const
2: 32-bit floating point type
Definition: Type.h:59
static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, const SDLoc &SL, const GCNSubtarget *ST)
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
SDValue copyToM0(SelectionDAG &DAG, SDValue Chain, const SDLoc &DL, SDValue V) const
bool isVector() const
Return true if this is a vector value type.
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:306
bool hasStackObjects() const
Return true if there are any stack objects in this function.
bool isAllocated(unsigned Reg) const
isAllocated - Return true if the specified register (or an alias) is allocated.
const SDValue & getBasePtr() const
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition: MathExtras.h:325
const TargetRegisterClass * getEquivalentVGPRClass(const TargetRegisterClass *SRC) const
unsigned getRegister(unsigned i) const
Return the specified register in the class.
bool isNegative() const
Return true if the value is negative.
bool hasFlatGlobalInsts() const
bool canMergeStoresTo(unsigned AS, EVT MemVT, const SelectionDAG &DAG) const override
Returns if it&#39;s reasonable to merge stores to MemVT size.
SDValue loadInputValue(SelectionDAG &DAG, const TargetRegisterClass *RC, EVT VT, const SDLoc &SL, const ArgDescriptor &Arg) const
bool supportsMinMaxDenormModes() const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void push_back(const T &Elt)
Definition: SmallVector.h:211
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:400
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
bool useVGPRIndexMode() const
unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:63
void allocateSpecialInputVGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:188
void setIsUndef(bool Val=true)
bool hasFmaMixInsts() const
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
const SDValue & getValue() const
unsigned addKernargSegmentPtr(const SIRegisterInfo &TRI)
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
SDVTList getVTList() const
This class represents a function call, abstracting a target machine&#39;s calling convention.
unsigned Reg
static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask=~0u, ArgDescriptor Arg=ArgDescriptor())
Address space for global memory (RAT0, VTX0).
Definition: AMDGPU.h:272
unsigned getSubReg() const
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:255
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:160
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:637
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change...
const GCNSubtarget * getSubtarget() const
bool hasAtomicFaddInsts() const
bool hasTrigReducedRange() const
float BitsToFloat(uint32_t Bits)
This function takes a 32-bit integer and returns the bit equivalent float.
Definition: MathExtras.h:632
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
static bool hasFP32Denormals(const MachineFunction &MF)
unsigned getVectorNumElements() const
const SDValue & getChain() const
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1157
Function Alias Analysis Results
SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
Definition: MachineInstr.h:879
const SIInstrInfo * getInstrInfo() const override
static const fltSemantics & EVTToAPFloatSemantics(EVT VT)
Returns an APFloat semantics tag appropriate for the given type.
static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val)
unsigned getAlignment() const
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
Definition: ISDOpcodes.h:863
unsigned second
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
SDNode * legalizeTargetIndependentNode(SDNode *Node, SelectionDAG &DAG) const
Legalize target independent instructions (e.g.
static uint32_t Concat[]
static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue C, SDValue GlueChain)
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, ImmutableCallSite CS) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:141
F(f)
bool isAGPR(const MachineRegisterInfo &MRI, unsigned Reg) const
void markPSInputEnabled(unsigned Index)
const TargetRegisterClass * getEquivalentSGPRClass(const TargetRegisterClass *VRC) const
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS)
Helper function to make it easier to build Select&#39;s if you just have operands and don&#39;t want to check...
const fltSemantics & getSemantics() const
Definition: APFloat.h:1175
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:875
1: 16-bit floating point type
Definition: Type.h:58
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is &#39;desirable&#39; to us...
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:445
const SDNodeFlags getFlags() const
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:710
MachineFunction & getMachineFunction() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
iv Induction Variable Users
Definition: IVUsers.cpp:52
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
Definition: SelectionDAG.h:491
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
LLVM_READONLY int getAtomicNoRetOp(uint16_t Opcode)
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition: ValueTypes.h:212
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
CLAMP value between 0.0 and 1.0.
static MachineBasicBlock * emitIndirectDst(MachineInstr &MI, MachineBasicBlock &MBB, const GCNSubtarget &ST)
bool isInlineConstant(const APInt &Imm) const
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1 at the ...
Definition: ISDOpcodes.h:407
Align getPrefLoopAlignment(MachineLoop *ML) const override
Return the preferred loop alignment.
unsigned int NumVTs
bool hasFastFMAF32() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:838
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
Address space for flat memory.
Definition: AMDGPU.h:271
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:496
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node.
const DebugLoc & getDebugLoc() const
Calling convention used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:202
void legalizeOperands(MachineInstr &MI, MachineDominatorTree *MDT=nullptr) const
Legalize all operands in this instruction.
LLVM_READONLY const MIMGLZMappingInfo * getMIMGLZMappingInfo(unsigned L)
const SIRegisterInfo & getRegisterInfo() const
Definition: SIInstrInfo.h:173
bool hasMad64_32() const
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
return AArch64::GPR64RegClass contains(Reg)
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
LLVM_READONLY int getVOPe64(uint16_t Opcode)
bool hasVOP3PInsts() const
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:160
bool isMemLoc() const
unsigned getAddressSpace() const
Return the address space for the associated pointer.
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
MachineSDNode * wrapAddr64Rsrc(SelectionDAG &DAG, const SDLoc &DL, SDValue Ptr) const
static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, EVT VT)
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1246
LLVM_READONLY int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0&#39;s from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:156
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:136
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations...
Definition: ISDOpcodes.h:517
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
Definition: APInt.h:1689
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
void setPrivateSegmentWaveByteOffset(unsigned Reg)
#define FP_DENORM_FLUSH_NONE
Definition: SIDefines.h:601
static unsigned numBitsUnsigned(SDValue Op, SelectionDAG &DAG)
uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the largest uint64_t less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:742
bool hasOneUse() const
Return true if there is exactly one use of this node.
static unsigned findFirstFreeSGPR(CCState &CCInfo)
A description of a memory reference used in the backend.
unsigned DemoteRegister
DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg allocated to hold a pointer to ...
static bool elementPairIsContiguous(ArrayRef< int > Mask, int Elt)
bool isSigned() const
Definition: InstrTypes.h:902
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:659
bool hasDwordx3LoadStores() const
Type * getPointerElementType() const
Definition: Type.h:381
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition: APInt.h:1495
const HexagonInstrInfo * TII
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:460
bool isSGPRReg(const MachineRegisterInfo &MRI, unsigned Reg) const
Shift and rotation operations.
Definition: ISDOpcodes.h:471
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
static bool isGather4(const MachineInstr &MI)
Definition: SIInstrInfo.h:489
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:140
void setHasNonSpillStackObjects(bool StackObject=true)
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
unsigned addDispatchID(const SIRegisterInfo &TRI)
EVT getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset, bool MemcpyStrSrc, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset...
static bool isMIMG(const MachineInstr &MI)
Definition: SIInstrInfo.h:481
bool isKnownNeverNaNForTargetNode(SDValue Op, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const override
If SNaN is false,.
SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
The returned value is undefined.
Definition: MathExtras.h:46
MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s), MachineInstr opcode, and operands.
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
BinOp getOperation() const
Definition: Instructions.h:769
bool isMemOpUniform(const SDNode *N) const
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, int64_t Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object...
Definition: SelectionDAG.h:866
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
static unsigned SubIdx2Lane(unsigned Idx)
Helper function for adjustWritemask.
CopyToReg - This node has three operands: a chain, a register number to set to this value...
Definition: ISDOpcodes.h:171
unsigned SubReg
ArrayRef< MachineMemOperand * > memoperands() const
MachineOperand buildExtractSubRegOrImm(MachineBasicBlock::iterator MI, MachineRegisterInfo &MRI, MachineOperand &SuperReg, const TargetRegisterClass *SuperRC, unsigned SubIdx, const TargetRegisterClass *SubRC) const
static bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
op_iterator op_end() const
bool hasD16Images() const
uint64_t getConstantOperandVal(unsigned i) const
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
static ArgDescriptor allocateSGPR64Input(CCState &CCInfo)
SimpleValueType SimpleTy
static MVT memVTFromAggregate(Type *Ty)
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
The memory access is dereferenceable (i.e., doesn&#39;t trap).
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amt) For double-word atomic operations: ValLo, ValHi, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amtLo, amtHi) ValLo, ValHi, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amtLo, amtHi) These correspond to the atomicrmw instruction.
Definition: ISDOpcodes.h:871
unsigned Intr
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:426
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
Definition: SelectionDAG.h:485
bool isTrapHandlerEnabled() const
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
Address space for 32-bit constant memory.
Definition: AMDGPU.h:279
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:423
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:600
This is an SDNode representing atomic operations.
int getMaskedMIMGOp(unsigned Opc, unsigned NewChannels)
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Definition: DerivedTypes.h:398
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
LocInfo getLocInfo() const
Align commonAlignment(Align A, Align B)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:215
bool isSGPRClass(const TargetRegisterClass *RC) const
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
zlib style complession
Align getAlignment() const
Return alignment of the basic block.
This file implements a class to represent arbitrary precision integral constant values and operations...
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:725
This represents a list of ValueType&#39;s that has been intern&#39;d by a SelectionDAG.
SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
bool isSDNodeSourceOfDivergence(const SDNode *N, FunctionLoweringInfo *FLI, LegacyDivergenceAnalysis *DA) const override
BlockT * getHeader() const
Definition: LoopInfo.h:105
SmallVector< ISD::InputArg, 32 > Ins
void legalizeOperandsVOP3(MachineRegisterInfo &MRI, MachineInstr &MI) const
Fix operands in MI to satisfy constant bus requirements.
SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
static void reservePrivateMemoryRegs(const TargetMachine &TM, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info)
Address space for region memory. (GDS)
Definition: AMDGPU.h:273
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
InstrTy * getInstruction() const
Definition: CallSite.h:96
SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
Class to represent function types.
Definition: DerivedTypes.h:108
unsigned getNextStackOffset() const
getNextStackOffset - Return the next stack offset such that all stack slots satisfy their alignment r...
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1632
bool isInfinity() const
Definition: APFloat.h:1164
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:423
SDValue SplitVectorLoad(SDValue Op, SelectionDAG &DAG) const
Split a vector load into 2 loads of half the vector.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:420
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition: ISDOpcodes.h:539
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose...
void setStackPtrOffsetReg(unsigned Reg)
void limitOccupancy(const MachineFunction &MF)
Definition: Lint.cpp:84
static unsigned getBufferOffsetForMMO(SDValue VOffset, SDValue SOffset, SDValue Offset, SDValue VIndex=SDValue())
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:454
bool useFlatForGlobal() const
SDValue getRegisterMask(const uint32_t *RegMask)
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
bool splitMUBUFOffset(uint32_t Imm, uint32_t &SOffset, uint32_t &ImmOffset, const GCNSubtarget *Subtarget, uint32_t Align)
static cl::opt< bool > DisableLoopAlignment("amdgpu-disable-loop-alignment", cl::desc("Do not align and prefetch loops"), cl::init(false))
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, unsigned OperandName) const
Returns the operand named Op.
const TargetMachine & getTarget() const
Definition: SelectionDAG.h:424
bool shouldEmitGOTReloc(const GlobalValue *GV) const
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:202
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
SITargetLowering(const TargetMachine &tm, const GCNSubtarget &STI)
SmallVector< ISD::OutputArg, 32 > Outs
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Definition: CallSite.h:279
void allocateSpecialInputSGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
Align getStackAlignment() const
static bool vectorEltWillFoldAway(SDValue Op)
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:113
static LLVM_ATTRIBUTE_UNUSED bool isCopyFromRegOfInlineAsm(const SDNode *N)
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:244
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false)
Helper function to make it easier to build SetCC&#39;s if you just have an ISD::CondCode instead of an SD...
Definition: SelectionDAG.h:996
bool enableAggressiveFMAFusion(EVT VT) const override
Return true if target always beneficiates from combining into FMA for a given value type...
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc)
uint32_t getImplicitParameterOffset(const MachineFunction &MF, const ImplicitParameter Param) const
Helper function that returns the byte offset of the given type of implicit parameter.
static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
bool FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
Definition: SelectionDAG.h:911
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition: APFloat.h:177
bool isKnownNeverNaN(SDValue Op, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue is known to never be NaN.
std::pair< SDValue, SDValue > split64BitValue(SDValue Op, SelectionDAG &DAG) const
Return 64-bit value Op as two 32-bit integers.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:1047
op_iterator op_begin() const
static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, ISD::LoadExtType ExtType, SDValue Op, const SDLoc &SL, EVT VT)
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors...
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition: Analysis.cpp:201
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
Definition: SelectionDAG.h:604
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
Definition: ISDOpcodes.h:808
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
bool getAddrModeArguments(IntrinsicInst *, SmallVectorImpl< Value *> &, Type *&) const override
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements. ...
Definition: SelectionDAG.h:775
void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock *> &Exits) const override
Insert explicit copies in entry and exit blocks.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
unsigned getUndefRegState(bool B)
void markPSInputAllocated(unsigned Index)
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition: ISDOpcodes.h:152
static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, EVT VT)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, SDValue *LWE, bool &IsTexFail)
SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands...
unsigned getSrcAddressSpace() const
static bool hasFP64FP16Denormals(const MachineFunction &MF)
Value * getOperand(unsigned i) const
Definition: User.h:169
Analysis containing CSE Info
Definition: CSEInfo.cpp:25
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Class to represent pointers.
Definition: DerivedTypes.h:579
unsigned getByValSize() const
UNDEF - An undefined node.
Definition: ISDOpcodes.h:179
This class is used to represent ISD::STORE nodes.
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition: ISDOpcodes.h:585
SDValue splitBinaryVectorOp(SDValue Op, SelectionDAG &DAG) const
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:139
bool hasAllowReciprocal() const
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a vector with the specified, possibly variable...
Definition: ISDOpcodes.h:381
TargetInstrInfo - Interface to description of machine instruction set.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
const Value * getValue() const
Return the base address of the memory access.
Calling convention used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:208
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:652
bool hasUnalignedBufferAccess() const
11: Arbitrary bit width integers
Definition: Type.h:71
bool hasDot2Insts() const
bool hasAllowContract() const
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
The memory access is volatile.
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:661
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define P(N)
const SDValue & getBasePtr() const
static bool fp16SrcZerosHighBits(unsigned Opc)
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
std::vector< AsmOperandInfo > AsmOperandInfoVector
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition: ISDOpcodes.h:167
unsigned UnsafeFPMath
UnsafeFPMath - This flag is enabled when the -enable-unsafe-fp-math flag is specified on the command ...
SDValue performRcpCombine(SDNode *N, DAGCombinerInfo &DCI) const
FPOpFusion::FPOpFusionMode AllowFPOpFusion
AllowFPOpFusion - This flag is set by the -fuse-fp-ops=xxx option.
Control flow instructions. These all have token chains.
Definition: ISDOpcodes.h:687
bool isMemOpHasNoClobberedMemOperand(const SDNode *N) const
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
const AMDGPUGWSResourcePseudoSourceValue * getGWSPSV(const SIInstrInfo &TII)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
bool isNegative() const
Definition: APFloat.h:1167
MachineBasicBlock * splitKillBlock(MachineInstr &MI, MachineBasicBlock *BB) const
constexpr bool isUInt< 8 >(uint64_t x)
Definition: MathExtras.h:379
unsigned const MachineRegisterInfo * MRI
const MCInstrDesc & getKillTerminatorFromPseudo(unsigned Opcode) const
bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:465
unsigned getKnownHighZeroBitsForFrameIndex() const
Return the number of high bits known to be zero fror a frame index.
Machine Value Type.
unsigned reservedPrivateSegmentWaveByteOffsetReg(const MachineFunction &MF) const
Return the end register initially reserved for the scratch wave offset in case spilling is needed...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
void allocateSpecialEntryInputVGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
Simple binary floating point operators.
Definition: ISDOpcodes.h:295
SDValue storeStackInputValue(SelectionDAG &DAG, const SDLoc &SL, SDValue Chain, SDValue ArgVal, int64_t Offset) const
void setTargetDAGCombine(ISD::NodeType NT)
Targets should invoke this method for each target independent node that they want to provide a custom...
bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
bool isMachineOpcode() const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition: ValueTypes.h:275
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
bool isNaN() const
Definition: APFloat.h:1165
SDNode * PostISelFolding(MachineSDNode *N, SelectionDAG &DAG) const override
Fold the instructions after selecting them.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
unsigned getReturnAddressReg(const MachineFunction &MF) const
void fixImplicitOperands(MachineInstr &MI) const
bool hasDLInsts() const
const RsrcIntrinsic * lookupRsrcIntrinsic(unsigned Intr)
constexpr char WavefrontSize[]
Key for Kernel::CodeProps::Metadata::mWavefrontSize.
const SDValue & getOperand(unsigned Num) const
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
Definition: ISDOpcodes.h:1022
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL...
Definition: ISDOpcodes.h:386
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const MCPhysReg * getCalleeSavedRegsViaCopy(const MachineFunction *MF) const
bool hasBitPreservingFPLogic(EVT VT) const override
Return true if it is safe to transform an integer-domain bitwise operation into the equivalent floati...
std::pair< const ArgDescriptor *, const TargetRegisterClass * > getPreloadedValue(PreloadedValue Value) const
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition: ValueTypes.h:249
bool isKnownNeverSNaN(SDValue Op, unsigned Depth=0) const
bool has16BitInsts() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
bool isEntryFunctionCC(CallingConv::ID CC)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
Definition: SelectionDAG.h:883
static bool isUniformMMO(const MachineMemOperand *MMO)
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
bool isEligibleForTailCallOptimization(SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SmallVectorImpl< ISD::InputArg > &Ins, SelectionDAG &DAG) const
std::pair< SDValue, SDValue > SplitVectorOperand(const SDNode *N, unsigned OpNo)
Split the node&#39;s operand with EXTRACT_SUBVECTOR and return the low/high part.
AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all...
virtual SDValue LowerGlobalAddress(AMDGPUMachineFunction *MFI, SDValue Op, SelectionDAG &DAG) const
virtual void computeKnownBitsForFrameIndex(const SDValue FIOp, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine which of the bits of FrameIndex FIOp are known to be 0.
const AMDGPUBufferPseudoSourceValue * getBufferPSV(const SIInstrInfo &TII, const Value *BufferRsrc)
void setType(unsigned VReg, LLT Ty)
Set the low-level type of VReg to Ty.
bool isKnownNeverNaNForTargetNode(SDValue Op, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const override
If SNaN is false,.
SI DAG Lowering interface definition.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop alignment.
static std::pair< MachineBasicBlock *, MachineBasicBlock * > splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop)
const SIFrameLowering * getFrameLowering() const override
unsigned getDestAddressSpace() const
AMDGPU::SIModeRegisterDefaults getMode() const
bool isIntrinsicSourceOfDivergence(unsigned IntrID)
bool mayBeEmittedAsTailCall(const CallInst *) const override
Return true if the target may be able emit the call instruction as a tail call.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This class provides iterator support for SDUse operands that use a specific SDNode.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
bool isExactlyValue(double V) const
We don&#39;t rely on operator== working on double values, as it returns true for things that are clearly ...
bool hasLDSFPAtomics() const
bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side...
MachineBasicBlock::instr_iterator begin() const
Return an iterator to the first bundled instruction.
unsigned getMachineOpcode() const
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:144
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:186
static SDValue constructRetValue(SelectionDAG &DAG, MachineSDNode *Result, ArrayRef< EVT > ResultTypes, bool IsTexFail, bool Unpacked, bool IsD16, int DMaskPop, int NumVDataDwords, const SDLoc &DL, LLVMContext &Context)
unsigned getAddressSpace() const
Definition: Globals.cpp:111
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
void setOffset(int64_t NewOffset)
bool DX10Clamp
Used by the vector ALU to force DX10-style treatment of NaNs: when set, clamp NaN to zero; otherwise...
unsigned addQueuePtr(const SIRegisterInfo &TRI)
constexpr double e
Definition: MathExtras.h:57
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using &#39;From&#39; to use &#39;To&#39; instead.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition: ValueTypes.h:314
static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, const TargetRegisterClass *VecRC)
TRAP - Trapping instruction.
Definition: ISDOpcodes.h:828
bool bitsLE(MVT VT) const
Return true if this has no more bits than VT.
const APInt & getAPIntValue() const
Generation getGeneration() const
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline...
const Triple & getTargetTriple() const
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition: ISDOpcodes.h:58
static ArgDescriptor createStack(unsigned Offset, unsigned Mask=~0u)
static bool resultsCompatible(CallingConv::ID CalleeCC, CallingConv::ID CallerCC, MachineFunction &MF, LLVMContext &C, const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn CalleeFn, CCAssignFn CallerFn)
Returns true if the results of the two calling conventions are compatible.
DEBUGTRAP - Trap intended to get the attention of a debugger.
Definition: ISDOpcodes.h:831
static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, EVT VT, SDValue N0, SDValue N1, SDValue N2, bool Signed)
#define FP_DENORM_FLUSH_IN_FLUSH_OUT
Definition: SIDefines.h:598
SDNode * getGluedNode() const
If this node has a glue operand, return the node to which the glue operand points.
void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
self_iterator getIterator()
Definition: ilist_node.h:81
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the &#39;usesCustomInserter&#39; fla...
CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y)...
static MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:324
static std::pair< unsigned, int > computeIndirectRegAndOffset(const SIRegisterInfo &TRI, const TargetRegisterClass *SuperRC, unsigned VecReg, int Offset)
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
AMDGPUFunctionArgInfo & getArgInfo()
The AMDGPU TargetMachine interface definition for hw codgen targets.
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
static void r1(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition: SHA1.cpp:49
Bit counting operators with an undefined result for zero inputs.
Definition: ISDOpcodes.h:477
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo...
Definition: ISDOpcodes.h:857
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:610
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:75
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
static MachineBasicBlock * emitIndirectSrc(MachineInstr &MI, MachineBasicBlock &MBB, const GCNSubtarget &ST)
const Pass * getPass() const
Definition: SelectionDAG.h:421
Extended Value Type.
Definition: ValueTypes.h:34
void setScratchWaveOffsetReg(unsigned Reg)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
const MachineBasicBlock & front() const
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:298
This structure contains all information that is necessary for lowering calls.
size_t size() const
Definition: SmallVector.h:52
bool hasUnalignedScratchAccess() const
bool isVolatile() const
const TargetMachine & getTargetMachine() const
This class contains a discriminated union of information about pointers in memory operands...
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode...
unsigned getNumOperands() const
Return the number of values used by this operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
TrapHandlerAbi getTrapHandlerAbi() const
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
constexpr char NumSGPRs[]
Key for Kernel::CodeProps::Metadata::mNumSGPRs.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value...
unsigned addDispatchPtr(const SIRegisterInfo &TRI)
SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands...
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
int getMIMGOpcode(unsigned BaseOpcode, unsigned MIMGEncoding, unsigned VDataDwords, unsigned VAddrDwords)
static CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg)
Selects the correct CCAssignFn for a given CallingConvention value.
bool hasUnpackedD16VMem() const
unsigned getAddressSpace() const
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:499
The memory access writes data.
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
bool getScalarizeGlobalBehavior() const
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
uint64_t getNullPointerValue(unsigned AddrSpace) const
Get the integer value of a null pointer in the given address space.
static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, MachineRegisterInfo &MRI, MachineInstr &MI, int Offset, bool UseGPRIdxMode, bool IsIndirectSrc)
const unsigned MaxDepth
void allocateSystemSGPRs(CCState &CCInfo, MachineFunction &MF, SIMachineFunctionInfo &Info, CallingConv::ID CallConv, bool IsShader) const
bool hasFlatAddressSpace() const
unsigned getWavefrontSize() const
bool hasAddr64() const
static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, const SDLoc &DL, unsigned Offset, EVT PtrVT, unsigned GAFlags=SIInstrInfo::MO_NONE)
SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type...
SDValue addTokenForArgument(SDValue Chain, SelectionDAG &DAG, MachineFrameInfo &MFI, int ClobberedFI) const
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, unsigned Alignment=1, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, bool *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
MachineBasicBlock * emitGWSMemViolTestLoop(MachineInstr &MI, MachineBasicBlock *BB) const
static bool isUndef(ArrayRef< int > Mask)
static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, const TargetRegisterClass *RC, unsigned NumArgRegs)
TokenFactor - This node takes multiple tokens as input and produces a single token result...
Definition: ISDOpcodes.h:51
MVT getScalarShiftAmountTy(const DataLayout &, EVT) const override
EVT is not used in-tree, but is used by out-of-tree target.
int pseudoToMCOpcode(int Opcode) const
Return a target-specific opcode if Opcode is a pseudo instruction.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
MachineSDNode * buildRSRC(SelectionDAG &DAG, const SDLoc &DL, SDValue Ptr, uint32_t RsrcDword1, uint64_t RsrcDword2And3) const
Return a resource descriptor with the &#39;Add TID&#39; bit enabled The TID (Thread ID) is multiplied by the ...
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:426
Iterator for intrusive lists based on ilist_node.
bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, EVT DestVT, EVT SrcVT) const override
Return true if an fpext operation input to an Opcode operation is free (for instance, because half-precision floating-point numbers are implicitly extended to float-precision) for an FMA instruction.
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
CCState - This class holds information needed while lowering arguments and return values...
void setNoUnsignedWrap(bool b)
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
Definition: SelectionDAG.h:650
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
unsigned countPopulation(T Value)
Count the number of set bits in a value.
Definition: MathExtras.h:556
unsigned getWavefrontSize(const MCSubtargetInfo *STI)
static ArgDescriptor allocateSGPR32Input(CCState &CCInfo)
bool haveRoundOpsF64() const
Have v_trunc_f64, v_ceil_f64, v_rndne_f64.
static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V)
bool hasDenormModeInst() const
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Returns platform specific canonical encoding of a floating point number.
Definition: ISDOpcodes.h:373
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition: ISDOpcodes.h:393
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition: ValueTypes.h:267
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition: Error.h:147
SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
SDValue splitTernaryVectorOp(SDValue Op, SelectionDAG &DAG) const
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:223
SDValue lowerUnhandledCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals, StringRef Reason) const
bool hasMadMixInsts() const
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:208
SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
Address space for local memory.
Definition: AMDGPU.h:276
ADDRSPACECAST - This operator converts between pointers of different address spaces.
Definition: ISDOpcodes.h:629
MachineOperand class - Representation of each machine instruction operand.
value_iterator value_begin() const
Calling convention used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:205
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
unsigned getScratchRSrcReg() const
Returns the physical register reserved for use as the resource descriptor for scratch accesses...
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
Definition: SelectionDAG.h:758
bool hasFFBL() const
const DebugLoc & getDebugLoc() const
bool isFMADLegalForFAddFSub(const SelectionDAG &DAG, const SDNode *N) const override
Returns true if the FADD or FSUB node passed could legally be combined with an fmul to form an ISD::F...
CCValAssign - Represent assignment of one arg/retval to a location.
SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, unsigned Align, bool isVol, bool AlwaysInline, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
SDValue WidenVectorLoad(SDValue Op, SelectionDAG &DAG) const
Widen a vector load from vec3 to vec4.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:755
BRCOND - Conditional branch.
Definition: ISDOpcodes.h:702
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimum or maximum on two values, following the IEEE-754 2008 definition.
Definition: ISDOpcodes.h:658
An SDNode that represents everything that will be needed to construct a MachineInstr.
Promote Memory to Register
Definition: Mem2Reg.cpp:110
bool hasMin3Max3_16() const
Byte Swap and Counting operators.
Definition: ISDOpcodes.h:474
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
Definition: ISDOpcodes.h:635
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue GlueChain)
This is an abstract virtual class for memory operations.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_READNONE bool isKernel(CallingConv::ID CC)
TypeSize getScalarSizeInBits() const
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
bool isDivergent() const
static uint32_t getConstantPermuteMask(uint32_t C)
static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, unsigned InitResultReg, unsigned PhiReg, int Offset, bool UseGPRIdxMode, bool IsIndirectSrc)
void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0)
Append the extracted elements from Start to Count out of the vector Op in Args.
Represents one node in the SelectionDAG.
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array...
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1313
SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
int64_t getImm() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N)
Definition: SelectionDAG.h:703
LLVM_READONLY const MIMGMIPMappingInfo * getMIMGMIPMappingInfo(unsigned L)
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
bool isDenormal() const
Definition: APFloat.h:1168
const Function & getFunction() const
Return the LLVM function that this machine code represents.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
static SDNode * findUser(SDValue Value, unsigned Opcode)
Helper function for LowerBRCOND.
const TargetRegisterClass * getRegClassForReg(const MachineRegisterInfo &MRI, unsigned Reg) const
void setWorkItemIDZ(ArgDescriptor Arg)
static bool allUsesHaveSourceMods(const SDNode *N, unsigned CostThreshold=4)
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:585
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:163
bool hasFFBH() const
unsigned getPrivateSegmentWaveByteOffsetSystemSGPR() const
Class to represent vector types.
Definition: DerivedTypes.h:432
SDNode * isConstantIntBuildVectorOrConstantInt(SDValue N)
Test whether the given value is a constant int or similar node.
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT...
Definition: ValueTypes.h:73
EVT getMemoryVT() const
Return the type of the in-memory value.
Target - Wrapper for Target specific information.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
Definition: APInt.h:69
unsigned getByValAlign() const
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
amdgpu Simplify well known AMD library false FunctionCallee Callee
bool isShader(CallingConv::ID cc)
A "pseudo-class" with methods for operating on BUILD_VECTORs.
Select(COND, TRUEVAL, FALSEVAL).
Definition: ISDOpcodes.h:481
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition: ValueTypes.h:243
void finalizeLowering(MachineFunction &MF) const override
Execute target specific actions to finalize target lowering.
static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, ArrayRef< SDValue > Elts)
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1329
static use_iterator use_end()
iterator_range< user_iterator > users()
Definition: Value.h:420
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:529
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
bool hasMed3_16() const
void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:532
bool isTailCall() const
static unsigned numBitsSigned(SDValue Op, SelectionDAG &DAG)
int getLDSBankCount() const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:467
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors...
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition: ISDOpcodes.h:366
int getMaskElt(unsigned Idx) const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
Assign the register class depending on the number of bits set in the writemask.
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfo(unsigned DimEnum)
static bool isFlatGlobalAddrSpace(unsigned AS)
static bool isVOP3(const MachineInstr &MI)
Definition: SIInstrInfo.h:421
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition: APInt.h:611
unsigned addPrivateSegmentBuffer(const SIRegisterInfo &TRI)
Flags
Flags values. These may be or&#39;d together.
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
unsigned addFlatScratchInit(const SIRegisterInfo &TRI)
static CCAssignFn * CCAssignFnForReturn(CallingConv::ID CC, bool IsVarArg)
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
The memory access reads data.
unsigned getOrigArgIndex() const
std::pair< const ArgDescriptor *, const TargetRegisterClass * > getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
LoopT * getParentLoop() const
Definition: LoopInfo.h:106
bool isLiveIn(unsigned Reg) const
void bundleInstWithWaitcnt(MachineInstr &MI) const
Insert MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
Provides AMDGPU specific target descriptions.
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
These are IR-level optimization flags that may be propagated to SDNodes.
static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, uint64_t Val)
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array...
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
SmallVector< SDValue, 32 > OutVals
Interface definition for SIInstrInfo.
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent) const override
Return the register class that should be used for the specified value type.
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition: MathExtras.h:459
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AS, unsigned Align, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, bool *IsFast=nullptr) const override
Determine if the target supports unaligned memory accesses.
bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
unsigned AllocateStack(unsigned Size, unsigned Alignment)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:215
bool isCanonicalized(SelectionDAG &DAG, SDValue Op, unsigned MaxDepth=5) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:448
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB &#39;Other&#39; at the position From, and insert it into this MBB right before &#39;...
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT)
Definition: SelectionDAG.h:729
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getLocMemOffset() const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, const DebugLoc &DL, const MachineOperand &IdxReg, unsigned InitReg, unsigned ResultReg, unsigned PhiReg, unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, bool IsIndirectSrc)
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition: ISDOpcodes.h:547
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:672
static bool isClampZeroToOne(SDValue A, SDValue B)
PointerUnion< const Value *, const PseudoSourceValue * > ptrVal
TargetOptions Options
Establish a view to a call site for examination.
Definition: CallSite.h:697
SDValue splitBinaryBitConstantOpImpl(DAGCombinerInfo &DCI, const SDLoc &SL, unsigned Opc, SDValue LHS, uint32_t ValLo, uint32_t ValHi) const
Split the 64-bit value LHS into two 32-bit components, and perform the binary operation Opc to it wit...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
Definition: CallingConv.h:199
#define I(x, y, z)
Definition: MD5.cpp:58
bool isShuffleMaskLegal(ArrayRef< int >, EVT) const override
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations, those with specific masks.
#define N
bool allowsMisalignedMemoryAccessesImpl(unsigned Size, unsigned AS, unsigned Align, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, bool *IsFast=nullptr) const
void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Flags getFlags() const
Return the raw flags of the source value,.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
The memory access always returns the same value (or traps).
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:192
bool hasFlatInstOffsets() const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL, bool LegalTypes=true)
bool isAmdHsaOrMesa(const Function &F) const
static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, SDValue *GLC, SDValue *SLC, SDValue *DLC)
bool shouldEmitConstantsToTextSection(const Triple &TT)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
bool denormalsEnabledForType(const SelectionDAG &DAG, EVT VT) const
Type * getValueType() const
Definition: GlobalValue.h:279
uint32_t Size
Definition: Profile.cpp:46
SDValue splitUnaryVectorOp(SDValue Op, SelectionDAG &DAG) const
const Value * getValueFromVirtualReg(unsigned Vreg)
This method is called from TargetLowerinInfo::isSDNodeSourceOfDivergence to get the Value correspondi...
bool FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
static void r0(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition: SHA1.cpp:43
unsigned getOpcode() const
FSINCOS - Compute both fsin and fcos as a single operation.
Definition: ISDOpcodes.h:666
Address space for private memory.
Definition: AMDGPU.h:277
virtual bool requiresUniformRegister(MachineFunction &MF, const Value *V) const override
Allows target to decide about the register class of the specific value that is live outside the defin...
SDValue getValue(unsigned R) const
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition: APFloat.h:924
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
bool isInfinity() const
Return true if the value is an infinity.
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:382
void setSimpleHint(unsigned VReg, unsigned PrefReg)
Specify the preferred (target independent) register allocation hint for the specified virtual registe...
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition: ISDOpcodes.h:176
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
Definition: SelectionDAG.h:482
bool isReg() const
isReg - Tests if this is a MO_Register operand.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getCondCode(ISD::CondCode Cond)
static bool isFrameIndexOp(SDValue Op)
bool isRegLoc() const
const MachinePointerInfo & getPointerInfo() const
void reset()
Definition: Optional.h:251
SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align=0, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, uint64_t Size=0, const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition: ISDOpcodes.h:399
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if &#39;Op & Mask&#39; is known to be zero.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Equivalent to hasAttribute(AttributeList::FunctionIndex, Kind) but may be faster. ...
bool memoperands_empty() const
Return true if we don&#39;t have any memory operands which described the memory access done by this instr...
Definition: MachineInstr.h:579
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getReg() const
SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
void insert(iterator MBBI, MachineBasicBlock *MBB)
SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
static bool canGuaranteeTCO(CallingConv::ID CC)
void setReturnAddressIsTaken(bool s)
INLINEASM_BR - Terminator version of inline asm. Used by asm-goto.
Definition: ISDOpcodes.h:728
TypeSize getScalarSizeInBits() const
Definition: ValueTypes.h:304
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
static MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition: MathExtras.h:320
ArrayRef< int > getMask() const
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
FMA - Perform a * b + c with no intermediate rounding step.
Definition: ISDOpcodes.h:356
const AMDGPUImagePseudoSourceValue * getImagePSV(const SIInstrInfo &TII, const Value *ImgRsrc)
SDValue getRegister(unsigned Reg, EVT VT)
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
EVT changeTypeToInteger()
Return the type converted to an equivalently sized integer or vector with integer element type...
Definition: ValueTypes.h:115
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:69
bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond)
Helper function to make it easier to build SelectCC&#39;s if you just have an ISD::CondCode instead of an...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:279
bool hasNoUnsignedWrap() const
SDValue getValueType(EVT)
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:199
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, const SDLoc &DL, SelectionDAG &DAG, bool Unpacked)
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
void computeKnownBitsForFrameIndex(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits of FrameIndex FIOp are known to be 0.
bool hasMAIInsts() const
void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone...
static EVT getEquivalentMemType(LLVMContext &Context, EVT VT)
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
Type * getElementType() const
Definition: DerivedTypes.h:399
IRTranslator LLVM IR MI
const APFloat & getValueAPF() const
bool isLegalFLATOffset(int64_t Offset, unsigned AddrSpace, bool Signed) const
Returns if Offset is legal for the subtarget as the offset to a FLAT encoded instruction.
static MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations...
Definition: ISDOpcodes.h:360
SetCC operator - This evaluates to a true value iff the condition is true.
Definition: ISDOpcodes.h:504
void RemoveOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
APInt bitcastToAPInt() const
Definition: APFloat.h:1114
void setWorkItemIDY(ArgDescriptor Arg)
SDValue SplitVectorStore(SDValue Op, SelectionDAG &DAG) const
Split a vector store into 2 stores of half the vector.
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition: ValueTypes.h:225
unsigned getNumOperands() const
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition: ISDOpcodes.h:199
Register getReg() const
getReg - Returns the register number.
Conversion operators.
Definition: ISDOpcodes.h:526
bool isTypeDesirableForOp(unsigned Op, EVT VT) const override
Return true if the target has native support for the specified value type and it is &#39;desirable&#39; to us...
const SDValue & getOperand(unsigned i) const
OUTCHAIN = ATOMIC_STORE(INCHAIN, ptr, val) This corresponds to "store atomic" instruction.
Definition: ISDOpcodes.h:850
uint64_t getZExtValue() const
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:535
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:75
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition: ValueTypes.h:126
void passSpecialInputs(CallLoweringInfo &CLI, CCState &CCInfo, const SIMachineFunctionInfo &Info, SmallVectorImpl< std::pair< unsigned, SDValue >> &RegsToPass, SmallVectorImpl< SDValue > &MemOpChains, SDValue Chain) const
SDValue LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals, bool isThisReturn, SDValue ThisVal) const
void setBytesInStackArgArea(unsigned Bytes)
std::pair< unsigned, unsigned > getFlatWorkGroupSizes(const Function &F) const
unsigned AllocateReg(unsigned Reg)
AllocateReg - Attempt to allocate one register.
AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all...
unsigned getLiveInVirtReg(unsigned PReg) const
getLiveInVirtReg - If PReg is a live-in physical register, return the corresponding live-in physical ...
void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand *> NewMemRefs)
Mutate the specified machine node&#39;s memory references to the provided list.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:161
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the &#39;usesCustomInserter&#39; fla...
void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
Perform various unary floating-point operations inspired by libm.
Definition: ISDOpcodes.h:640
static bool hasCFUser(const Value *V, SmallPtrSet< const Value *, 16 > &Visited)
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:211
unsigned getMaxPrivateElementSize() const
static void processShaderInputArgs(SmallVectorImpl< ISD::InputArg > &Splits, CallingConv::ID CallConv, ArrayRef< ISD::InputArg > Ins, BitVector &Skipped, FunctionType *FType, SIMachineFunctionInfo *Info)
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition: ValueTypes.h:64
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register...
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
Definition: ISDOpcodes.h:846
bool isSignaling() const
Definition: APFloat.h:1169
MVT getVectorIdxTy(const DataLayout &) const override
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
bool use_empty() const
Definition: Value.h:343
const SDValue & getBasePtr() const
LLVMContext * getContext() const
Definition: SelectionDAG.h:430
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition: ISDOpcodes.h:429
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:906
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Return true if it is beneficial to convert a load of a constant to just the constant itself...
void initializeSplitCSR(MachineBasicBlock *Entry) const override
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
Address space for constant memory (VTX2).
Definition: AMDGPU.h:275
Carry-using nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:243
iterator_range< arg_iterator > args()
Definition: Function.h:730
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:218
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:153
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1122
Helper class for constructing bundles of MachineInstrs.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition: Type.h:336
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
const BasicBlock * getParent() const
Definition: Instruction.h:66
bool hasCalls() const
Return true if the current function has any function calls.
const fltSemantics & getFltSemantics() const
Definition: Type.h:169
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
Register getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const
This class is used to represent ISD::LOAD nodes.
const SIRegisterInfo * getRegisterInfo() const override
bool shouldEmitPCReloc(const GlobalValue *GV) const