[clang] [llvm] [SystemZ] SystemZ ABI using shared LLVM ABI (PR #245806)

Dennis Wang via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 24 15:01:17 PST 2026


https://github.com/denniwang created https://github.com/llvm/llvm-project/pull/245806

This ports SystemZ argument and return classification to LLVM’s shared ABI library and enables Clang to use it for both ELF and z/OS XPLINK.

 To represent the existing SystemZ ABI rules, this extends the shared ABI types with inreg support and a distinction between long and long long, and updates Clang’s type and argument-info conversions accordingly.

Adds unit tests.

>From b06ed3ad383e6192d6e5e6118c061592b14f9c3d Mon Sep 17 00:00:00 2001
From: denniswang <denniswang at ibm.com>
Date: Tue, 17 Nov 2026 14:43:58 -0800
Subject: [PATCH 1/2] llvm shared abi systemz impl

---
 clang/lib/CodeGen/CGCall.cpp         |  10 +-
 clang/lib/CodeGen/CodeGenModule.cpp  |  15 +
 clang/lib/CodeGen/QualTypeMapper.cpp |   8 +-
 llvm/include/llvm/ABI/FunctionInfo.h |  16 +
 llvm/include/llvm/ABI/TargetInfo.h   |  16 +
 llvm/include/llvm/ABI/Types.h        |  14 +-
 llvm/lib/ABI/CMakeLists.txt          |   1 +
 llvm/lib/ABI/Targets/SystemZ.cpp     | 504 +++++++++++++++++++++++++++
 8 files changed, 575 insertions(+), 9 deletions(-)
 create mode 100644 llvm/lib/ABI/Targets/SystemZ.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index ae73b16a42782d..3367e03f45c639 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -972,6 +972,7 @@ void CodeGenModule::computeABIInfoUsingLib(CGFunctionInfo &FI) {
       CheckSimple(Target.getDirectAlign(), Res.getDirectAlign(), "DirectAlign");
       CheckSimple(Target.getDirectOffset(), Res.getDirectOffset(),
                   "DirectOffset");
+      CheckSimple(Target.getInReg(), Res.getInReg(), "InReg");
       // Extend falls through to here, and only Direct carries the flag.
       if (Res.isDirect())
         CheckSimple(Target.getCanBeFlattened(), Res.getCanBeFlattened(),
@@ -1038,9 +1039,11 @@ ABIArgInfo CodeGenModule::convertABIArgInfo(const llvm::abi::ArgInfo &AbiInfo,
       DirectAlign = Align->value();
     // TODO: Move Padding into the ABIArgInfo struct when we add support for
     //       targets that need a different setting than we have here.
-    return ABIArgInfo::getDirect(CoercedType, AbiInfo.getDirectOffset(),
-                                 /*Padding=*/nullptr,
-                                 AbiInfo.getCanBeFlattened(), DirectAlign);
+    ABIArgInfo Res = ABIArgInfo::getDirect(
+        CoercedType, AbiInfo.getDirectOffset(),
+        /*Padding=*/nullptr, AbiInfo.getCanBeFlattened(), DirectAlign);
+    Res.setInReg(AbiInfo.getInReg());
+    return Res;
   }
   case llvm::abi::ArgInfo::Extend: {
     llvm::Type *CoercedType = nullptr;
@@ -1061,6 +1064,7 @@ ABIArgInfo CodeGenModule::convertABIArgInfo(const llvm::abi::ArgInfo &AbiInfo,
     else
       Res = ABIArgInfo::getNoExtend(cast<llvm::IntegerType>(CoercedType));
     Res.setConservative(AbiInfo.isConservative());
+    Res.setInReg(AbiInfo.getInReg());
     return Res;
   }
   case llvm::abi::ArgInfo::Indirect: {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 9226f110728dfe..76a4a331b75dd2 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -363,6 +363,9 @@ bool CodeGenModule::shouldUseLLVMABILowering(unsigned CallingConv) const {
   if (T.isSPIRV())
     return T.getVendor() != llvm::Triple::AMD && !getLangOpts().HLSL;
 
+  if (T.getArch() == llvm::Triple::systemz)
+    return true;
+
   if (T.getArch() == llvm::Triple::aarch64 ||
       T.getArch() == llvm::Triple::aarch64_32 ||
       T.getArch() == llvm::Triple::aarch64_be)
@@ -485,6 +488,18 @@ CodeGenModule::getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB) {
     TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
     return *TheLLVMABITargetInfo;
 
+  case llvm::Triple::systemz: {
+    llvm::abi::SystemZABIOptions Opts(T.getOS() == llvm::Triple::ZOS
+                                          ? llvm::abi::SystemZABIKind::XPLINK
+                                          : llvm::abi::SystemZABIKind::ELF);
+    Opts.IsSoftFloatABI = getCodeGenOpts().FloatABI == "soft";
+    Opts.HasVector = !Opts.IsSoftFloatABI && getTarget().getABI() == "vector";
+    initializeCommonABICompatInfo(Opts.CompatInfo,
+                                  getLangOpts().getClangABICompat());
+    TheLLVMABITargetInfo = llvm::abi::createSystemZTargetInfo(TB, Opts);
+    return *TheLLVMABITargetInfo;
+  }
+
   case llvm::Triple::x86_64: {
     StringRef ABI = getTarget().getABI();
     llvm::abi::X86AVXABILevel AVXLevel =
diff --git a/clang/lib/CodeGen/QualTypeMapper.cpp b/clang/lib/CodeGen/QualTypeMapper.cpp
index 3531ec2ba0812d..65abe1d251e81c 100644
--- a/clang/lib/CodeGen/QualTypeMapper.cpp
+++ b/clang/lib/CodeGen/QualTypeMapper.cpp
@@ -204,8 +204,6 @@ QualTypeMapper::convertBuiltinType(const BuiltinType *BT) {
   case BuiltinType::UShort:
   case BuiltinType::Int:
   case BuiltinType::UInt:
-  case BuiltinType::Long:
-  case BuiltinType::ULong:
   case BuiltinType::LongLong:
   case BuiltinType::ULongLong:
   case BuiltinType::Int128:
@@ -214,6 +212,12 @@ QualTypeMapper::convertBuiltinType(const BuiltinType *BT) {
                                   /*Signed=*/BT->isSignedInteger(),
                                   /*IsBitInt=*/false);
 
+  case BuiltinType::Long:
+  case BuiltinType::ULong:
+    return Builder.getIntegerType(ASTCtx.getTypeSize(QT), getTypeAlign(QT),
+                                  /*Signed=*/BT->isSignedInteger(),
+                                  /*IsBitInt=*/false, /*IsLong=*/true);
+
   case BuiltinType::Half:
   case BuiltinType::Float16:
   case BuiltinType::BFloat16:
diff --git a/llvm/include/llvm/ABI/FunctionInfo.h b/llvm/include/llvm/ABI/FunctionInfo.h
index ea145a0ff0d482..aa1fc3dea66f7d 100644
--- a/llvm/include/llvm/ABI/FunctionInfo.h
+++ b/llvm/include/llvm/ABI/FunctionInfo.h
@@ -82,12 +82,14 @@ class ArgInfo {
   bool IndirectByVal : 1;
   bool IndirectRealign : 1;
   bool CanBeFlattened : 1;
+  bool InReg : 1;
   unsigned NeededIntRegs : 3;
   unsigned NeededSseRegs : 3;
 
   ArgInfo(Kind K = Direct)
       : TheKind(K), SignExt(false), ZeroExt(false), Conservative(false),
         IndirectByVal(false), IndirectRealign(false), CanBeFlattened(false),
+        InReg(false),
         NeededIntRegs(0), NeededSseRegs(0) {}
 
 public:
@@ -200,6 +202,13 @@ class ArgInfo {
     return *this;
   }
 
+  /// See getInReg.
+  ArgInfo &setInReg(bool IsInReg = true) {
+    assert((isDirect() || isExtend()) && "Invalid Kind!");
+    InReg = IsInReg;
+    return *this;
+  }
+
   Kind getKind() const { return TheKind; }
   bool isDirect() const { return TheKind == Direct; }
   bool isIndirect() const { return TheKind == Indirect; }
@@ -253,6 +262,13 @@ class ArgInfo {
     return IndirectRealign;
   }
 
+  /// Whether the value is passed in registers, which lowers to the `inreg`
+  /// attribute. Mirrors clang::CodeGen::ABIArgInfo::getInReg.
+  bool getInReg() const {
+    assert((isDirect() || isExtend()) && "Invalid Kind!");
+    return InReg;
+  }
+
   /// Whether a Direct record coercion may be split into one wire argument
   /// per field. Mirrors clang::CodeGen::ABIArgInfo::CanBeFlattened.
   bool getCanBeFlattened() const {
diff --git a/llvm/include/llvm/ABI/TargetInfo.h b/llvm/include/llvm/ABI/TargetInfo.h
index cd88f2ce0492eb..f797f2ca0aadb3 100644
--- a/llvm/include/llvm/ABI/TargetInfo.h
+++ b/llvm/include/llvm/ABI/TargetInfo.h
@@ -237,6 +237,22 @@ struct AArch64ABIOptions {
 LLVM_ABI std::unique_ptr<TargetInfo>
 createAArch64TargetInfo(TypeBuilder &TB, const AArch64ABIOptions &Opts);
 
+enum class SystemZABIKind { ELF, XPLINK };
+
+struct SystemZABIOptions {
+  SystemZABIKind Kind = SystemZABIKind::ELF;
+  bool HasVector = false;
+  bool IsSoftFloatABI = false;
+  ABICompatInfo CompatInfo;
+
+  SystemZABIOptions() = default;
+  explicit SystemZABIOptions(SystemZABIKind Kind) : Kind(Kind) {}
+};
+
+/// Create the SystemZ classifier for the ELF or XPLINK ABI.
+LLVM_ABI std::unique_ptr<TargetInfo>
+createSystemZTargetInfo(TypeBuilder &TB, const SystemZABIOptions &Opts);
+
 } // namespace abi
 } // namespace llvm
 
diff --git a/llvm/include/llvm/ABI/Types.h b/llvm/include/llvm/ABI/Types.h
index f0713312335f9b..eea0a14dffe6c3 100644
--- a/llvm/include/llvm/ABI/Types.h
+++ b/llvm/include/llvm/ABI/Types.h
@@ -167,15 +167,20 @@ class IntegerType : public Type {
 private:
   bool IsSigned;
   bool IsBitInt;
+  bool IsLong;
 
 public:
   IntegerType(uint64_t BitWidth, Align ABIAlign, bool IsSigned,
-              bool IsBitInt = false)
+              bool IsBitInt = false, bool IsLong = false)
       : Type(TypeKind::Integer, TypeSize::getFixed(BitWidth), ABIAlign),
-        IsSigned(IsSigned), IsBitInt(IsBitInt) {}
+        IsSigned(IsSigned), IsBitInt(IsBitInt), IsLong(IsLong) {}
 
   bool isSigned() const { return IsSigned; }
   bool isBitInt() const { return IsBitInt; }
+  /// True for C's `long` and `unsigned long`. These are distinct from
+  /// `long long` even when both have the same width, and some ABIs treat the
+  /// two differently.
+  bool isLong() const { return IsLong; }
   bool isBool() const {
     return getSizeInBits().getFixedValue() == 1 && !IsBitInt;
   }
@@ -528,9 +533,10 @@ class TypeBuilder {
   }
 
   const IntegerType *getIntegerType(uint64_t BitWidth, Align Align, bool Signed,
-                                    bool IsBitInt = false) {
+                                    bool IsBitInt = false,
+                                    bool IsLong = false) {
     return new (Allocator.Allocate<IntegerType>())
-        IntegerType(BitWidth, Align, Signed, IsBitInt);
+        IntegerType(BitWidth, Align, Signed, IsBitInt, IsLong);
   }
 
   const FloatType *getFloatType(const fltSemantics &Semantics, Align Align) {
diff --git a/llvm/lib/ABI/CMakeLists.txt b/llvm/lib/ABI/CMakeLists.txt
index 470c395e5f20d8..68fbcda85802ee 100644
--- a/llvm/lib/ABI/CMakeLists.txt
+++ b/llvm/lib/ABI/CMakeLists.txt
@@ -8,6 +8,7 @@ add_llvm_component_library(LLVMABI
   Targets/AMDGPU.cpp
   Targets/BPF.cpp
   Targets/SPIRV.cpp
+  Targets/SystemZ.cpp
   Targets/X86.cpp
 
   ADDITIONAL_HEADER_DIRS
diff --git a/llvm/lib/ABI/Targets/SystemZ.cpp b/llvm/lib/ABI/Targets/SystemZ.cpp
new file mode 100644
index 00000000000000..271b1726953f66
--- /dev/null
+++ b/llvm/lib/ABI/Targets/SystemZ.cpp
@@ -0,0 +1,504 @@
+//===- SystemZ.cpp - SystemZ ABI Implementation ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/ABI/FunctionInfo.h"
+#include "llvm/ABI/TargetInfo.h"
+#include "llvm/ABI/Types.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include <optional>
+
+namespace llvm::abi {
+
+class SystemZTargetInfo : public TargetInfo {
+public:
+  SystemZTargetInfo(TypeBuilder &TB, const SystemZABIOptions &Opts)
+      : TargetInfo(TB), Opts(Opts) {}
+
+  const ABICompatInfo &getABICompatInfo() const override {
+    return Opts.CompatInfo;
+  }
+
+  void computeInfo(FunctionInfo &FI) const override {
+    if (!maybeCommonClassifyReturnType(FI))
+      FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
+    for (auto &I : FI.arguments())
+      I.Info = classifyArgumentType(I.ABIType);
+  }
+
+  Align getMaxIntegerAlign() const override { return Align(8); }
+
+private:
+  SystemZABIOptions Opts;
+
+  bool isPromotableIntegerTypeForABI(const Type *Ty) const;
+  bool isCompoundType(const Type *Ty) const;
+  bool isVectorArgumentType(const Type *Ty) const;
+  const Type *getFPArgumentType(const Type *Ty, uint64_t Size) const;
+  const Type *getSingleElementType(const Type *Ty) const;
+  ArgInfo classifyReturnType(const Type *RetTy) const;
+  ArgInfo classifyArgumentType(const Type *Ty) const;
+};
+
+bool SystemZTargetInfo::isPromotableIntegerTypeForABI(const Type *Ty) const {
+  // Frontends represent enums using their underlying integer type.
+  const auto *IT = dyn_cast<IntegerType>(Ty);
+  if (!IT)
+    return false;
+  uint64_t Width = IT->getSizeInBits().getFixedValue();
+  return isPromotableInteger(IT) || (IT->isBitInt() ? Width < 64 : Width == 32);
+}
+
+bool SystemZTargetInfo::isCompoundType(const Type *Ty) const {
+  // Clang's ABI aggregate predicate distinguishes member-function pointers
+  // from scalar data-member pointers.
+  const Type *ValueTy = Ty;
+  while (const auto *AT = dyn_cast<AtomicType>(ValueTy))
+    ValueTy = AT->getValueType();
+  if (const auto *MPT = dyn_cast<MemberPointerType>(ValueTy))
+    return ValueTy == Ty && MPT->isFunctionPointer();
+  return Ty->isComplex() || Ty->isVector() || isAggregateTypeForABI(Ty);
+}
+
+bool SystemZTargetInfo::isVectorArgumentType(const Type *Ty) const {
+  const auto *VT = dyn_cast<VectorType>(Ty);
+  return Opts.HasVector && VT && VT->isFixedLength() &&
+         VT->getABISizeInBits() <= 128;
+}
+
+const Type *SystemZTargetInfo::getFPArgumentType(const Type *Ty,
+                                                 uint64_t Size) const {
+  if (Opts.IsSoftFloatABI)
+    return nullptr;
+
+  const auto *FT = dyn_cast<FloatType>(Ty);
+  if (!FT)
+    return nullptr;
+
+  // An over-aligned single-element struct uses the FP type matching its size.
+  if (FT->getSemantics() == &APFloat::IEEEhalf()) {
+    if (Size == 16)
+      return TB.getFloatType(APFloat::IEEEhalf(), Align(2));
+    if (Size == 32)
+      return TB.getFloatType(APFloat::IEEEsingle(), Align(4));
+    return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
+  }
+  if (FT->getSemantics() == &APFloat::IEEEsingle()) {
+    if (Size == 32)
+      return TB.getFloatType(APFloat::IEEEsingle(), Align(4));
+    return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
+  }
+  if (FT->getSemantics() == &APFloat::IEEEdouble())
+    return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
+  return nullptr;
+}
+
+const Type *SystemZTargetInfo::getSingleElementType(const Type *Ty) const {
+  const auto *RT = dyn_cast<RecordType>(Ty);
+  if (!RT || RT->isUnion())
+    return Ty;
+
+  // The shared isSingleElementStruct helper differs: it unwraps arrays,
+  // ignores empty fields, and rejects trailing padding, which SystemZ allows.
+  const Type *Found = nullptr;
+
+  // Check the bases first. Empty bases don't affect things either way.
+  for (ArrayRef<FieldInfo> Bases :
+       {RT->getBaseClasses(), RT->getVirtualBaseClasses()}) {
+    for (const FieldInfo &Base : Bases) {
+      if (Base.FieldType->isEmptyRecord())
+        continue;
+      if (Found)
+        return Ty;
+      Found = getSingleElementType(Base.FieldType);
+    }
+  }
+
+  for (const FieldInfo &Field : RT->getFields()) {
+    // Like isSingleElementRecord(), ignore C++20 empty data members.
+    if (Field.HasNoUniqueAddress && Field.FieldType->isEmptyRecord())
+      continue;
+    // Empty fields, array fields, and anonymous bitfields count as fields.
+    if (Found)
+      return Ty;
+    Found = getSingleElementType(Field.FieldType);
+  }
+  return Found ? Found : Ty;
+}
+
+ArgInfo SystemZTargetInfo::classifyReturnType(const Type *RetTy) const {
+  if (RetTy->isVoid())
+    return ArgInfo::getIgnore();
+  if (isVectorArgumentType(RetTy))
+    return ArgInfo::getDirect();
+  if (isCompoundType(RetTy) || RetTy->getABISizeInBits() > 64)
+    return getNaturalAlignIndirect(RetTy, getAllocaAddrSpace());
+  return isPromotableIntegerTypeForABI(RetTy) ? ArgInfo::getExtend(RetTy)
+                                              : ArgInfo::getDirect();
+}
+
+ArgInfo SystemZTargetInfo::classifyArgumentType(const Type *Ty) const {
+  Ty = useFirstFieldIfTransparentUnion(Ty);
+
+  if (RecordArgABI RAA = getRecordArgABI(Ty))
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(),
+                                   RAA == RAA_DirectInMemory);
+
+  if (isPromotableIntegerTypeForABI(Ty))
+    return ArgInfo::getExtend(Ty);
+
+  uint64_t Size = Ty->getABISizeInBits();
+  const Type *SingleElementTy = getSingleElementType(Ty);
+  // Vector-like records cannot have padding.
+  if (isVectorArgumentType(SingleElementTy) &&
+      SingleElementTy->getABISizeInBits() == Size)
+    return ArgInfo::getDirect(SingleElementTy);
+
+  if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(), /*ByVal=*/false);
+
+  if (const auto *RT = dyn_cast<RecordType>(Ty)) {
+    if (RT->hasFlexibleArrayMember())
+      return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(), /*ByVal=*/false);
+
+    if (const Type *FPArgTy = getFPArgumentType(SingleElementTy, Size))
+      return ArgInfo::getDirect(FPArgTy);
+
+    const Type *PassTy =
+        TB.getIntegerType(Size, Align(Size / 8), /*Signed=*/false);
+    if (Size <= 32) {
+      // Clang's getNoExtend: Extend with neither signext nor zeroext set.
+      return ArgInfo::getExtend(PassTy).setZeroExt(false);
+    }
+    return ArgInfo::getDirect(PassTy);
+  }
+
+  if (isCompoundType(Ty))
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(), /*ByVal=*/false);
+  return ArgInfo::getDirect();
+}
+
+class SystemZXPLinkTargetInfo : public TargetInfo {
+public:
+  SystemZXPLinkTargetInfo(TypeBuilder &TB, const SystemZABIOptions &Opts)
+      : TargetInfo(TB), Opts(Opts) {}
+
+  const ABICompatInfo &getABICompatInfo() const override {
+    return Opts.CompatInfo;
+  }
+
+  void computeInfo(FunctionInfo &FI) const override {
+    if (!maybeCommonClassifyReturnType(FI))
+      FI.getReturnInfo() =
+          classifyReturnType(FI.getReturnType(), FI.getCallingConvention());
+
+    unsigned NumRequiredArgs = FI.getNumRequiredArgs();
+    unsigned ArgNo = 0;
+    for (auto &I : FI.arguments()) {
+      bool IsNamedArg = ArgNo < NumRequiredArgs;
+      I.Info = classifyArgumentType(I.ABIType, IsNamedArg,
+                                    FI.getCallingConvention());
+      ++ArgNo;
+    }
+  }
+
+  Align getMaxIntegerAlign() const override { return Align(8); }
+
+private:
+  static constexpr unsigned GPRBits = 64;
+  SystemZABIOptions Opts;
+
+  bool isPromotableIntegerTypeForABI(const Type *Ty) const;
+  bool isCompoundType(const Type *Ty) const;
+  bool isVectorArgumentType(const Type *Ty) const;
+  const Type *getSingleElementType(const Type *Ty) const;
+  std::optional<const Type *> getFPTypeOfComplexLikeType(const Type *Ty) const;
+  ArgInfo classifyReturnType(const Type *RetTy, CallingConv::ID CallConv) const;
+  ArgInfo classifyArgumentType(const Type *Ty, bool IsNamedArg,
+                               CallingConv::ID CallConv) const;
+};
+
+bool SystemZXPLinkTargetInfo::isPromotableIntegerTypeForABI(
+    const Type *Ty) const {
+  const auto *IT = dyn_cast<IntegerType>(Ty);
+  if (!IT)
+    return false;
+  uint64_t Width = IT->getSizeInBits().getFixedValue();
+  // Besides everything narrower than 64 bits, XPLINK also extends long and
+  // unsigned long, but not long long.
+  return isPromotableInteger(IT) || Width < 64 || IT->isLong();
+}
+
+bool SystemZXPLinkTargetInfo::isCompoundType(const Type *Ty) const {
+  return Ty->isComplex() || isAggregateTypeForABI(Ty);
+}
+
+bool SystemZXPLinkTargetInfo::isVectorArgumentType(const Type *Ty) const {
+  const auto *VT = dyn_cast<VectorType>(Ty);
+  return Opts.HasVector && VT && VT->isFixedLength() &&
+         VT->getABISizeInBits() <= 128;
+}
+
+// Types are not uniqued, so two equal types can be distinct objects. This
+// plays the role of the canonical type comparison Clang uses. Records are
+// compared by identity.
+static bool isSameType(const Type *A, const Type *B) {
+  if (A == B)
+    return true;
+  if (A->getKind() != B->getKind())
+    return false;
+
+  switch (A->getKind()) {
+  case TypeKind::Void:
+    return true;
+  case TypeKind::Atomic:
+    return isSameType(cast<AtomicType>(A)->getValueType(),
+                      cast<AtomicType>(B)->getValueType());
+  case TypeKind::Complex:
+    return isSameType(cast<ComplexType>(A)->getElementType(),
+                      cast<ComplexType>(B)->getElementType());
+  case TypeKind::Integer: {
+    const auto *IA = cast<IntegerType>(A);
+    const auto *IB = cast<IntegerType>(B);
+    return IA->getSizeInBits() == IB->getSizeInBits() &&
+           IA->isSigned() == IB->isSigned() &&
+           IA->isBitInt() == IB->isBitInt() && IA->isLong() == IB->isLong();
+  }
+  case TypeKind::Float:
+    return cast<FloatType>(A)->getSemantics() ==
+           cast<FloatType>(B)->getSemantics();
+  case TypeKind::Pointer:
+    return cast<PointerType>(A)->getAddrSpace() ==
+               cast<PointerType>(B)->getAddrSpace() &&
+           A->getSizeInBits() == B->getSizeInBits();
+  case TypeKind::MemberPointer: {
+    const auto *MA = cast<MemberPointerType>(A);
+    const auto *MB = cast<MemberPointerType>(B);
+    return MA->isFunctionPointer() == MB->isFunctionPointer() &&
+           MA->getAddrSpace() == MB->getAddrSpace() &&
+           A->getSizeInBits() == B->getSizeInBits();
+  }
+  case TypeKind::Array: {
+    const auto *AA = cast<ArrayType>(A);
+    const auto *AB = cast<ArrayType>(B);
+    return AA->getNumElements() == AB->getNumElements() &&
+           AA->isMatrixType() == AB->isMatrixType() &&
+           isSameType(AA->getElementType(), AB->getElementType());
+  }
+  case TypeKind::Vector: {
+    const auto *VA = cast<VectorType>(A);
+    const auto *VB = cast<VectorType>(B);
+    return VA->getNumElements() == VB->getNumElements() &&
+           VA->getVectorKind() == VB->getVectorKind() &&
+           isSameType(VA->getElementType(), VB->getElementType());
+  }
+  case TypeKind::Tuple: {
+    const auto *TA = cast<TupleType>(A);
+    const auto *TB = cast<TupleType>(B);
+    return TA->getNumVectors() == TB->getNumVectors() &&
+           isSameType(TA->getVectorType(), TB->getVectorType());
+  }
+  case TypeKind::Record:
+    return false;
+  }
+  llvm_unreachable("unknown type kind");
+}
+
+const Type *
+SystemZXPLinkTargetInfo::getSingleElementType(const Type *Ty) const {
+  const auto *RT = dyn_cast<RecordType>(Ty);
+  if (!RT)
+    return Ty;
+
+  // Check if the union only consists of a single type, and return that type.
+  if (RT->isUnion()) {
+    const Type *Found = nullptr;
+    for (const FieldInfo &Field : RT->getFields()) {
+      const Type *FieldTy = getSingleElementType(Field.FieldType);
+      if (!Found)
+        Found = FieldTy;
+      else if (!isSameType(Found, FieldTy))
+        return Ty;
+    }
+    return Found ? Found : Ty;
+  }
+
+  const Type *Found = nullptr;
+
+  // Check the bases first. Empty bases don't affect things either way.
+  for (ArrayRef<FieldInfo> Bases :
+       {RT->getBaseClasses(), RT->getVirtualBaseClasses()}) {
+    for (const FieldInfo &Base : Bases) {
+      if (Base.FieldType->isEmptyRecord())
+        continue;
+      if (Found)
+        return Ty;
+      Found = getSingleElementType(Base.FieldType);
+    }
+  }
+
+  // Count every field, including empty [[no_unique_address]] members.
+  for (const FieldInfo &Field : RT->getFields()) {
+    if (Found)
+      return Ty;
+    Found = getSingleElementType(Field.FieldType);
+  }
+  return Found ? Found : Ty;
+}
+
+std::optional<const Type *>
+SystemZXPLinkTargetInfo::getFPTypeOfComplexLikeType(const Type *Ty) const {
+  const auto *RT = dyn_cast<RecordType>(Ty);
+  if (!RT || RT->isUnion())
+    return std::nullopt;
+
+  // Check for non-empty base classes.
+  for (ArrayRef<FieldInfo> Bases :
+       {RT->getBaseClasses(), RT->getVirtualBaseClasses()})
+    for (const FieldInfo &Base : Bases)
+      if (!Base.FieldType->isEmptyRecord())
+        return std::nullopt;
+
+  int Count = 0;
+  const FloatType *ElemFT = nullptr;
+  const Type *RetTy = nullptr;
+  for (const FieldInfo &Field : RT->getFields()) {
+    if (Count >= 2)
+      return std::nullopt;
+
+    const Type *SingleTy = getSingleElementType(Field.FieldType);
+    const auto *FT = dyn_cast<FloatType>(SingleTy);
+    if (!FT)
+      return std::nullopt;
+
+    // Only float, double and long double qualify, not half or bfloat.
+    const fltSemantics *Sem = FT->getSemantics();
+    if (Sem != &APFloat::IEEEsingle() && Sem != &APFloat::IEEEdouble() &&
+        Sem != &APFloat::IEEEquad())
+      return std::nullopt;
+
+    if (Count == 0) {
+      ElemFT = FT;
+      RetTy = SingleTy;
+    } else if (ElemFT->getSemantics() != FT->getSemantics()) {
+      return std::nullopt;
+    }
+    Count++;
+  }
+
+  if (Count == 2 && RetTy) {
+    if (Ty->getABISizeInBits() == 2 * RetTy->getABISizeInBits())
+      return RetTy;
+  }
+  return std::nullopt;
+}
+
+ArgInfo
+SystemZXPLinkTargetInfo::classifyReturnType(const Type *RetTy,
+                                            CallingConv::ID CallConv) const {
+  if (RetTy->isVoid())
+    return ArgInfo::getIgnore();
+
+  RetTy = useFirstFieldIfTransparentUnion(RetTy);
+
+  if (CallConv != CallingConv::C &&
+      (isAggregateTypeForABI(RetTy) || RetTy->isComplex()))
+    return getNaturalAlignIndirect(RetTy, getAllocaAddrSpace());
+
+  if (isVectorArgumentType(RetTy))
+    return ArgInfo::getDirect();
+
+  if (RetTy->isComplex())
+    return ArgInfo::getDirect();
+
+  if (isa<RecordType>(RetTy)) {
+    if (getFPTypeOfComplexLikeType(RetTy))
+      return ArgInfo::getDirect();
+  }
+
+  if (isAggregateTypeForABI(RetTy)) {
+    uint64_t AggregateTypeSize = RetTy->getABISizeInBits();
+    if (AggregateTypeSize <= 3 * GPRBits) {
+      uint64_t NumElements =
+          AggregateTypeSize / GPRBits + (AggregateTypeSize % GPRBits != 0);
+      const Type *CoerceTy =
+          TB.getIntegerType(GPRBits, Align(8), /*Signed=*/false);
+      CoerceTy = TB.getArrayType(CoerceTy, NumElements, NumElements * GPRBits);
+      return ArgInfo::getDirect(CoerceTy).setInReg();
+    }
+    return getNaturalAlignIndirect(RetTy, getAllocaAddrSpace());
+  }
+
+  return isPromotableIntegerTypeForABI(RetTy) ? ArgInfo::getExtend(RetTy)
+                                              : ArgInfo::getDirect();
+}
+
+ArgInfo
+SystemZXPLinkTargetInfo::classifyArgumentType(const Type *Ty, bool IsNamedArg,
+                                              CallingConv::ID CallConv) const {
+  Ty = useFirstFieldIfTransparentUnion(Ty);
+
+  if (RecordArgABI RAA = getRecordArgABI(Ty))
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(),
+                                   RAA == RAA_DirectInMemory);
+
+  if (isPromotableIntegerTypeForABI(Ty))
+    return ArgInfo::getExtend(Ty);
+
+  if (CallConv != CallingConv::C && isCompoundType(Ty))
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(), /*ByVal=*/false);
+
+  auto CompTy = getFPTypeOfComplexLikeType(Ty);
+  if (IsNamedArg) {
+    if (Ty->isComplex()) {
+      auto AI = ArgInfo::getDirect();
+      AI.setCanBeFlattened(false);
+      return AI;
+    }
+
+    if (CompTy.has_value()) {
+      const Type *CoerceTy =
+          getStructOfTypes({*CompTy, *CompTy}, /*Packed=*/false);
+      auto AI = ArgInfo::getDirect(CoerceTy);
+      AI.setCanBeFlattened(false);
+      return AI;
+    }
+  }
+
+  if (isVectorArgumentType(Ty))
+    return ArgInfo::getDirect();
+
+  if (isa<RecordType>(Ty) || Ty->isComplex() || CompTy.has_value()) {
+    uint64_t Bits = Ty->getABISizeInBits();
+    const Type *CoerceTy;
+    if (Bits <= GPRBits) {
+      CoerceTy = TB.getIntegerType(GPRBits, Align(8), /*Signed=*/false);
+    } else {
+      uint64_t NumRegs = llvm::alignTo(Bits, GPRBits) / GPRBits;
+      const Type *RegTy =
+          TB.getIntegerType(GPRBits, Align(8), /*Signed=*/false);
+      CoerceTy = TB.getArrayType(RegTy, NumRegs, NumRegs * GPRBits);
+    }
+    return ArgInfo::getDirect(CoerceTy);
+  }
+
+  if (isCompoundType(Ty))
+    return getNaturalAlignIndirect(Ty, getAllocaAddrSpace(), /*ByVal=*/false);
+
+  return ArgInfo::getDirect();
+}
+
+std::unique_ptr<TargetInfo>
+createSystemZTargetInfo(TypeBuilder &TB, const SystemZABIOptions &Opts) {
+  if (Opts.Kind == SystemZABIKind::XPLINK)
+    return std::make_unique<SystemZXPLinkTargetInfo>(TB, Opts);
+  return std::make_unique<SystemZTargetInfo>(TB, Opts);
+}
+
+} // namespace llvm::abi

>From b1283ea18ac853e7ff8af61666a92b92ba8194b0 Mon Sep 17 00:00:00 2001
From: denniswang <denniswang812 at gmail.com>
Date: Tue, 24 Nov 2026 13:59:27 -0800
Subject: [PATCH 2/2] format + tests

---
 llvm/include/llvm/ABI/FunctionInfo.h         |   3 +-
 llvm/unittests/ABI/CMakeLists.txt            |   1 +
 llvm/unittests/ABI/SystemZTargetInfoTest.cpp | 425 +++++++++++++++++++
 3 files changed, 427 insertions(+), 2 deletions(-)
 create mode 100644 llvm/unittests/ABI/SystemZTargetInfoTest.cpp

diff --git a/llvm/include/llvm/ABI/FunctionInfo.h b/llvm/include/llvm/ABI/FunctionInfo.h
index aa1fc3dea66f7d..15a2b027fc8895 100644
--- a/llvm/include/llvm/ABI/FunctionInfo.h
+++ b/llvm/include/llvm/ABI/FunctionInfo.h
@@ -89,8 +89,7 @@ class ArgInfo {
   ArgInfo(Kind K = Direct)
       : TheKind(K), SignExt(false), ZeroExt(false), Conservative(false),
         IndirectByVal(false), IndirectRealign(false), CanBeFlattened(false),
-        InReg(false),
-        NeededIntRegs(0), NeededSseRegs(0) {}
+        InReg(false), NeededIntRegs(0), NeededSseRegs(0) {}
 
 public:
   /// \param T The type to coerce to. If null, the argument's original type is
diff --git a/llvm/unittests/ABI/CMakeLists.txt b/llvm/unittests/ABI/CMakeLists.txt
index 573abcbd01310b..0a7f6e598b4d0a 100644
--- a/llvm/unittests/ABI/CMakeLists.txt
+++ b/llvm/unittests/ABI/CMakeLists.txt
@@ -6,6 +6,7 @@ set(LLVM_LINK_COMPONENTS
 
 add_llvm_unittest(ABITests
   AArch64TargetInfoTest.cpp
+  SystemZTargetInfoTest.cpp
   IRTypeMapperTest.cpp
   FunctionInfoTest.cpp
   TargetInfoTest.cpp
diff --git a/llvm/unittests/ABI/SystemZTargetInfoTest.cpp b/llvm/unittests/ABI/SystemZTargetInfoTest.cpp
new file mode 100644
index 00000000000000..1f72a3a84e4cdb
--- /dev/null
+++ b/llvm/unittests/ABI/SystemZTargetInfoTest.cpp
@@ -0,0 +1,425 @@
+//===- SystemZTargetInfoTest.cpp - SystemZ ABI unit tests
+//------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/ABI/FunctionInfo.h"
+#include "llvm/ABI/TargetInfo.h"
+#include "llvm/ABI/Types.h"
+#include "llvm/ADT/APFloat.h"
+#include "llvm/Support/Allocator.h"
+#include "gtest/gtest.h"
+
+namespace {
+
+using namespace llvm;
+using ABIType = llvm::abi::Type;
+using namespace llvm::abi;
+
+class SystemZTargetInfoTest : public ::testing::Test {
+protected:
+  BumpPtrAllocator Alloc;
+  TypeBuilder TB{Alloc};
+  const ABIType *I8 = TB.getIntegerType(8, Align(1), true);
+  const ABIType *I32 = TB.getIntegerType(32, Align(4), true);
+  const ABIType *I64 = TB.getIntegerType(64, Align(8), true);
+  const ABIType *F16 = TB.getFloatType(APFloat::IEEEhalf(), Align(2));
+  const ABIType *F32 = TB.getFloatType(APFloat::IEEEsingle(), Align(4));
+  const ABIType *F64 = TB.getFloatType(APFloat::IEEEdouble(), Align(8));
+
+  const ABIType *record(ArrayRef<FieldInfo> Fields, uint64_t Size,
+                        Align Alignment,
+                        RecordFlags Flags = RecordFlags::CanPassInRegisters,
+                        ArrayRef<FieldInfo> Bases = {}) {
+    return TB.getRecordType(Fields, TypeSize::getFixed(Size), Alignment,
+                            Alignment, StructPacking::Default, Bases, {},
+                            Flags);
+  }
+
+  std::unique_ptr<FunctionInfo> classify(const ABIType *Ty,
+                                         SystemZABIOptions Opts = {}) {
+    auto FI = FunctionInfo::create(CallingConv::C, Ty, {Ty});
+    createSystemZTargetInfo(TB, Opts)->computeInfo(*FI);
+    return FI;
+  }
+
+  void expectIndirect(const ArgInfo &Info, Align Alignment, bool ByVal) {
+    ASSERT_TRUE(Info.isIndirect());
+    EXPECT_EQ(Info.getIndirectAlign(), Alignment);
+    EXPECT_EQ(Info.getIndirectByVal(), ByVal);
+    EXPECT_EQ(Info.getIndirectAddrSpace(), 0u);
+  }
+
+  void expectFloatCoercion(const ArgInfo &Info, const fltSemantics *Semantics) {
+    ASSERT_TRUE(Info.isDirect());
+    const auto *FT =
+        dyn_cast_or_null<llvm::abi::FloatType>(Info.getCoerceToType());
+    ASSERT_NE(FT, nullptr);
+    EXPECT_EQ(FT->getSemantics(), Semantics);
+  }
+
+  void expectIntegerCoercion(const ArgInfo &Info, unsigned Width, bool NoExt) {
+    if (NoExt) {
+      ASSERT_TRUE(Info.isExtend());
+      EXPECT_TRUE(Info.isNoExt());
+    } else {
+      ASSERT_TRUE(Info.isDirect());
+    }
+    const auto *IT =
+        dyn_cast_or_null<llvm::abi::IntegerType>(Info.getCoerceToType());
+    ASSERT_NE(IT, nullptr);
+    EXPECT_EQ(IT->getSizeInBits().getFixedValue(), Width);
+  }
+};
+
+// Cases mirror the signatures in Clang's CodeGen/SystemZ/systemz-abi*.c tests.
+TEST_F(SystemZTargetInfoTest, VoidReturn) {
+  auto FI = FunctionInfo::create(CallingConv::C, TB.getVoidType(), {});
+  createSystemZTargetInfo(TB, {})->computeInfo(*FI);
+  EXPECT_TRUE(FI->getReturnInfo().isIgnore());
+}
+
+TEST_F(SystemZTargetInfoTest, IntegerExtensionAndBitIntBoundary) {
+  for (unsigned Width : {1u, 8u, 16u, 32u, 33u, 63u, 64u}) {
+    for (bool Signed : {false, true}) {
+      for (bool BitInt : {false, true}) {
+        if (!BitInt && Width > 32 && Width < 64)
+          continue;
+        const ABIType *Ty = TB.getIntegerType(Width, Align(8), Signed, BitInt);
+        auto FI = classify(Ty);
+        for (const ArgInfo *Info :
+             {&FI->getReturnInfo(), &FI->getArgInfo(0).Info}) {
+          if (Width == 64) {
+            EXPECT_TRUE(Info->isDirect());
+            continue;
+          }
+          ASSERT_TRUE(Info->isExtend());
+          EXPECT_EQ(Info->isSignExt(), Signed);
+          EXPECT_EQ(Info->isZeroExt(), !Signed);
+          EXPECT_EQ(Info->getCoerceToType(), Ty);
+        }
+      }
+    }
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, ScalarsAndWideValues) {
+  for (const ABIType *Ty :
+       {I64, F16, F32, F64,
+        static_cast<const ABIType *>(TB.getPointerType(64, Align(8)))}) {
+    auto FI = classify(Ty);
+    EXPECT_TRUE(FI->getReturnInfo().isDirect());
+    EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+  }
+  for (const ABIType *Ty :
+       {static_cast<const ABIType *>(TB.getIntegerType(128, Align(8), true)),
+        static_cast<const ABIType *>(
+            TB.getIntegerType(65, Align(8), true, true)),
+        static_cast<const ABIType *>(
+            TB.getFloatType(APFloat::IEEEquad(), Align(8))),
+        static_cast<const ABIType *>(TB.getComplexType(F32, Align(4)))}) {
+    auto FI = classify(Ty);
+    expectIndirect(FI->getReturnInfo(), Ty->getAlignment(), true);
+    expectIndirect(FI->getArgInfo(0).Info, Ty->getAlignment(), false);
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, MemberPointers) {
+  const ABIType *DataMember = TB.getMemberPointerType(false, 64, Align(8));
+  auto FI = classify(DataMember);
+  EXPECT_TRUE(FI->getReturnInfo().isDirect());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+
+  FI = classify(TB.getAtomicType(DataMember, 64, Align(8)));
+  EXPECT_TRUE(FI->getReturnInfo().isDirect());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+
+  FI = classify(TB.getMemberPointerType(true, 128, Align(8)));
+  expectIndirect(FI->getReturnInfo(), Align(8), true);
+  expectIndirect(FI->getArgInfo(0).Info, Align(8), false);
+}
+
+TEST_F(SystemZTargetInfoTest, RecordSizeAndNoExt) {
+  for (unsigned Bytes : {0u, 1u, 2u, 3u, 4u, 8u, 9u}) {
+    SCOPED_TRACE(Bytes);
+    auto *Array = TB.getArrayType(I8, Bytes, Bytes * 8);
+    const ABIType *Ty = record({FieldInfo(Array)}, Bytes * 8, Align(1));
+    auto FI = classify(Ty);
+    expectIndirect(FI->getReturnInfo(), Align(1), true);
+    if (Bytes == 1 || Bytes == 2 || Bytes == 4 || Bytes == 8)
+      expectIntegerCoercion(FI->getArgInfo(0).Info, Bytes * 8, Bytes <= 4);
+    else
+      expectIndirect(FI->getArgInfo(0).Info, Align(1), false);
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, FloatRecordsAndSoftFloat) {
+  for (const ABIType *Elt : {F16, F32, F64}) {
+    unsigned Size = Elt->getABISizeInBits();
+    const ABIType *Ty = record({FieldInfo(Elt)}, Size, Elt->getAlignment());
+    auto FI = classify(Ty);
+    ASSERT_TRUE(FI->getArgInfo(0).Info.isDirect());
+    const auto *FT = dyn_cast<llvm::abi::FloatType>(
+        FI->getArgInfo(0).Info.getCoerceToType());
+    ASSERT_NE(FT, nullptr);
+    EXPECT_EQ(FT->getSemantics(),
+              cast<llvm::abi::FloatType>(Elt)->getSemantics());
+    expectIndirect(FI->getReturnInfo(), Elt->getAlignment(), true);
+
+    SystemZABIOptions Soft;
+    Soft.IsSoftFloatABI = true;
+    auto SoftFI = classify(Ty, Soft);
+    expectIntegerCoercion(SoftFI->getArgInfo(0).Info, Size, Size <= 32);
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, NestedAndPaddedFloatRecords) {
+  for (const ABIType *Elt : {F16, F32}) {
+    const ABIType *Inner =
+        record({FieldInfo(Elt)}, Elt->getABISizeInBits(), Elt->getAlignment());
+    for (unsigned Size : {32u, 64u}) {
+      const ABIType *Ty = record({FieldInfo(Inner)}, Size, Align(Size / 8));
+      auto FI = classify(Ty);
+      ASSERT_TRUE(FI->getArgInfo(0).Info.isDirect());
+      const auto *FT = dyn_cast<llvm::abi::FloatType>(
+          FI->getArgInfo(0).Info.getCoerceToType());
+      ASSERT_NE(FT, nullptr);
+      EXPECT_EQ(FT->getSemantics(),
+                Size == 32 ? &APFloat::IEEEsingle() : &APFloat::IEEEdouble());
+    }
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, ArraysUnionsAndEmptyFieldsDoNotReduceToFloat) {
+  const ABIType *Array = TB.getArrayType(F32, 1, 32);
+  const ABIType *Empty = record({}, 0, Align(1));
+  for (const ABIType *Ty :
+       {record({FieldInfo(Array)}, 32, Align(4)),
+        record({FieldInfo(F32)}, 32, Align(4),
+               RecordFlags::CanPassInRegisters | RecordFlags::IsUnion),
+        record({FieldInfo(Empty), FieldInfo(F32)}, 32, Align(4)),
+        record({FieldInfo(I32, 0, true, 1, true), FieldInfo(F32)}, 64,
+               Align(4))}) {
+    auto FI = classify(Ty);
+    unsigned Size = Ty->getABISizeInBits();
+    expectIntegerCoercion(FI->getArgInfo(0).Info, Size, Size <= 32);
+  }
+}
+
+TEST_F(SystemZTargetInfoTest, FlexibleArraysAndNontrivialRecords) {
+  const ABIType *Flexible = record({FieldInfo(I64)}, 64, Align(8),
+                                   RecordFlags::CanPassInRegisters |
+                                       RecordFlags::HasFlexibleArrayMember);
+  auto FI = classify(Flexible);
+  expectIndirect(FI->getArgInfo(0).Info, Align(8), false);
+
+  const ABIType *Nontrivial =
+      record({FieldInfo(F32)}, 32, Align(4), RecordFlags::IsCXXRecord);
+  FI = classify(Nontrivial);
+  expectIndirect(FI->getReturnInfo(), Align(4), false);
+  expectIndirect(FI->getArgInfo(0).Info, Align(4), false);
+}
+
+TEST_F(SystemZTargetInfoTest, TransparentUnionUsesFirstField) {
+  const ABIType *Ty =
+      record({FieldInfo(I32), FieldInfo(F32)}, 32, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsUnion |
+                 RecordFlags::IsTransparent);
+  auto FI = classify(Ty);
+  ASSERT_TRUE(FI->getArgInfo(0).Info.isExtend());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isSignExt());
+  EXPECT_EQ(FI->getArgInfo(0).Info.getCoerceToType(), I32);
+  expectIndirect(FI->getReturnInfo(), Align(4), true);
+}
+
+TEST_F(SystemZTargetInfoTest, VectorFacilityAndRecordPadding) {
+  for (unsigned Bytes : {1u, 8u, 16u, 32u}) {
+    const ABIType *Vec =
+        TB.getVectorType(I8, ElementCount::getFixed(Bytes), Align(8));
+    for (bool HasVector : {false, true}) {
+      SystemZABIOptions Opts;
+      Opts.HasVector = HasVector;
+      auto FI = classify(Vec, Opts);
+      if (HasVector && Bytes <= 16) {
+        EXPECT_TRUE(FI->getReturnInfo().isDirect());
+        EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+        EXPECT_EQ(FI->getArgInfo(0).Info.getCoerceToType(), Vec);
+      } else {
+        expectIndirect(FI->getReturnInfo(), Align(8), true);
+        expectIndirect(FI->getArgInfo(0).Info, Align(8), false);
+      }
+    }
+  }
+
+  const ABIType *Vec =
+      TB.getVectorType(I8, ElementCount::getFixed(8), Align(8));
+  SystemZABIOptions Opts;
+  Opts.HasVector = true;
+  auto FI = classify(record({FieldInfo(Vec)}, 64, Align(8)), Opts);
+  ASSERT_TRUE(FI->getArgInfo(0).Info.isDirect());
+  EXPECT_EQ(FI->getArgInfo(0).Info.getCoerceToType(), Vec);
+  expectIndirect(FI->getReturnInfo(), Align(8), true);
+  FI = classify(record({FieldInfo(Vec)}, 128, Align(8)), Opts);
+  expectIndirect(FI->getArgInfo(0).Info, Align(8), false);
+}
+
+TEST_F(SystemZTargetInfoTest, VariadicClassification) {
+  const ABIType *Vec =
+      TB.getVectorType(I8, ElementCount::getFixed(16), Align(8));
+  auto FI =
+      FunctionInfo::create(CallingConv::C, I32, {I32, Vec}, RequiredArgs(1));
+  SystemZABIOptions Opts;
+  Opts.HasVector = true;
+  createSystemZTargetInfo(TB, Opts)->computeInfo(*FI);
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isExtend());
+  EXPECT_TRUE(FI->getArgInfo(1).Info.isDirect());
+}
+
+TEST_F(SystemZTargetInfoTest, XPLINKClassification) {
+  SystemZABIOptions Opts;
+  Opts.Kind = SystemZABIKind::XPLINK;
+
+  // Scalar integers are extended.
+  auto FI = classify(I32, Opts);
+  EXPECT_TRUE(FI->getReturnInfo().isExtend());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isExtend());
+
+  // Floats are direct.
+  FI = classify(F64, Opts);
+  EXPECT_TRUE(FI->getReturnInfo().isDirect());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+
+  // Aggregate <= 24 bytes (3 GPRs) is coerced to array of i64 on return.
+  const ABIType *SmallRec =
+      record({FieldInfo(I32), FieldInfo(I32)}, 64, Align(8));
+  FI = classify(SmallRec, Opts);
+  EXPECT_TRUE(FI->getReturnInfo().isDirect());
+  ASSERT_TRUE(FI->getReturnInfo().getCoerceToType());
+  EXPECT_TRUE(FI->getReturnInfo().getCoerceToType()->isArray());
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+}
+
+TEST_F(SystemZTargetInfoTest, SingleElementSkipsEmptyBaseAndMember) {
+  const ABIType *Empty = record({}, 8, Align(1));
+
+  // An empty base does not stop the struct from being a single float.
+  const ABIType *WithBase =
+      record({FieldInfo(F32)}, 32, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsCXXRecord,
+             {FieldInfo(Empty)});
+  auto FI = classify(WithBase);
+  ASSERT_TRUE(FI->getArgInfo(0).Info.isDirect());
+  expectFloatCoercion(FI->getArgInfo(0).Info, &APFloat::IEEEsingle());
+
+  // An empty [[no_unique_address]] member is ignored.
+  const ABIType *WithEmptyMember =
+      record({FieldInfo(Empty, 0, false, 0, false, true), FieldInfo(F32)}, 32,
+             Align(4));
+  FI = classify(WithEmptyMember);
+  ASSERT_TRUE(FI->getArgInfo(0).Info.isDirect());
+  expectFloatCoercion(FI->getArgInfo(0).Info, &APFloat::IEEEsingle());
+
+  // A non-empty base plus a field is not a single element.
+  const ABIType *TwoElements =
+      record({FieldInfo(F32)}, 64, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsCXXRecord,
+             {FieldInfo(record({FieldInfo(F32)}, 32, Align(4)))});
+  FI = classify(TwoElements);
+  expectIntegerCoercion(FI->getArgInfo(0).Info, 64, false);
+}
+
+TEST_F(SystemZTargetInfoTest, XPLINKComplexLikeStructs) {
+  SystemZABIOptions Opts;
+  Opts.Kind = SystemZABIKind::XPLINK;
+  const ABIType *Empty = record({}, 8, Align(1));
+  auto IsCoercedToRecord = [&](const ABIType *Ty) {
+    auto FI = classify(Ty, Opts);
+    const ArgInfo &Info = FI->getArgInfo(0).Info;
+    return Info.isDirect() &&
+           isa_and_nonnull<llvm::abi::RecordType>(Info.getCoerceToType());
+  };
+
+  // Two floats are complex-like.
+  EXPECT_TRUE(IsCoercedToRecord(
+      record({FieldInfo(F32), FieldInfo(F32)}, 64, Align(4))));
+
+  // An empty base does not stop it from being complex-like.
+  EXPECT_TRUE(IsCoercedToRecord(
+      record({FieldInfo(F32), FieldInfo(F32)}, 64, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsCXXRecord,
+             {FieldInfo(Empty)})));
+
+  // A non-empty base does.
+  EXPECT_FALSE(IsCoercedToRecord(
+      record({FieldInfo(F32), FieldInfo(F32)}, 96, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsCXXRecord,
+             {FieldInfo(record({FieldInfo(F32)}, 32, Align(4)))})));
+
+  // Half precision floats are not complex-like.
+  EXPECT_FALSE(IsCoercedToRecord(
+      record({FieldInfo(F16), FieldInfo(F16)}, 32, Align(2))));
+}
+
+TEST_F(SystemZTargetInfoTest, XPLINKExtendsLongButNotLongLong) {
+  SystemZABIOptions Opts;
+  Opts.Kind = SystemZABIKind::XPLINK;
+  const ABIType *Long = TB.getIntegerType(64, Align(8), /*Signed=*/true,
+                                          /*IsBitInt=*/false, /*IsLong=*/true);
+
+  // long is extended, long long is passed directly.
+  auto FI = classify(Long, Opts);
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isExtend());
+  EXPECT_TRUE(FI->getReturnInfo().isExtend());
+  FI = classify(I64, Opts);
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+  EXPECT_TRUE(FI->getReturnInfo().isDirect());
+
+  // The ELF ABI extends neither.
+  FI = classify(Long);
+  EXPECT_TRUE(FI->getArgInfo(0).Info.isDirect());
+}
+
+TEST_F(SystemZTargetInfoTest, XPLINKAggregateReturnIsInReg) {
+  SystemZABIOptions Opts;
+  Opts.Kind = SystemZABIKind::XPLINK;
+  const ABIType *Rec = record({FieldInfo(I32), FieldInfo(I32)}, 64, Align(8));
+  auto FI = classify(Rec, Opts);
+  ASSERT_TRUE(FI->getReturnInfo().isDirect());
+  EXPECT_TRUE(FI->getReturnInfo().getInReg());
+  // Arguments are not marked inreg.
+  EXPECT_FALSE(FI->getArgInfo(0).Info.getInReg());
+}
+
+TEST_F(SystemZTargetInfoTest, XPLINKSingleElementUnions) {
+  SystemZABIOptions Opts;
+  Opts.Kind = SystemZABIKind::XPLINK;
+  const ABIType *F32Again = TB.getFloatType(APFloat::IEEEsingle(), Align(4));
+
+  // union { float a, b; } behaves like a float, so a struct of two of them is
+  // complex-like and is passed as a struct of two floats.
+  const ABIType *SameUnion =
+      record({FieldInfo(F32), FieldInfo(F32Again)}, 32, Align(4),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsUnion);
+  const ABIType *Pair =
+      record({FieldInfo(SameUnion), FieldInfo(SameUnion)}, 64, Align(4));
+  auto FI = classify(Pair, Opts);
+  const ArgInfo &Info = FI->getArgInfo(0).Info;
+  ASSERT_TRUE(Info.isDirect());
+  EXPECT_TRUE(isa<llvm::abi::RecordType>(Info.getCoerceToType()));
+
+  // union { float a; double b; } has two different types, so it stays a union.
+  const ABIType *MixedUnion =
+      record({FieldInfo(F32), FieldInfo(F64)}, 64, Align(8),
+             RecordFlags::CanPassInRegisters | RecordFlags::IsUnion);
+  const ABIType *MixedPair =
+      record({FieldInfo(MixedUnion), FieldInfo(MixedUnion)}, 128, Align(8));
+  FI = classify(MixedPair, Opts);
+  EXPECT_FALSE(isa_and_nonnull<llvm::abi::RecordType>(
+      FI->getArgInfo(0).Info.getCoerceToType()));
+}
+
+} // namespace



More information about the cfe-commits mailing list