llvm / llvm/llvm-project

Common initial sequence is not respected when alignas is used

Open
#186,040 2 comments 0 reactions 0 assignees View on GitHub
clang:frontend diverges-from:edg diverges-from:gcc diverges-from:msvc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

The following program demonstrates the issue:
```cpp
#include
#include
int main(){
struct A{char x;};
struct alignas(2)B{char x;};
struct C{A y;char z;};
struct D{B y;char z;};
union U{C a;D b;};
static_assert(std::is_standard_layout_v);
static_assert(std::is_standard_layout_v);
static_assert(std::is_layout_compatible_v);
U u;
u.a.z=1;
std::cout<<+u.b.z<<'\n';
}
```
Clang recognizes that C and D are both layout-compatible standard layout classes, therefore all of their members should be part of the common initial sequence. However, Clang does not seem to lay out their respective z members so that they have the same offset. There seems to be two possible solutions here. First, reject that C and D are layout-compatible and possibly also further reject that A and B are layout-compatible. Second, whenever a standard layout class is used as a member it must be aligned to the maximum possible alignment so that any alignment differences do not matter.

See also cplusplus/draft#8787.

Contributor guide

Open the contributing guide

Research direction

Start by compiling the supplied C++ reproducer and inspecting Clang's record layouts for C and D, focusing on the offsets of their z members. Then trace the handling of standard-layout classes, common initial sequences, layout compatibility, and alignas to determine whether compatibility should be rejected or member offsets adjusted; add a regression test for the resolved behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.