[cfe-dev] Cortex-M4F Assembly Code Generation Incorrect for float casting, causing HardFaults
Tim Northover via cfe-dev
cfe-dev at lists.llvm.org
Thu Aug 10 07:57:24 PDT 2017
On 10 August 2017 at 07:25, Dan Walmsley via cfe-dev
<cfe-dev at lists.llvm.org> wrote:
> So its not currently possible to read a uint32 value from a buffer at an unaligned position. This should work shouldn’t it?
People have already pointed out that you're violating alignment
requirements which makes the code wrong. There's actually a second
issue called "strict aliasing". Essentially, if you have a buffer or
other object of one type it's invalid to cast a pointer to a different
type and access it even if the alignment requirements are met.
The portable way to write your Read function is:
template <typename T> inline T Read (uint8_t* data)
{
T value;
memcpy(&value, data, sizeof(Val));
return Val;
}
because "memcpy" is one of the very few ways of legitimately playing
those kinds of tricks. It'll also completely avoid the alignment
problems you were having and the compiler should optimize this to the
best permitted code sequence (for example it might use an unaligned
load followed by an aligned store if it thinks that's profitable).
Cheers.
Tim.
More information about the cfe-dev
mailing list