From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 48) id 0E9463858D39; Tue, 14 Dec 2021 00:38:28 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 0E9463858D39 From: "kobalicek.petr at gmail dot com" To: gcc-bugs@gcc.gnu.org Subject: [Bug c++/103699] Reading or writing a constant unaligned value is wrongly optimized causing an incorrect result (GCC-11 and up) Date: Tue, 14 Dec 2021 00:38:27 +0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: changed X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: c++ X-Bugzilla-Version: 11.0 X-Bugzilla-Keywords: X-Bugzilla-Severity: normal X-Bugzilla-Who: kobalicek.petr at gmail dot com X-Bugzilla-Status: WAITING X-Bugzilla-Resolution: X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Flags: X-Bugzilla-Changed-Fields: Message-ID: In-Reply-To: References: Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated MIME-Version: 1.0 X-BeenThere: gcc-bugs@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-bugs mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Tue, 14 Dec 2021 00:38:28 -0000 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=3D103699 --- Comment #4 from Petr --- Additional test case: #include #include typedef uint32_t __attribute__((__aligned__(1))) UnalignedUInt32; typedef uint64_t __attribute__((__aligned__(1))) UnalignedUInt64; uint32_t byteswap32(uint32_t x) noexcept { return (x << 24) | (x >> 24) | ((x << 8) & 0x00FF0000u) | ((x >> 8) & 0x0000FF00); } uint64_t byteswap64(uint64_t x) noexcept { return ((x << 56) & 0xff00000000000000) | ((x << 40) & 0x00ff000000000000) | ((x << 24) & 0x0000ff0000000000) | ((x << 8) & 0x000000ff00000000) | ((x >> 8) & 0x00000000ff000000) | ((x >> 24) & 0x0000000000ff0000) | ((x >> 40) & 0x000000000000ff00) | ((x >> 56) & 0x00000000000000ff); } static inline void writeU64be(void* p, uint64_t val) { static_cast(p)[0] =3D byteswap64(val); } static inline uint32_t readU32be(const void* p) noexcept { uint32_t x =3D static_cast(p)[0]; return byteswap32(x); } // Returns 0708090A uint32_t test_u32() { uint8_t array[16] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; writeU64be(array + 6, 0xAABBCCDDEEFF1213); return readU32be(array + 7); } static uint8_t array_static[16] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; int main() { printf("%08X\n", test_u32()); writeU64be(array_static + 6, 0xAABBCCDDEEFF1213); printf("%08X\n", readU32be(array_static + 7)); return 0; } It prints: 0708090A BBCCDDEE Clang prints: BBCCDDEE BBCCDDEE=