Author: Andy Kaylor Date: 2026-11-17T14:27:38-08:00 New Revision: bf719cf852f8f0ea9c2e412072577990b0cb50c0
URL: https://github.com/llvm/llvm-project/commit/bf719cf852f8f0ea9c2e412072577990b0cb50c0 DIFF: https://github.com/llvm/llvm-project/commit/bf719cf852f8f0ea9c2e412072577990b0cb50c0.diff LOG: [CIR] Separate language alignment from ABI alignment (#243165) CIR's use and backing implementation of mlir::DataLayout::getTypeABIAlignment conflated two similar but distinct concepts. One thing this can refer to is the alignment that will be assumed for the type when it is lowered to LLVM IR. This determines array stride and field offsets, padding, and packing for records. The other possible meaning is the alignment the source language requires for objects of the type on the target platfrom. This determines alignment of allocas, globals, and memory accesses and is also used in calling convention lowering. These two alignments usually agree, but not always. This change introduces a new method, getTypeLanguageAlignment, in CIRDataLayout and uses that method when the source language alignment is needed. This does not yet correctly handle the AArch64 vector alignment issue, as the needed infrastructure for that was being introduced in another PR when the problem I'm fixing here came up during the review. Assisted-by: Cursor / claude-opus-5.5 Added: Modified: clang/include/clang/CIR/Dialect/IR/CIRAttrs.td clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h clang/include/clang/CIR/Dialect/IR/CIRTypes.td clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp clang/lib/CIR/Dialect/IR/CIRTypes.cpp clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.cpp clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.h clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp clang/test/CIR/CodeGen/agg-init-constexpr.cpp clang/test/CIR/CodeGen/bitint-max-align.c clang/test/CIR/CodeGen/bitint-record-layout.c clang/test/CIR/Transforms/abi-lowering/x86_64-struct-padded.cir clang/test/CIR/Transforms/abi-lowering/x86_64-union.cir clang/unittests/CIR/IntTypeABIAlignTest.cpp Removed: ################################################################################ diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td index d9aecbaecda48..ce544bcdb157d 100644 --- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td +++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td @@ -1573,9 +1573,11 @@ def CIR_PtrSpecAttr : CIR_Attr<"PtrSpec", "ptr_spec"> { def CIR_BitIntSpecAttr : CIR_Attr<"BitIntSpec", "bitint_spec"> { let summary = "!cir.int _BitInt data layout spec"; let description = [{ - Upper bound, in bits, on the ABI alignment of a `_BitInt`. This is - `TargetInfo::getBitIntMaxAlign()`. `_BitInt(N)` is aligned to - `min(PowerOf2Ceil(N), max_align)` bits, and at least one byte. + Upper bound, in bits, on the language alignment of a `_BitInt`. This is + `TargetInfo::getBitIntMaxAlign()`. The language alignment of `_BitInt(N)` + is `min(PowerOf2Ceil(N), max_align)` bits, and at least one byte. The cap + does not apply to the `_BitInt`'s ABI alignment, which is the alignment + of the integer that holds it, or 1 when it is held as bytes. Used as the value of the `!cir.int<u, 1, bitint>`-keyed data-layout entry. The key names the `_BitInt` class. Its width is not a layout diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h b/clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h index 9eca9450a5d97..0e66f19292158 100644 --- a/clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h +++ b/clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h @@ -27,6 +27,13 @@ class CIRDataLayout { unsigned programAddrSpace = 0; + /// TargetInfo::getBitIntMaxAlign(), in bits, from the module's + /// #cir.bitint_spec entry. + uint64_t bitIntMaxAlignBits = 0; + + /// The module whose cir.record_layouts entries give record alignments. + mlir::ModuleOp module; + public: mlir::DataLayout layout; @@ -47,6 +54,13 @@ class CIRDataLayout { return getAlignment(ty, true); } + /// Returns the alignment, in bytes, that the source language requires for + /// an object of type \p ty. ABI classification, coercion temporaries, and + /// accesses with no explicit alignment use it. The ABI alignment of \p ty is + /// the alignment of the memory representation \p ty lowers to, which record + /// layout and array strides use. + uint64_t getTypeLanguageAlignment(mlir::Type ty) const; + /// Returns the maximum number of bytes that may be overwritten by /// storing the specified type. /// diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td index ee153ce051e33..8623803a21d3d 100644 --- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td +++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td @@ -97,6 +97,15 @@ def CIR_IntType : CIR_Type<"Int", "int", [ return get(ctx, /*width=*/1, /*isSigned=*/false, /*isBitInt=*/true); } + /// The _BitInt alignment cap, in bits, held by the #cir.bitint_spec entry + /// in \p params, or the default cap when there is no entry. + static uint64_t + getBitIntMaxAlignBits(mlir::DataLayoutEntryListRef params); + + /// The alignment, in bytes, that C requires of this _BitInt when the + /// target caps _BitInt alignment at \p maxAlignBits bits. + uint64_t getBitIntAlignRequirement(uint64_t maxAlignBits) const; + /// Returns a minimum bitwidth of cir::IntType static unsigned minBitwidth() { return 1; } /// Returns a maximum bitwidth of cir::IntType. diff --git a/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp b/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp index 3552f76c7ef44..88e5f5e42162e 100644 --- a/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp @@ -147,24 +147,10 @@ struct CIRRecordLowering final { return CharUnits::fromQuantity(dataLayout.layout.getTypeSizeInBits(ty)); } - CharUnits getMemberAlignment(mlir::Type Ty) { - // An access unit takes the alignment of its storage type. A zero-width - // bit-field has no storage and so imposes no alignment. - if (auto bitFieldTy = mlir::dyn_cast<cir::BitFieldType>(Ty)) { - if (mlir::Type storage = bitFieldTy.getStorageType()) - return getMemberAlignment(storage); - return CharUnits::One(); - } - // Recurse on Arrays, they have the member alignment of their element type. - if (auto arrayTy = mlir::dyn_cast<cir::ArrayType>(Ty)) - return getMemberAlignment(arrayTy.getElementType()); - // Int types (_BitInt in particular) share the alignment of their storage - // type. - if (auto intTy = mlir::dyn_cast<cir::IntType>(Ty)) - return CharUnits::fromQuantity( - intTy.getStorageTypeAlignment(dataLayout.layout)); - - return CharUnits::fromQuantity(dataLayout.layout.getTypeABIAlignment(Ty)); + /// The record is marked packed when a member's offset is not a multiple of + /// this alignment. + CharUnits getMemberAlignment(mlir::Type ty) { + return CharUnits::fromQuantity(dataLayout.layout.getTypeABIAlignment(ty)); } bool isZeroInitializable(const FieldDecl *fd) { diff --git a/clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp b/clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp index 2347edcfee161..08b2efcac4ef0 100644 --- a/clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp +++ b/clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp @@ -1,6 +1,8 @@ #include "clang/CIR/Dialect/IR/CIRDataLayout.h" +#include "clang/CIR/Dialect/IR/CIRDialect.h" #include "clang/CIR/Dialect/IR/CIRTypes.h" #include "clang/CIR/MissingFeatures.h" +#include "llvm/ADT/TypeSwitch.h" using namespace cir; @@ -8,13 +10,18 @@ using namespace cir; // DataLayout Class Implementation //===----------------------------------------------------------------------===// -CIRDataLayout::CIRDataLayout(mlir::ModuleOp modOp) : layout(modOp) { +CIRDataLayout::CIRDataLayout(mlir::ModuleOp modOp) + : module(modOp), layout(modOp) { reset(modOp.getDataLayoutSpec()); } void CIRDataLayout::reset(mlir::DataLayoutSpecInterface spec) { bigEndian = false; + bitIntMaxAlignBits = cir::IntType::getBitIntMaxAlignBits({}); if (spec) { + bitIntMaxAlignBits = cir::IntType::getBitIntMaxAlignBits( + spec.getSpecForType(cir::IntType::getTypeID())); + mlir::StringAttr key = mlir::StringAttr::get( spec.getContext(), mlir::DLTIDialect::kDataLayoutEndiannessKey); if (mlir::DataLayoutEntryInterface entry = spec.getSpecForIdentifier(key)) @@ -41,6 +48,41 @@ llvm::Align CIRDataLayout::getAlignment(mlir::Type ty, bool useABIAlign) const { return llvm::Align(align); } +uint64_t CIRDataLayout::getTypeLanguageAlignment(mlir::Type ty) const { + auto maxMemberAlignment = [&](llvm::ArrayRef<mlir::Type> members) { + uint64_t align = 1; + for (mlir::Type member : members) + align = std::max(align, getTypeLanguageAlignment(member)); + return align; + }; + return llvm::TypeSwitch<mlir::Type, uint64_t>(ty) + .Case([&](cir::IntType intTy) -> uint64_t { + if (intTy.isBitInt()) + return intTy.getBitIntAlignRequirement(bitIntMaxAlignBits); + return layout.getTypeABIAlignment(intTy); + }) + .Case([&](cir::RecordType recTy) -> uint64_t { + if (cir::RecordLayoutAttr recLayout = + cir::tryGetRecordLayout(module, recTy.getName())) + return recLayout.getRecordAlign(); + // A record without a layout entry, such as one in hand-written CIR. + assert(recTy.isComplete() && "Cannot get layout of incomplete records"); + if (recTy.getPacked()) + return 1; + return maxMemberAlignment(recTy.getMembers()); + }) + .Case<cir::ArrayType, cir::ComplexType, cir::MatrixType>( + [&](auto elementsTy) -> uint64_t { + return getTypeLanguageAlignment(elementsTy.getElementType()); + }) + .Case([&](cir::BitFieldType bitFieldTy) -> uint64_t { + if (mlir::Type storage = bitFieldTy.getStorageType()) + return getTypeLanguageAlignment(storage); + return 1; + }) + .Default([&](mlir::Type ty) { return layout.getTypeABIAlignment(ty); }); +} + // The implementation of this method is provided inline as it is particularly // well suited to constant folding when called on a specific Type subclass. llvm::TypeSize CIRDataLayout::getTypeSizeInBits(mlir::Type ty) const { diff --git a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp index e09be9c77cf8f..6fcdd35331ef3 100644 --- a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp +++ b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp @@ -794,9 +794,10 @@ cir::PtrSpecAttr getPointerSpec(mlir::DataLayoutEntryListRef params, // entry. That is LongLongAlign's initial value. constexpr static uint64_t kDefaultBitIntMaxAlignBits = 64; -/// The _BitInt alignment cap in bits. The #cir.bitint_spec entry holds -/// TargetInfo::getBitIntMaxAlign(). -uint64_t getBitIntMaxAlignBits(mlir::DataLayoutEntryListRef params) { +} // namespace + +/// The #cir.bitint_spec entry holds TargetInfo::getBitIntMaxAlign(). +uint64_t IntType::getBitIntMaxAlignBits(mlir::DataLayoutEntryListRef params) { for (mlir::DataLayoutEntryInterface entry : params) { if (!entry.isTypeEntry()) continue; @@ -805,7 +806,6 @@ uint64_t getBitIntMaxAlignBits(mlir::DataLayoutEntryListRef params) { } return kDefaultBitIntMaxAlignBits; } -} // namespace llvm::TypeSize PointerType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout, @@ -1095,15 +1095,17 @@ void IntType::print(mlir::AsmPrinter &printer) const { llvm::TypeSize IntType::getTypeSizeInBits(const mlir::DataLayout &dataLayout, mlir::DataLayoutEntryListRef params) const { - return llvm::TypeSize::getFixed(getStorageTypeWidth(dataLayout)); + if (!isBitInt()) + return llvm::TypeSize::getFixed(getWidth()); + uint64_t alignBits = + getBitIntAlignRequirement(getBitIntMaxAlignBits(params)) * 8; + return llvm::TypeSize::getFixed(llvm::alignTo(getWidth(), alignBits)); } unsigned IntType::getStorageTypeWidth(const mlir::DataLayout &dataLayout) const { - if (!isBitInt()) - return getWidth(); - uint64_t alignBits = dataLayout.getTypeABIAlignment(*this) * 8; - return static_cast<unsigned>(llvm::alignTo(getWidth(), alignBits)); + return static_cast<unsigned>( + dataLayout.getTypeSizeInBits(*this).getFixedValue()); } uint64_t @@ -1115,14 +1117,22 @@ IntType::getStorageTypeAlignment(const mlir::DataLayout &dataLayout) const { return dataLayout.getTypeABIAlignment(storageTy); } +uint64_t IntType::getBitIntAlignRequirement(uint64_t maxAlignBits) const { + assert(isBitInt() && "only a _BitInt has a target alignment cap"); + uint64_t alignBits = std::min( + static_cast<uint64_t>(llvm::PowerOf2Ceil(getWidth())), maxAlignBits); + return std::max(alignBits / 8, static_cast<uint64_t>(1)); +} + uint64_t IntType::getABIAlignment(const mlir::DataLayout &dataLayout, mlir::DataLayoutEntryListRef params) const { unsigned width = getWidth(); if (isBitInt()) { - uint64_t maxAlignBits = getBitIntMaxAlignBits(params); - uint64_t alignBits = std::min( - static_cast<uint64_t>(llvm::PowerOf2Ceil(width)), maxAlignBits); - return std::max(alignBits / 8, static_cast<uint64_t>(1)); + uint64_t storageBytes = getStorageTypeWidth(dataLayout) / 8; + uint64_t storageAlign = getStorageTypeAlignment(dataLayout); + if (llvm::alignTo(storageBytes, storageAlign) == storageBytes) + return storageAlign; + return 1; } // Round up to a power-of-two byte alignment. DataLayout consumers such as // llvm::Align require power-of-two alignments, and width / 8 is not a power diff --git a/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.cpp b/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.cpp index fde7c7cb3a210..36849f803de8e 100644 --- a/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.cpp +++ b/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.cpp @@ -106,29 +106,15 @@ static bool memberIsEmptyRecord(mlir::Type ty) { return recTy && recTy.isEmptyForABI(); } -/// A record's declared alignment, which the ABI uses for the byval and sret -/// alignment of an indirect argument. DataLayout derives alignment from the -/// members, so it cannot see `__attribute__((aligned(N)))`. The declared value -/// comes from the module's record-layout metadata instead. CIRGen emits an -/// entry for every record it names, so the computed fallback only serves -/// hand-written CIR. -static llvm::Align recordDeclaredAlign(ModuleOp modOp, cir::RecordType recTy, - const DataLayout &dl) { - auto layout = cir::tryGetRecordLayout(modOp, recTy.getName()); - if (!layout) - return llvm::Align(dl.getTypeABIAlignment(recTy)); - return llvm::Align(layout.getRecordAlign()); -} - /// A record's unadjusted alignment, the alignment its members give it before -/// an alignment attribute on the record raises it. Like the declared -/// alignment, it comes from the module's record-layout metadata, and the -/// computed fallback only serves hand-written CIR. +/// an alignment attribute on the record raises it. It comes from the module's +/// record-layout metadata, and the computed fallback only serves hand-written +/// CIR. static llvm::Align recordUnadjustedAlign(ModuleOp modOp, cir::RecordType recTy, - const DataLayout &dl) { + const cir::CIRDataLayout &cirDL) { auto layout = cir::tryGetRecordLayout(modOp, recTy.getName()); if (!layout) - return llvm::Align(dl.getTypeABIAlignment(recTy)); + return llvm::Align(cirDL.getTypeLanguageAlignment(recTy)); return llvm::Align(layout.getUnadjustedAlign()); } @@ -336,13 +322,15 @@ static mlir::Type unwrapLongDoubleVectorElement(mlir::Type ty) { /// reach this function. static const llvm::abi::Type *mapCIRType(mlir::Type type, mlir::abi::ABITypeMapper &typeMapper, - const DataLayout &dl, ModuleOp modOp) { + const DataLayout &dl, + const cir::CIRDataLayout &cirDL, + ModuleOp modOp) { llvm::abi::TypeBuilder &tb = typeMapper.getTypeBuilder(); return llvm::TypeSwitch<mlir::Type, const llvm::abi::Type *>(type) .Case([&](cir::IntType intTy) { - return tb.getIntegerType(intTy.getWidth(), - llvm::Align(dl.getTypeABIAlignment(type)), - intTy.isSigned(), intTy.getIsBitInt()); + return tb.getIntegerType( + intTy.getWidth(), llvm::Align(cirDL.getTypeLanguageAlignment(type)), + intTy.isSigned(), intTy.getIsBitInt()); }) .Case([&](cir::PointerType ptrTy) { unsigned addrSpace = 0; @@ -352,45 +340,50 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, addrSpace = targetAsAttr.getValue(); // Any address-space attribute is a qualifier. bool hasAddressSpaceQualifier = ptrTy.getAddrSpace() != nullptr; - return tb.getPointerType(dl.getTypeSizeInBits(type), - llvm::Align(dl.getTypeABIAlignment(type)), - addrSpace, hasAddressSpaceQualifier); + return tb.getPointerType( + dl.getTypeSizeInBits(type), + llvm::Align(cirDL.getTypeLanguageAlignment(type)), addrSpace, + hasAddressSpaceQualifier); }) .Case([&](cir::VPtrType) { // cir::VPtrType carries no address-space parameter yet, so this // always maps into the default one until that gap closes. assert(!cir::MissingFeatures::addressSpace()); - return tb.getPointerType(dl.getTypeSizeInBits(type), - llvm::Align(dl.getTypeABIAlignment(type))); + return tb.getPointerType( + dl.getTypeSizeInBits(type), + llvm::Align(cirDL.getTypeLanguageAlignment(type))); }) .Case([&](cir::BoolType) { // A bool is a one-bit integer to the classifier, as QualTypeMapper // maps it, so a bool vector is sized one bit per element. - return tb.getIntegerType(1, llvm::Align(dl.getTypeABIAlignment(type)), - /*Signed=*/false); + return tb.getIntegerType( + 1, llvm::Align(cirDL.getTypeLanguageAlignment(type)), + /*Signed=*/false); }) .Case([&](cir::VoidType) { return tb.getVoidType(); }) .Case([&](cir::FPTypeInterface fpTy) { // LongDoubleType reports its underlying format's semantics, so the // classifier sees x87 or IEEE quad rather than the wrapper. - return tb.getFloatType(fpTy.getFloatSemantics(), - llvm::Align(dl.getTypeABIAlignment(type))); + return tb.getFloatType( + fpTy.getFloatSemantics(), + llvm::Align(cirDL.getTypeLanguageAlignment(type))); }) .Case([&](cir::ComplexType complexTy) { return tb.getComplexType( - mapCIRType(complexTy.getElementType(), typeMapper, dl, modOp), - llvm::Align(dl.getTypeABIAlignment(type))); + mapCIRType(complexTy.getElementType(), typeMapper, dl, cirDL, + modOp), + llvm::Align(cirDL.getTypeLanguageAlignment(type))); }) .Case([&](cir::VectorType vecTy) { // isSupportedType rejects a scalable vector, so the element count is // always fixed here. return tb.getVectorType( - mapCIRType(vecTy.getElementType(), typeMapper, dl, modOp), - vecTy.getSize(), llvm::Align(dl.getTypeABIAlignment(type))); + mapCIRType(vecTy.getElementType(), typeMapper, dl, cirDL, modOp), + vecTy.getSize(), llvm::Align(cirDL.getTypeLanguageAlignment(type))); }) .Case([&](cir::ArrayType arrTy) { const llvm::abi::Type *elemAbi = - mapCIRType(arrTy.getElementType(), typeMapper, dl, modOp); + mapCIRType(arrTy.getElementType(), typeMapper, dl, cirDL, modOp); return tb.getArrayType(elemAbi, arrTy.getSize(), dl.getTypeSizeInBits(type).getFixedValue()); }) @@ -404,8 +397,9 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, flags = flags | llvm::abi::RecordFlags::HasFlexibleArrayMember; llvm::TypeSize sizeBits = llvm::TypeSize::getFixed( dl.getTypeSizeInBits(type).getFixedValue()); - llvm::Align align = recordDeclaredAlign(modOp, recTy, dl); - llvm::Align unadjustedAlign = recordUnadjustedAlign(modOp, recTy, dl); + llvm::Align align(cirDL.getTypeLanguageAlignment(recTy)); + llvm::Align unadjustedAlign = + recordUnadjustedAlign(modOp, recTy, cirDL); // Mapped with no fields, an empty record reaches Ignore on its own. // The size still matters, since a target may pass a large empty @@ -449,14 +443,15 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, const bool holdsUnit = idx == 0 && unitTy; if (holdsUnit) fields.push_back(llvm::abi::FieldInfo( - mapCIRType(unitTy, typeMapper, dl, modOp), offsetBits, + mapCIRType(unitTy, typeMapper, dl, cirDL, modOp), offsetBits, /*IsBitField=*/true, decl.getWidth(), /*IsUnnamedBitField=*/decl.getIsUnnamed())); mlir::Type declaredTy = decl.getDeclaredType(); if (!holdsUnit || dl.getTypeSizeInBits(declaredTy).getFixedValue() > unitBits) fields.push_back(llvm::abi::FieldInfo( - mapCIRType(declaredTy, typeMapper, dl, modOp), offsetBits, + mapCIRType(declaredTy, typeMapper, dl, cirDL, modOp), + offsetBits, /*IsBitField=*/true, holdsUnit ? 0 : decl.getWidth(), /*IsUnnamedBitField=*/holdsUnit || decl.getIsUnnamed())); } @@ -487,7 +482,7 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, memberIsEmptyRecord(variantTy)) continue; fields.push_back(llvm::abi::FieldInfo( - mapCIRType(variantTy, typeMapper, dl, modOp))); + mapCIRType(variantTy, typeMapper, dl, cirDL, modOp))); } return tb.getUnionType(fields, sizeBits, align, unadjustedAlign, llvm::abi::StructPacking::Default, flags); @@ -517,7 +512,7 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, "an empty-for-ABI member must not reach the classifier as an " "unnamed bit-field"); fields.push_back(llvm::abi::FieldInfo( - mapCIRType(fieldTy, typeMapper, dl, modOp), + mapCIRType(fieldTy, typeMapper, dl, cirDL, modOp), recTy.getElementOffset(dl, idx) * 8, /*IsBitField=*/isUnnamed, isUnnamed ? widthBits : 0, /*IsUnnamedBitField=*/isUnnamed)); @@ -747,10 +742,10 @@ CIRABIClassifierCommon::classifySignature( const llvm::abi::Type *retAbi = voidRet ? typeMapper.getTypeBuilder().getVoidType() - : mapCIRType(retCIR, typeMapper, dl, modOp); + : mapCIRType(retCIR, typeMapper, dl, cirDataLayout, modOp); SmallVector<const llvm::abi::Type *> argAbi; for (mlir::Type a : inputs) - argAbi.push_back(mapCIRType(a, typeMapper, dl, modOp)); + argAbi.push_back(mapCIRType(a, typeMapper, dl, cirDataLayout, modOp)); std::unique_ptr<llvm::abi::FunctionInfo> fi = llvm::abi::FunctionInfo::create(callConv, retAbi, argAbi, required); diff --git a/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.h b/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.h index 1250465402986..d49842a7ddd3a 100644 --- a/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.h +++ b/clang/lib/CIR/Dialect/Transforms/CIRABIClassifier.h @@ -24,6 +24,7 @@ #include "mlir/IR/Diagnostics.h" #include "mlir/Interfaces/DataLayoutInterfaces.h" #include "mlir/Support/LogicalResult.h" +#include "clang/CIR/Dialect/IR/CIRDataLayout.h" #include "clang/CIR/Dialect/IR/CIRDialect.h" #include "clang/CIR/Dialect/Passes.h" #include "llvm/ABI/FunctionInfo.h" @@ -117,7 +118,7 @@ class CIRABIClassifierCommon : public CIRABIClassifier { protected: CIRABIClassifierCommon(const mlir::DataLayout &dl, mlir::ModuleOp modOp) - : dl(dl), modOp(modOp), typeMapper(dl) {} + : dl(dl), modOp(modOp), cirDataLayout(modOp), typeMapper(dl) {} /// The library classifier for a function whose recorded target features /// may refine the ABI rules. @@ -132,6 +133,7 @@ class CIRABIClassifierCommon : public CIRABIClassifier { const mlir::DataLayout &dl; mlir::ModuleOp modOp; + cir::CIRDataLayout cirDataLayout; mlir::abi::ABITypeMapper typeMapper; private: diff --git a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp index 5583e88e32b25..b30a20e921421 100644 --- a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp +++ b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp @@ -2766,7 +2766,7 @@ void LoweringPreparePass::lowerStoreOfConstAggregate(cir::StoreOp op) { cir::CopyOp copyOp = builder.createCopy(op.getAddr(), globalPtr); cir::CIRDataLayout dataLayout(mlirModule); - uint64_t naturalAlign = dataLayout.getABITypeAlign(ty).value(); + uint64_t naturalAlign = dataLayout.getTypeLanguageAlignment(ty); if (alloca.getAlignment() != naturalAlign) copyOp.setDstAlignment(alloca.getAlignment()); uint64_t srcAlign = gv.getAlignment().value_or(naturalAlign); diff --git a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp index 5a5a5c778b710..97a70984a8486 100644 --- a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp +++ b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp @@ -500,8 +500,10 @@ static cir::AllocaOp createCoercionSlot( SmallPtrSetImpl<mlir::Operation *> &createdOps, unsigned offset) { assert(srcTy != dstTy && "callers must pre-check that the types diff er"); - uint64_t srcAlign = dl.getTypeABIAlignment(srcTy); - uint64_t dstAlign = dl.getTypeABIAlignment(dstTy); + cir::CIRDataLayout cirDataLayout( + slotBlock->getParentOp()->getParentOfType<mlir::ModuleOp>()); + uint64_t srcAlign = cirDataLayout.getTypeLanguageAlignment(srcTy); + uint64_t dstAlign = cirDataLayout.getTypeLanguageAlignment(dstTy); uint64_t allocaAlign = std::max(srcAlign, dstAlign); mlir::Type slotTy = coercionByteSize(srcTy, dl) >= coercionByteSize(dstTy, dl) ? srcTy @@ -517,7 +519,8 @@ static cir::AllocaOp createCoercionSlot( assert((offset == 0 || offset + dl.getTypeSize(coercedTy) <= dl.getTypeSize(slotTy)) && "coerce slot too small for offset access"); - assert((offset == 0 || offset % dl.getTypeABIAlignment(coercedTy) == 0) && + assert((offset == 0 || + offset % cirDataLayout.getTypeLanguageAlignment(coercedTy) == 0) && "a direct offset must be aligned for the coerced access"); mlir::OpBuilder::InsertionGuard guard(builder); @@ -738,7 +741,9 @@ emitCopiedCoercionSlot(mlir::OpBuilder &builder, mlir::Location loc, if (cir::AllocaOp src = cir::getUnderlyingAlloca(load.getAddr())) srcAlign = src.getAlignment(); else - srcAlign = load.getAlignment().value_or(dl.getTypeABIAlignment(recTy)); + srcAlign = load.getAlignment().value_or( + cir::CIRDataLayout(load->getParentOfType<mlir::ModuleOp>()) + .getTypeLanguageAlignment(recTy)); SmallPtrSet<mlir::Operation *, 4> ignored; cir::AllocaOp slot = createCoercionSlot(builder, loc, recTy, coercedTy, slotBlock, dl, ignored, offset); @@ -869,11 +874,13 @@ rewireRecordUses(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value val, } mlir::IntegerAttr srcAlign = builder.getI64IntegerAttr(addrAlign); + cir::CIRDataLayout cirDataLayout( + val.getParentRegion()->getParentOfType<mlir::ModuleOp>()); for (cir::StoreOp store : stores) { mlir::OpBuilder::InsertionGuard guard(builder); builder.setInsertionPoint(store); - uint64_t dstAlign = - store.getAlignment().value_or(dl.getTypeABIAlignment(recTy)); + uint64_t dstAlign = store.getAlignment().value_or( + cirDataLayout.getTypeLanguageAlignment(recTy)); auto copy = cir::CopyOp::create(builder, store.getLoc(), store.getAddr(), addr, builder.getI64IntegerAttr(dstAlign), srcAlign); @@ -1299,7 +1306,9 @@ insertArgCoercion(mlir::FunctionOpInterface funcOp, slot = cir::AllocaOp::create( builder, loc, getAllocaPtrTy(flatTy, dl), builder.getStringAttr("coerce"), - builder.getI64IntegerAttr(dl.getTypeABIAlignment(flatTy))); + builder.getI64IntegerAttr( + cir::CIRDataLayout(funcOp->getParentOfType<mlir::ModuleOp>()) + .getTypeLanguageAlignment(flatTy))); flattenOps.insert(slot); } else { slot = createCoercionSlot(builder, loc, flatTy, origTy, &entry, dl, @@ -2577,18 +2586,10 @@ mlir::LogicalResult classifyRegisterPair(cir::VAArgOp op, return mlir::success(); } -/// The alignment an argument is placed at. A record can require more than -/// the types of its members imply, from an `aligned` attribute on the record -/// or on one of its fields, and neither raises the alignment of any type. -/// Only the record layout knows, so the member-derived value alone can be too -/// small. -uint64_t argumentAreaAlign(mlir::Type ty, mlir::ModuleOp modOp, - const mlir::DataLayout &dl) { - uint64_t align = dl.getTypeABIAlignment(ty); - if (auto recTy = mlir::dyn_cast<cir::RecordType>(ty)) - if (auto layout = cir::tryGetRecordLayout(modOp, recTy.getName())) - align = std::max<uint64_t>(align, layout.getRecordAlign()); - return align; +/// The alignment an argument is placed at, which is the language alignment of +/// its type. +uint64_t argumentAreaAlign(mlir::Type ty, mlir::ModuleOp modOp) { + return cir::CIRDataLayout(modOp).getTypeLanguageAlignment(ty); } mlir::Value roundPointerUpToAlignment(CIRBaseBuilderTy &b, mlir::Location loc, @@ -2619,7 +2620,7 @@ mlir::Value buildOverflowAddrAndAdvance(CIRBaseBuilderTy &b, mlir::Value overflow = b.createLoad(f.loc, overflowP); mlir::Value bytePtr = b.createPtrBitcast(overflow, byteTy); - uint64_t tyAlign = argumentAreaAlign(f.resultTy, f.module, f.dl); + uint64_t tyAlign = argumentAreaAlign(f.resultTy, f.module); if (tyAlign > 8) bytePtr = roundPointerUpToAlignment(b, f.loc, bytePtr, tyAlign, f.dl); @@ -2717,7 +2718,7 @@ bool needsTempCopy(const VAArgFetch &f, unsigned neededInt, // A slot is only as aligned as its class, 8 for a GP register and 16 for an // SSE one, so a fetch the ABI places more strictly is copied through a temp. uint64_t slotAlign = neededSse ? 16 : 8; - return argumentAreaAlign(f.resultTy, f.module, f.dl) > slotAlign; + return argumentAreaAlign(f.resultTy, f.module) > slotAlign; } /// Copies what the registers carry into \p temp, which is the size of the @@ -2751,7 +2752,7 @@ mlir::Value copyRegisterToTemp(CIRBaseBuilderTy &b, mlir::Location loc, if (mlir::isa<cir::RecordType>(f.resultTy)) cir::CopyOp::create( b, loc, temp, regView, - b.getI64IntegerAttr(argumentAreaAlign(f.resultTy, f.module, f.dl)), + b.getI64IntegerAttr(argumentAreaAlign(f.resultTy, f.module)), b.getI64IntegerAttr(8)); else b.createStore(loc, b.createAlignedLoad(loc, regView, 8), temp); @@ -2860,18 +2861,17 @@ CIRABIRewriteContext::rewriteVAArg(mlir::Operation *vaArgOp, regPairTemp = builder.createAlloca( loc, builder.getPointerTo(ac.coercedType), "vaarg.reg", clang::CharUnits::fromQuantity( - std::max(dl.getTypeABIAlignment(ac.coercedType), - argumentAreaAlign(resultTy, module, dl)))); + std::max(cirDataLayout.getTypeLanguageAlignment(ac.coercedType), + argumentAreaAlign(resultTy, module)))); } mlir::Value regTemp; bool copyThroughTemp = !pairNeedsReassembly && needsTempCopy(fetch, neededInt, neededSse); if (copyThroughTemp) { - regTemp = - builder.createAlloca(loc, builder.getPointerTo(resultTy), "vaarg.reg", - clang::CharUnits::fromQuantity( - argumentAreaAlign(resultTy, module, dl))); + regTemp = builder.createAlloca( + loc, builder.getPointerTo(resultTy), "vaarg.reg", + clang::CharUnits::fromQuantity(argumentAreaAlign(resultTy, module))); } addr = cir::TernaryOp::create( @@ -2913,7 +2913,7 @@ CIRABIRewriteContext::rewriteVAArg(mlir::Operation *vaArgOp, // Every path above places the result at least this well aligned. mlir::Value resultAddr = builder.createPtrBitcast(addr, resultTy); - uint64_t resultAlign = argumentAreaAlign(resultTy, module, dl); + uint64_t resultAlign = argumentAreaAlign(resultTy, module); if (mlir::isa<cir::RecordType>(resultTy)) { SmallPtrSet<mlir::Operation *, 1> noExceptions; if (failed(rewireRecordUses(builder, loc, op.getResult(), resultAddr, diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp index 79f674eb5bb08..43afa2d15c8bf 100644 --- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp +++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp @@ -101,13 +101,15 @@ static mlir::InFlightDiagnostic emitTypeConversionError(mlir::Location loc, /// Alignment to use for a memory access whose op carries no explicit alignment. /// For _BitInt the storage integer iM's ABI alignment (e.g. i128's 16) -/// over-aligns the value, so use the CIR _BitInt ABI alignment (e.g. 8). -static uint64_t getMemoryFallbackAlignment(mlir::Type cirType, +/// over-aligns the value, so use the _BitInt language alignment (e.g. 8). +static uint64_t getMemoryFallbackAlignment(mlir::Operation *op, + mlir::Type cirType, mlir::Type llvmMemType, const mlir::DataLayout &dataLayout) { if (auto intTy = mlir::dyn_cast<cir::IntType>(cirType); intTy && intTy.isBitInt()) - return dataLayout.getTypeABIAlignment(intTy); + return cir::CIRDataLayout(op->getParentOfType<mlir::ModuleOp>()) + .getTypeLanguageAlignment(intTy); return dataLayout.getTypeABIAlignment(llvmMemType); } @@ -380,16 +382,16 @@ mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite( if (!convertTypeForMemory(*getTypeConverter(), dataLayout, pointeeType)) return emitTypeConversionError(op, pointeeType); - mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>()); + cir::CIRDataLayout cirDataLayout(op->getParentOfType<mlir::ModuleOp>()); const mlir::Value length = mlir::LLVM::ConstantOp::create( rewriter, op.getLoc(), rewriter.getI64Type(), - op.getCopySizeInBytes(layout)); + op.getCopySizeInBytes(cirDataLayout.layout)); assert(!cir::MissingFeatures::aggValueSlotVolatile()); - uint64_t dstTypeAlign = - dataLayout.getTypeABIAlignment(op.getDst().getType().getPointee()); - uint64_t srcTypeAlign = - dataLayout.getTypeABIAlignment(op.getSrc().getType().getPointee()); + uint64_t dstTypeAlign = cirDataLayout.getTypeLanguageAlignment( + op.getDst().getType().getPointee()); + uint64_t srcTypeAlign = cirDataLayout.getTypeLanguageAlignment( + op.getSrc().getType().getPointee()); mlir::NamedAttribute dstAlignAttr = rewriter.getNamedAttr( mlir::LLVM::LLVMDialect::getAlignAttrName(), @@ -2785,7 +2787,7 @@ mlir::LogicalResult CIRToLLVMLoadOpLowering::matchAndRewrite( mlir::LLVM::AtomicOrdering ordering = getLLVMMemOrder(op.getMemOrder()); std::optional<size_t> opAlign = op.getAlignment(); unsigned alignment = (unsigned)opAlign.value_or( - getMemoryFallbackAlignment(op.getType(), llvmTy, dataLayout)); + getMemoryFallbackAlignment(op, op.getType(), llvmTy, dataLayout)); assert(!cir::MissingFeatures::lowerModeOptLevel()); @@ -2843,7 +2845,7 @@ mlir::LogicalResult CIRToLLVMStoreOpLowering::matchAndRewrite( << "NYI: lowering store of a type with no memory representation"; std::optional<size_t> opAlign = op.getAlignment(); unsigned alignment = (unsigned)opAlign.value_or( - getMemoryFallbackAlignment(valueType, llvmTy, dataLayout)); + getMemoryFallbackAlignment(op, valueType, llvmTy, dataLayout)); assert(!cir::MissingFeatures::lowerModeOptLevel()); diff --git a/clang/test/CIR/CodeGen/agg-init-constexpr.cpp b/clang/test/CIR/CodeGen/agg-init-constexpr.cpp index d89959c410991..c0f5b7cceb8c2 100644 --- a/clang/test/CIR/CodeGen/agg-init-constexpr.cpp +++ b/clang/test/CIR/CodeGen/agg-init-constexpr.cpp @@ -24,7 +24,7 @@ extern "C" void construct() { // CIR-NEXT: %[[WC_ALLOCA:.*]] = cir.alloca "c" {{.*}} : !cir.ptr<!rec_WithCtor> // CIR-NEXT: %[[TMP_ALLOCA:.*]] = cir.alloca "tmp" {{.*}} : !cir.ptr<!rec_WithCtor> // CIR-NEXT: %[[GET_GLOBAL:.*]] = cir.get_global @__const.construct.tmp : !cir.ptr<!rec_WithCtor> -// CIR-NEXT: cir.copy %[[GET_GLOBAL]] align(8) to %[[TMP_ALLOCA]] align(8) : !cir.ptr<!rec_WithCtor> +// CIR-NEXT: cir.copy %[[GET_GLOBAL]] to %[[TMP_ALLOCA]] : !cir.ptr<!rec_WithCtor> // CIR-NEXT: cir.copy %[[TMP_ALLOCA]] align(8) to %[[WC_ALLOCA]] align(8) skip_tail_padding : !cir.ptr<!rec_WithCtor> // CIR-NEXT: cir.return diff --git a/clang/test/CIR/CodeGen/bitint-max-align.c b/clang/test/CIR/CodeGen/bitint-max-align.c index e2a72d3f91001..0f47ee2420049 100644 --- a/clang/test/CIR/CodeGen/bitint-max-align.c +++ b/clang/test/CIR/CodeGen/bitint-max-align.c @@ -51,8 +51,9 @@ struct Has129 g_struct = {7, -1}; // A64-OGCG-DAG: @g_struct = global { i32, [12 x i8], i256 } { i32 7, [12 x i8] zeroinitializer, i256 -1 }, align 16 // x86_64: 4 bytes of padding bring the 24-byte _BitInt to its 8-byte -// alignment. CIR packs the struct. Classic codegen does not. -// X64-CIR-DAG: !rec_Has129 = !cir.struct<"Has129" packed {data !s32i, pad !cir.array<!u8i x 4>, data !cir.int<s, 129, bitint>}> +// alignment. The _BitInt is stored as [24 x i8], whose LLVM alignment is 1, +// so the padding is written as an array and the struct is not packed. +// X64-CIR-DAG: !rec_Has129 = !cir.struct<"Has129" {data !s32i, pad !cir.array<!u8i x 4>, data !cir.int<s, 129, bitint>}> // X64-CIR-DAG: cir.global external @g_struct = #cir.const_record<{#cir.int<7> : !s32i, #cir.zero : !cir.array<!u8i x 4>, #cir.int<-1> : !cir.int<s, 129, bitint>}> : !rec_Has129 align(8) -// X64-LLVM-DAG: %struct.Has129 = type {{[<]?}}{ i32, [4 x i8], [24 x i8] }{{[>]?}} -// X64-LLVM-DAG: @g_struct = global %struct.Has129 {{[<]?}}{ i32 7, [4 x i8] zeroinitializer, [24 x i8] c"\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF" }{{[>]?}}, align 8 +// X64-LLVM-DAG: %struct.Has129 = type { i32, [4 x i8], [24 x i8] } +// X64-LLVM-DAG: @g_struct = global %struct.Has129 { i32 7, [4 x i8] zeroinitializer, [24 x i8] c"\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF\FF" }, align 8 diff --git a/clang/test/CIR/CodeGen/bitint-record-layout.c b/clang/test/CIR/CodeGen/bitint-record-layout.c index d4c95bee2a49b..5208e54dcfbed 100644 --- a/clang/test/CIR/CodeGen/bitint-record-layout.c +++ b/clang/test/CIR/CodeGen/bitint-record-layout.c @@ -137,6 +137,21 @@ struct Outer2 { // CIR-DAG: !rec_Outer2 = !cir.struct<"Outer2" {data !s8i, pad !cir.array<!u8i x 7>, data !rec_Inner2, data !s16i, pad !cir.array<!u8i x 6>}> // LLVM-DAG: %struct.Outer2 = type { i8, [7 x i8], %struct.Inner2, i16, [6 x i8] } +// Inner3 lowers to { i128 }, whose LLVM alignment is 16. Its C alignment is 8, +// so it sits at offset 8 in Outer3, which is packed. +struct Inner3 { + _BitInt(128) bi; +}; +// CIR-DAG: !rec_Inner3 = !cir.struct<"Inner3" {data !s128i_bitint}> +// LLVM-DAG: %struct.Inner3 = type { i128 } + +struct Outer3 { + char c; + struct Inner3 inner; +}; +// CIR-DAG: !rec_Outer3 = !cir.struct<"Outer3" packed {data !s8i, pad !cir.array<!u8i x 7>, data !rec_Inner3}> +// LLVM-DAG: %struct.Outer3 = type <{ i8, [7 x i8], %struct.Inner3 }> + union JustBIUnion jbiu = { .bi = 54321 }; // CIR-DAG: cir.global external @jbiu = #cir.const_record<{#cir.int<54321> : !cir.int<s, 65, bitint>}> : !rec_JustBIUnion align(8) @@ -196,6 +211,9 @@ struct Outer nestedArr[2] = {{1, 222}, {3, 444}}; struct Outer2 nestedArr2[2] = {{1, 222}, {3, 444}}; // CIR-DAG: cir.global external @nestedArr2 = #cir.const_array<[#cir.const_record<{#cir.int<1> : !s8i, #cir.zero : !cir.array<!u8i x 7>, #cir.const_record<{#cir.int<222> : !s32i, #cir.zero : !cir.array<!u8i x 4>, #cir.int<0> : !s128i_bitint}> : !rec_Inner2, #cir.int<0> : !s16i, #cir.zero : !cir.array<!u8i x 6>}> : !rec_Outer2, #cir.const_record<{#cir.int<3> : !s8i, #cir.zero : !cir.array<!u8i x 7>, #cir.const_record<{#cir.int<444> : !s32i, #cir.zero : !cir.array<!u8i x 4>, #cir.int<0> : !s128i_bitint}> : !rec_Inner2, #cir.int<0> : !s16i, #cir.zero : !cir.array<!u8i x 6>}> : !rec_Outer2]> : !cir.array<!rec_Outer2 x 2> align(16) // LLVM-DAG: @nestedArr2 = global [2 x %struct.Outer2] [%struct.Outer2 { i8 1, [7 x i8] zeroinitializer, %struct.Inner2 <{ i32 222, [4 x i8] zeroinitializer, i128 0 }>, i16 0, [6 x i8] zeroinitializer }, %struct.Outer2 { i8 3, [7 x i8] zeroinitializer, %struct.Inner2 <{ i32 444, [4 x i8] zeroinitializer, i128 0 }>, i16 0, [6 x i8] zeroinitializer }], align 16 +struct Outer3 nestedArr3[2] = {{1, {222}}, {3, {444}}}; +// CIR-DAG: cir.global external @nestedArr3 = #cir.const_array<[#cir.const_record<{#cir.int<1> : !s8i, #cir.zero : !cir.array<!u8i x 7>, #cir.const_record<{#cir.int<222> : !s128i_bitint}> : !rec_Inner3}> : !rec_Outer3, #cir.const_record<{#cir.int<3> : !s8i, #cir.zero : !cir.array<!u8i x 7>, #cir.const_record<{#cir.int<444> : !s128i_bitint}> : !rec_Inner3}> : !rec_Outer3]> : !cir.array<!rec_Outer3 x 2> align(16) +// LLVM-DAG: @nestedArr3 = global [2 x %struct.Outer3] [%struct.Outer3 <{ i8 1, [7 x i8] zeroinitializer, %struct.Inner3 { i128 222 } }>, %struct.Outer3 <{ i8 3, [7 x i8] zeroinitializer, %struct.Inner3 { i128 444 } }>], align 16 _BitInt(128) get_bi(void) { return l128[1].bi; } // CIR-LABEL: cir.func no_inline dso_local @get_bi() -> !s128i_bitint @@ -227,6 +245,12 @@ _BitInt(128) get_bi2(void) { return arrMem[1].bi[1]; } // LLVM-LABEL: define dso_local i128 @get_bi2() // LLVM: load i128, ptr getelementptr inbounds nuw (i8, ptr @arrMem, i64 64), align 8 +void copy_outer3(struct Outer3 *d, struct Outer3 *s) { *d = *s; } +// CIR-LABEL: cir.func no_inline dso_local @copy_outer3( +// CIR: cir.copy %{{.*}} align(8) to %{{.*}} align(8) : !cir.ptr<!rec_Outer3> +// LLVM-LABEL: define dso_local void @copy_outer3( +// LLVM: call void @llvm.memcpy.p0.p0.i64(ptr align 8 %{{.*}}, ptr align 8 %{{.*}}, i64 24, i1 false) + void force_emit() { union BIUnionArr b; diff --git a/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-padded.cir b/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-padded.cir index d979c9350886b..0ece41145eda4 100644 --- a/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-padded.cir +++ b/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-padded.cir @@ -107,7 +107,7 @@ module attributes { // CHECK: cir.func{{.*}} @call_ov(%arg0: !s32i) // CHECK: %[[IN:.*]] = cir.alloca "coerce"{{.*}}: !cir.ptr<!rec_Ov> // CHECK: %[[OUT:.*]] = cir.alloca "coerce"{{.*}}: !cir.ptr<!rec_Ov> - // CHECK: cir.copy %[[IN]] align(4) to %[[OUT]] align(4) : !cir.ptr<!rec_Ov> + // CHECK: cir.copy %[[IN]] align(16) to %[[OUT]] align(16) : !cir.ptr<!rec_Ov> // CHECK: %[[OUTVIEW:.*]] = cir.cast bitcast %[[OUT]] : !cir.ptr<!rec_Ov> -> !cir.ptr<!s32i> // CHECK: %[[REG:.*]] = cir.load %[[OUTVIEW]] : !cir.ptr<!s32i>, !s32i // CHECK: cir.call @take_ov(%[[REG]]) : (!s32i) -> () diff --git a/clang/test/CIR/Transforms/abi-lowering/x86_64-union.cir b/clang/test/CIR/Transforms/abi-lowering/x86_64-union.cir index 81f7e1f917af5..c1b7a281a5297 100644 --- a/clang/test/CIR/Transforms/abi-lowering/x86_64-union.cir +++ b/clang/test/CIR/Transforms/abi-lowering/x86_64-union.cir @@ -512,7 +512,7 @@ module attributes { } // CHECK: cir.func{{.*}} @take_empty_over(%arg0: !s32i) - // CHECK: %[[SLOT:.*]] = cir.alloca "coerce" align(4) : !cir.ptr<!rec_UEmptyOver> + // CHECK: %[[SLOT:.*]] = cir.alloca "coerce" align(16) : !cir.ptr<!rec_UEmptyOver> // CHECK: %[[CAST:.*]] = cir.cast bitcast %[[SLOT]] : !cir.ptr<!rec_UEmptyOver> -> !cir.ptr<!s32i> // A union of nothing but an empty member classifies Ignore, the same as the diff --git a/clang/unittests/CIR/IntTypeABIAlignTest.cpp b/clang/unittests/CIR/IntTypeABIAlignTest.cpp index 5fe0dc5bd2b4b..e56e1c5c94600 100644 --- a/clang/unittests/CIR/IntTypeABIAlignTest.cpp +++ b/clang/unittests/CIR/IntTypeABIAlignTest.cpp @@ -6,16 +6,21 @@ // //===----------------------------------------------------------------------===// // -// Unit tests for IntType::getABIAlignment. +// Unit tests for IntType::getABIAlignment and +// CIRDataLayout::getTypeLanguageAlignment. // //===----------------------------------------------------------------------===// +#include "mlir/Dialect/DLTI/DLTI.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/MLIRContext.h" +#include "clang/CIR/Dialect/IR/CIRAttrs.h" +#include "clang/CIR/Dialect/IR/CIRDataLayout.h" #include "clang/CIR/Dialect/IR/CIRDialect.h" #include "clang/CIR/Dialect/IR/CIRTypes.h" #include "llvm/Support/MathExtras.h" #include "gtest/gtest.h" +#include <optional> using namespace mlir; using namespace cir; @@ -24,7 +29,9 @@ namespace { class IntTypeABIAlignTest : public ::testing::Test { protected: - IntTypeABIAlignTest() { context.loadDialect<cir::CIRDialect>(); } + IntTypeABIAlignTest() { + context.loadDialect<cir::CIRDialect, mlir::DLTIDialect>(); + } MLIRContext context; @@ -37,6 +44,46 @@ class IntTypeABIAlignTest : public ::testing::Test { module->erase(); return align; } + + struct Alignments { + uint64_t abi; + uint64_t language; + }; + + /// The ABI and language alignments of \p ty in a module whose data layout + /// aligns i8 through i128 to their widths, as x86-64 does, and caps the + /// language alignment of a _BitInt at \p bitIntMaxAlignBits, if given. + /// \p recordLayouts become the module's cir.record_layouts entries. + Alignments + targetAlignments(mlir::Type ty, + std::optional<uint32_t> bitIntMaxAlignBits = {}, + llvm::ArrayRef<mlir::NamedAttribute> recordLayouts = {}) { + OpBuilder builder(&context); + auto module = ModuleOp::create(builder.getUnknownLoc()); + auto i64 = mlir::IntegerType::get(&context, 64); + llvm::SmallVector<mlir::DataLayoutEntryInterface> entries; + for (uint64_t width : {8, 16, 32, 64, 128}) { + auto align = mlir::DenseIntElementsAttr::get<uint64_t>( + mlir::VectorType::get({2}, i64), {width, width}); + entries.push_back(mlir::DataLayoutEntryAttr::get( + mlir::IntegerType::get(&context, width), align)); + } + if (bitIntMaxAlignBits) { + auto key = IntType::getBitIntMaxAlignKey(&context); + auto spec = BitIntSpecAttr::get(&context, *bitIntMaxAlignBits); + entries.push_back(mlir::DataLayoutEntryAttr::get(key, spec)); + } + module->setAttr(mlir::DLTIDialect::kDataLayoutAttrName, + mlir::DataLayoutSpecAttr::get(&context, entries)); + if (!recordLayouts.empty()) + module->setAttr(CIRDialect::getRecordLayoutsAttrName(), + mlir::DictionaryAttr::get(&context, recordLayouts)); + cir::CIRDataLayout dl(module); + Alignments result{dl.layout.getTypeABIAlignment(ty), + dl.getTypeLanguageAlignment(ty)}; + module->erase(); + return result; + } }; // The fundamental integer widths keep their natural alignment. @@ -67,4 +114,87 @@ TEST_F(IntTypeABIAlignTest, NonFundamentalWidthIsPowerOfTwo) { // A sub-byte width must still report a valid, non-zero alignment. TEST_F(IntTypeABIAlignTest, SubByteWidth) { EXPECT_EQ(abiAlign(1, true), 1u); } +// An ordinary integer's language alignment is its ABI alignment. +TEST_F(IntTypeABIAlignTest, LanguageAlignmentOfOrdinaryInt) { + Alignments i32 = targetAlignments(IntType::get(&context, 32, true)); + EXPECT_EQ(i32.abi, 4u); + EXPECT_EQ(i32.language, 4u); + Alignments i128 = targetAlignments(IntType::get(&context, 128, true)); + EXPECT_EQ(i128.abi, 16u); + EXPECT_EQ(i128.language, 16u); +} + +// A _BitInt's ABI alignment is the alignment of its storage integer. +// _BitInt(17) is held in an i32. +TEST_F(IntTypeABIAlignTest, AlignmentsOfBitInt) { + Alignments bitInt17 = + targetAlignments(IntType::get(&context, 17, true, /*isBitInt=*/true)); + EXPECT_EQ(bitInt17.abi, 4u); + EXPECT_EQ(bitInt17.language, 4u); +} + +// x86-64 caps the language alignment of a _BitInt at 64 bits. _BitInt(65) is +// then held in an i128, whose alignment of 16 is the ABI alignment. +TEST_F(IntTypeABIAlignTest, BitIntMaxAlignCapsLanguageAlignment) { + Alignments bitInt65 = + targetAlignments(IntType::get(&context, 65, true, /*isBitInt=*/true), 64); + EXPECT_EQ(bitInt65.abi, 16u); + EXPECT_EQ(bitInt65.language, 8u); +} + +// _BitInt(129) is 24 bytes, which an i192 cannot hold without padding, so it +// is held as bytes and its ABI alignment is 1. +TEST_F(IntTypeABIAlignTest, BitIntHeldAsBytes) { + Alignments bitInt129 = targetAlignments( + IntType::get(&context, 129, true, /*isBitInt=*/true), 64); + EXPECT_EQ(bitInt129.abi, 1u); + EXPECT_EQ(bitInt129.language, 8u); +} + +// The int member has the higher ABI alignment, so it is the union's storage +// type and sets the union's ABI alignment. The union's language alignment is +// the largest language alignment of any member, which is the _BitInt's 8. +TEST_F(IntTypeABIAlignTest, UnionLanguageAlignmentUsesAllMembers) { + mlir::Type members[] = {IntType::get(&context, 129, true, /*isBitInt=*/true), + IntType::get(&context, 32, true)}; + auto padding = cir::ArrayType::get(IntType::get(&context, 8, false), 20); + auto unionTy = UnionType::get(&context, members, /*packed=*/false, padding, + RecordType::getAllDataKinds(members)); + Alignments alignments = targetAlignments(unionTy, 64); + EXPECT_EQ(alignments.abi, 4u); + EXPECT_EQ(alignments.language, 8u); +} + +// struct Outer3 { char c; struct Inner3 { _BitInt(128) bi; } inner; } is +// packed in CIR only so that inner sits at its C offset of 8, since Inner3's +// ABI alignment is 16. Its language alignment is the record alignment in its +// layout entry. Without an entry, the packed record gets 1. +TEST_F(IntTypeABIAlignTest, PackedRecordLanguageAlignmentFromLayout) { + auto u8 = IntType::get(&context, 8, false); + auto s8 = IntType::get(&context, 8, true); + mlir::Type innerMembers[] = { + IntType::get(&context, 128, true, /*isBitInt=*/true)}; + auto inner = StructType::get(&context, innerMembers, + mlir::StringAttr::get(&context, "Inner3"), + /*packed=*/false, /*is_class=*/false, + RecordType::getAllDataKinds(innerMembers)); + mlir::Type outerMembers[] = {s8, cir::ArrayType::get(u8, 7), inner}; + RecordMemberKind outerKinds[] = { + RecordMemberKind::Data, RecordMemberKind::Pad, RecordMemberKind::Data}; + auto outerName = mlir::StringAttr::get(&context, "Outer3"); + auto outer = StructType::get(&context, outerMembers, outerName, + /*packed=*/true, /*is_class=*/false, outerKinds); + + mlir::NamedAttribute layouts[] = {mlir::NamedAttribute( + outerName, RecordLayoutAttr::get(&context, ArgPassingKind::CanPassInRegs, + /*has_trivial_dtor=*/true, + /*record_align=*/8))}; + Alignments withLayout = targetAlignments(outer, 64, layouts); + EXPECT_EQ(withLayout.abi, 1u); + EXPECT_EQ(withLayout.language, 8u); + + Alignments withoutLayout = targetAlignments(outer, 64); + EXPECT_EQ(withoutLayout.language, 1u); +} + } // namespace _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
