Avoid strict aliasing violation on type punning inside llvm::PointerIntPair
authorBreno GuimarĂ£es <brenorg@gmail.com>
Thu, 23 Feb 2023 15:29:47 +0000 (15:29 +0000)
committerVictor Campos <victor.campos@arm.com>
Thu, 23 Feb 2023 17:03:23 +0000 (17:03 +0000)
commit875391728c11339c8a6cd3338bcaa5ec0ffc2496
treef429a9ab91528d11e996585ec38ade16866180c1
parentaf694df712f28f419883e322d7dc978f04bfe38f
Avoid strict aliasing violation on type punning inside llvm::PointerIntPair

llvm::PointerIntPair has methods that when used together can invoke
undefined behavior by violating strict aliasing.

`getPointer()` uses the underlying storage as it's declared: `intptr_t`
`getAddrOfPointer()` casts the underlying storage as if it was a
`PointerTy`

This violates strict aliasing, so depending on how they are used, it's
possible to have the compiler to optimize the code in unwanted ways.
See the unit test in the patch. We declare a `PointerIntPair` and use
the `getAddrOfPointer` method to fill in the a pointer value.  Then,
when we use `getPointer` the compiler is thrown off, thinking that
`intptr_t` storage could not have possibly be changed, and the check
fails.

Reviewed By: efriedma

Differential Revision: https://reviews.llvm.org/D124571
llvm/include/llvm/ADT/PointerIntPair.h
llvm/unittests/ADT/PointerIntPairTest.cpp