<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Thu, Jan 14, 2016 at 12:56 PM, John McCall via cfe-dev <span dir="ltr"><<a href="mailto:cfe-dev@lists.llvm.org" target="_blank">cfe-dev@lists.llvm.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">C 6.3.2.3p7 (N1548) says:<br>
A pointer to an object type may be converted to a pointer to a<br>
different object type. If the resulting pointer is not correctly<br>
aligned) for the referenced type, the behavior is undefined.<br>
<br>
C++ [expr.reinterpret.cast]p7 (N4527) defines pointer conversions in terms<br>
of conversions from void*:<br>
An object pointer can be explicitly converted to an object pointer<br>
of a different type. When a prvalue v of object pointer type is<br>
converted to the object pointer type “pointer to cv T”, the result<br>
is static_cast<cv T*>(static_cast<cv void*>(v)).<br>
<br>
C++ [expr.static.cast]p13 says of conversions from void*:<br>
A prvalue of type “pointer to cv1 void” can be converted to a<br>
prvalue of type “pointer to cv2 T” .... If the original pointer value<br>
represents the address A of a byte in memory and A satisfies the alignment<br>
requirement of T, then the resulting pointer value represents the same<br>
address as the original pointer value, that is, A. The result of any<br>
other such pointer conversion is unspecified.<br>
<br>
The clear intent of these rules is that the implementation may assume<br>
that any pointer is adequately aligned for its pointee type, because any<br>
attempt to actually create such a pointer has undefined behavior. It is<br>
very likely that, if we found a hole in those rules that seemed to permit<br>
the creation of unaligned pointers, we could go to the committees and<br>
have that hole closed. The language policy here is clear.<br>
<br>
There are architectures where this policy is mandatory. The classic<br>
example is (I believe) the Cray C90, which provides word-addressed 32-bit<br>
pointers. Pointers to most types can use this native representation directly.<br>
char*, however, requires sub-word addressing, which means void* and char*<br>
are actually 64 bits in order to permit the storage of the sub-word offset.<br>
An int* therefore literally cannot express an arbitrary void*.<br>
<br>
Less dramatically, there are architectural features that clearly depend<br>
on alignment. It's unreasonable to expect processors to support atomic<br>
accesses that straddle the basic unit of their cache coherence implementations.<br>
Supporting small unaligned accesses has a fairly marginal cost in extra<br>
hardware, but as accesses grow to 128 bits or larger, those costs can spiral<br>
out of control. These restrictions are fairly widely understood by compiler<br>
users.<br>
<br>
Everything below is mushier. It's clearly advantageous for the compiler to<br>
be able to make stronger assumptions about alignment when accessing memory.<br>
ISAs often allow more efficient accesses to properly-aligned memory; for<br>
example, 32-bit ARM can perform a 64-bit memory access in a single<br>
instruction, but the address is required to be 8-byte-aligned. Alignment<br>
also affects compiler decisions even when the architecture doesn't enforce<br>
it; for example, it can be profitable to combine two adjacent loads into<br>
a single, wider load, but this will often slow down code if the wider load is<br>
no longer properly aligned.<br>
<br>
As is the case with most forms of undefined behavior, programmers have at<br>
best an abstract appreciation for the positive effects of these optimizations,<br>
but they have a very concrete understanding of the disruptive life effects<br>
of being forced to fix crashes from mis-alignment.<br>
<br>
Our standard response in LLVM/Clang is to explain the undefined behavior<br>
rule, explain the benefits it provides, and politely ask users to, well,<br>
deal with it. And that's appropriate; most forms of undefined behavior<br>
under the standard(s) are reasonable requests with reasonable code<br>
workarounds. However, we have also occasionally looked at a particular<br>
undefined behavior rule and decided that there's a real usability problem<br>
with enforcing it as written. In these cases, we use our power as<br>
implementors to make some subset of that behavior well-defined in order to<br>
fix that problem. For example, we did this for TBAA, because we recognized<br>
that certain "obvious" aliasing violations were idiomatic and only had<br>
awkward workarounds under the standard.<br>
<br>
There's a similar problem here. Much like TBAA, fixing it doesn't require<br>
completely abandoning the idea of enforcing type-based alignment assumptions.<br>
It does, however, require a significant adjustment to the language rule.<br>
<br>
The problem is this: the standards make it undefined behavior to even<br>
create an unaligned pointer. Therefore, as soon as I've got such a<br>
pointer, I'm basically doomed; it is no longer possible to locally<br>
work around the problem. I have to change the type of the pointer to<br>
something that requires less alignment, and not just where I'm using<br>
it, or even just within my function, but all the way up to wherever it<br>
came from.<br>
<br>
For example, suppose I've got this function:<br>
<br>
void processBuffer(const int32_t *buffer, size_t length) {<br>
...<br>
}<br>
<br>
I get a bug report saying that my function is crashing, and I decide<br>
that the right fix is to make the function handle unaligned buffers<br>
correctly. Maybe that's a binary-compatibility requirement, or maybe the<br>
buffer is usually coming from a serialized format that doesn't guarantee<br>
alignment, and it's clearly unreasonable to copy the buffer just to satisfy<br>
my function.<br>
<br>
So how can I make this function handle unaligned buffers? The type of the<br>
argument itself means that being passed an unaligned buffer has undefined<br>
behavior. Now, I can change that parameter to use an unaligned typedef:<br>
<br>
typedef int32_t unaligned_int32_t __attribute__((aligned(1)));<br>
void processBuffer(const unaligned_int32_t *buffer, size_t length) {<br>
...<br>
}<br>
<br>
But this has severe problems. First off, this is a GCC/Clang extension; a lot<br>
of programmers feel uncomfortable adopting that, especially to fix a problem<br>
that's in principle common across compilers. Second, alignment attributes<br>
are not really part of the type system, which means that they can be<br>
silently dropped by any number of things, including both major features<br>
like templates and just day-to-day quality-of-implementation stuff like the<br>
common-type logic of the conditional operator. And finally, my callers<br>
still have undefined behavior, and I really need to go audit all of them<br>
to make sure they're using the same sort of typedef. This is not a reliable<br>
solution to the bug.<br>
<br>
Furthermore, the compiler doesn't really care whether the pointer is<br>
abstractly aligned independent of any access to memory. There aren't very<br>
many interesting alignment-based optimizations on pointer values as mere<br>
values. In principle, we could optimize operations that cast the pointer<br>
to an integral type and examine the low bits, but those operations are not<br>
very common, and when they're there, it's probably for a good reason;<br>
that's the kind of optimization is very likely to just create miscompiles<br>
without really showing any benefit.<br>
<br>
Therefore, I would like to propose that Clang formally adopt a significantly<br>
weaker language rule for enforcing the alignment of pointers. The basic<br>
idea is this:<br>
<br>
It is not undefined behavior to create a pointer that is less aligned<br>
than its pointee type. Instead, it is only undefined behavior to<br>
access memory through a pointer that is less aligned than its pointee<br>
type.<br>
<br>
That is, the only thing that matters is the type when you actually perform<br>
the access, not any type the pointer might have had at some earlier point<br>
during execution.<br>
<br>
Notably, I believe that this rule doesn't require any changes in our<br>
current behavior, so adopting it is just a restriction on future compiler<br>
optimization. For the most part, LLVM IR only attaches alignment to loads,<br>
stores, and specific intrinsics like llvm.memcpy; there is no way to say<br>
that a pointer value is expected to have a particular alignment. The<br>
one exception that I'm aware of is that an indirect parameter can have<br>
an expected alignment. However, Clang currently only sets this for<br>
by-value arguments that the calling convention says to pass indirectly,<br>
and that remains acceptable under this new rule because it's an ABI rule<br>
rather than a constraint on programmer behavior (other than assembly<br>
programmers). The rule just means that we can't start setting it on<br>
arbitrary pointer parameters.<br>
<br>
It is also a very portable rule; I'm not aware of any compilers that do<br>
try to take advantage of the formal alignment of pointer values independent<br>
of access.<br>
<br>
The key question in this new rule is what counts as an "access". I'll spell<br>
this out in more detail, but it's mostly intuitive: anything that ultimately<br>
requires a load or store. The only thing that's perhaps questionable is that<br>
we'd like to treat calls to library functions that access memory as if they<br>
were direct accesses to their arguments. For example, we'd like to assume<br>
that the pointer arguments to memcpy are properly aligned for their types<br>
(that is, their explicit types, before the implicit conversion to void*) so<br>
that we can generate a more efficient copy operation. This analysis<br>
currently relies on the language rule that pointers may not be misaligned;<br>
preserving it requires us to treat calls to library functions as special,<br>
which of course we already do. Programmers can still suppress this<br>
assumption by explicitly casting the arguments to void*.<br>
<br>
Here's the proposed new rule, expressed more formally:<br>
<br>
---<br>
<br>
It is well-defined behavior to construct a pointer to memory that<br>
is less aligned than the alignment of the pointee type (if a complete<br>
type). However, it is undefined behavior to “access” an expression that<br>
is an r-value of type T* or an l-value of type T if T is a complete type<br>
and the memory is less aligned than T.<br>
<br>
An r-value expression of pointer type is accessed if:<br>
- it is dereferenced (with *) and the resulting l-value is accessed,<br>
- it is implicitly converted to another pointer type and the<br>
result is accessed,<br>
- it undergoes pointer addition and the result is accessed,<br>
- it is passed to a function in the C standard library that is known<br>
to access the memory,<br>
- in C++, it is converted to a pointer to a virtual base, or<br>
- in C++, it is explicitly cast (other than by a reinterpret_cast) to<br>
a related class pointer type and the result is accessed.<br>
<br>
An l-value expression is accessed if:<br>
- it undergoes an lvalue-to-rvalue conversion (i.e. it is loaded),<br>
- it is the LHS of an assignment operator (including the<br>
compound assignments),<br>
- it is the base of a member access (with .) and the resulting l-value<br>
is accessed (recall that x->y is defined as ((*x).y),<br></blockquote><div><br></div><div>I think this is overreaching. The member access has undefined behavior if there isn't an object of the right type designated by the lvalue, which is a much stronger requirement than that the alignment holds (if the base is misaligned, you still get immediate UB, even with your proposed change, because there is no object present at that misaligned location).</div><div><br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
- it undergoes indirection (with &) and the resulting pointer is accessed,<br>
- in C++, it is implicitly converted to be an l-value to a base type<br>
and the result is accessed,<br></blockquote><div><br></div><div>Again, you get UB in the conversion if there's not an actual object present.</div><div><br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
- in C++, it is converted to be an l-value of a virtual base type,<br>
- in C++, it is used as the "this""" argument of a call to a<br>
non-static member function, or<br>
- in C++, a reference is bound to it (which includes explicit<br>
casts to reference type).<br>
<br>
These are the cases covered by the language standard. There is a<br>
very long tail of other kinds of expression that obviously access memory,<br>
like the atomic and overflow builtins, which I can't reasonably enumerate.<br>
The intent should be obvious, but I'm willing to spell it out in other<br>
cases where necessary.<br>
<br>
Note that this definition is *syntactic*, meaning that it is expressed<br>
in terms of the components of a single statement. This means that an<br>
access that might be undefined behavior if written as a single statement:<br>
highlyAlignedStruct->charMember = 0;<br>
may not be undefined behavior if split across two statements:<br>
“char *member = &highlyAlignedStruct->charMember;<br>
*member = 0;<br>
In effect, the compiler promises to never propagate alignment assumptions<br>
between statements through its knowledge of how a pointer was constructed.<br>
This is necessary in order to allow local workarounds to be reliable.<br>
<br>
Note also that this definition does not propagate through explicit casts,<br>
other than class-hierarchy casts in C++. Again, this is a deliberate<br>
choice to make misalignment workarounds more straightforward.<br>
<br>
But note that this rule does still allow the compiler to make stronger<br>
abstract assumptions about the alignment of C++ references and the<br>
"this" pointer.</blockquote><div><br></div><div>It seems like this is a subset of your proposed rule:</div><div><br></div><div>The result of casting a pointer of one type to a pointer of another type is a pointer to the original object, and (after some series of pointer casts) may be used to access that object (or things that are permitted to alias it) even if some intermediate pointer type has an alignment requirement that the object does not satisfy.</div><div><br></div><div>I certainly support that subset. I think it's reasonable for us to guarantee that object pointer values will round-trip through any series of casts through object pointer types (and intptr_t) so long as you end up with the right type (a type that is alias-compatible with the original type) before you perform the access.</div><div><br></div><div>Your above proposal seems to also make a collection of other cases valid, where the problem is something other than misalignment. For instance, it sounds like you also want to make pointer arithmetic valid when there is no underlying array, and perhaps when the arithmetic leaves the underlying complete object entirely?</div></div></div></div>