llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.68k stars 11.86k forks source link

Clang allows arrays with overaligned element types with size not a multiple of alignment where GCC doesn't #53414

Open hubert-reinterpretcast opened 2 years ago

hubert-reinterpretcast commented 2 years ago

Clang allows arrays of overaligned elements where the alignment and the size does not share the usual relationship (size is an integer multiple of the alignment) with no diagnostic message whatsoever (-Wall -Wextra -Weverything -pedantic-errors) even though such arrays break expectations one way or another and GCC has (since at least 4.1.2) disallowed at least cases where the size is less then the alignment.

In terms of possible ways to realize such an array, either the elements are not necessarily all aligned to the higher alignment or the size of the array must be larger than the size of the elements multiplied by the number of elements. Clang implements the former and GCC (as of 11.x) avoids both.

Compiler Explorer link: https://godbolt.org/z/hYzn8jx4b

Source:

typedef struct A1 { char a[1]; } A1 __attribute__((__aligned__(8)));
typedef struct A2 { char a[8]; } A2 __attribute__((__aligned__(8)));
typedef struct A3 { char a[9]; } A3 __attribute__((__aligned__(8)));

#define NUM_ELEMENTS 2

extern A1 arr1[NUM_ELEMENTS];  // GCC errors; Clang does not
extern A2 arr2[NUM_ELEMENTS];  // GCC okay with this
extern A3 arr3[NUM_ELEMENTS];  // GCC errors; Clang does not

_Static_assert(sizeof(arr1) != sizeof(*arr1) * NUM_ELEMENTS, "");  // Clang is okay with this
_Static_assert(sizeof(arr2) == sizeof(*arr2) * NUM_ELEMENTS, "");
_Static_assert(sizeof(arr3) != sizeof(*arr3) * NUM_ELEMENTS, "");  // Clang is okay with this

Compiler invocation: clang -cc1 -fsyntax-only -Wall -Wextra -Weverything -pedantic-errors -x c -

Expected behaviour: Diagnostic messages for array elements with sizes that are not an integer multiple of their alignment

Actual behaviour: Compiles successfully with no diagnostics

Compiler version info (clang -v):

clang version 14.0.0 (https://github.com/llvm/llvm-project.git fe30370b007e7efa1bd1f39a3189b27ae4e5fcbe)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /opt/wandbox/clang-head/bin
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Candidate multilib: .;@m64
Selected multilib: .;@m64
llvmbot commented 2 years ago

@llvm/issue-subscribers-clang-frontend