[clang] [Sema] Diagnose taking the address of a #pragma pack member (PR #219096)

Aaron Puchert via cfe-commits cfe-commits at lists.llvm.org
Mon Sep 14 13:57:58 PDT 2026


================
@@ -16983,6 +16983,26 @@ void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
   }
 }
 
+/// If packing reduces \p FD below the alignment required by its type, return
+/// the alignment it is reduced to. __attribute__((packed)) reduces every
+/// field; #pragma pack(N) only reduces fields that require more than N.
+static std::optional<CharUnits> getPackedFieldAlignment(const ASTContext &Ctx,
+                                                        const FieldDecl *FD) {
+  const RecordDecl *RD = FD->getParent();
+  bool IsPacked = FD->hasAttr<PackedAttr>() || RD->hasAttr<PackedAttr>();
+  const auto *MFAA = RD->getAttr<MaxFieldAlignmentAttr>();
+  if (!IsPacked && !MFAA)
+    return std::nullopt;
+
+  CharUnits TypeAlignment = Ctx.getTypeAlignInChars(FD->getType());
+  if (!IsPacked &&
+      Ctx.toCharUnitsFromBits(MFAA->getAlignment()) >= TypeAlignment)
+    return std::nullopt;
----------------
aaronpuchert wrote:

That's an interesting development. I forgot that `__attribute__((aligned))` on `typedef` can also lower alignment. I'd be fine if you skip that for now (since your focus is packing pragmas), but perhaps we should actually include this attribute. (Perhaps a bit weird to warn about this under `-Waddress-of-packed-member`, but the effect is the same. Your motivating example doesn't care which attribute lowered alignment.)

https://github.com/llvm/llvm-project/pull/219096


More information about the cfe-commits mailing list