clang performing copy-elision in ways which break ABI aliasing rules
| Bugzilla Link | 11470 |
| Version | unspecified |
| OS | Linux |
| CC | @DougGregor,@efriedma-quic,@sunfishcode,@nlewycky,@rjmccall |
Extended Description
Consider the following:
struct foo { int a, b; double c, d, e; };
extern foo x;
foo f() { return { 1, x.a }; }
foo x = f();
Depending on what copy elision happens, x is initialized as either {1,0} or {1,1}. With the double members in struct foo, we elide all the copies and an -O0 build initializes x as {1,1}. (Without the double members, we return as i64 and get the resulting value {1,0}). However, we define f as:
define void @_Z1fv(%struct.foo* noalias sret %agg.result) nounwind uwtable {
This is wrong! %agg.result is not noalias. This results in us incorrectly assuming the write to %agg.result.a and the read of @x.a do not alias, and producing the result {1,0}. This coincidentally happens to be a legal outcome in this case, but not in general.
Another example:
struct bar {
bar(bar *o) : ok(true) {
o->ok = false;
if (!ok)
ok = true;
}
bool ok;
double make, it, bigger;
};
bar f(bar *p) {
return p;
}
int main() {
bar self_reference = f(&self_reference);
return !self_reference.ok;
}
In a compliant compiler, main must always return 0, whether we elide the copies or not. But in clang at -O3, it returns 1! This is again because we've incorrectly marked the return slot in bar as noalias.
Note that, while the above initializations have undefined behaviour for const objects, by C++11[class.ctor]p14, I believe they have well-defined behaviour in these cases, since the objects are not const.
This weaker rule is pretty weird. Copy elision is actually required now in some cases, so the practical upshot seems to be that constructors (which always construct some object directly) and functions (if they want to use NRVO) always have to assume that their result might be aliased, except that it can't be aliased by loads. So we can reorder stores to 'this', but only if we can prove that there aren't any intervening stores that might alias them.
I continue to think that we should just assume that the standard wording will eventually catch up to where we are.
Core issues 2158 and 2271 are related to this. We now have this rule:
"During the construction of an object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor’s this pointer, the value of the object or subobject thus obtained is unspecified."
This isn't quite the "behavior is undefined" rule we might like, and doesn't entirely justify some of the optimizations we might perform due to the 'noalias' annotation, but it's in the right direction.
Hello,
did you ever report this to WG21? I didn't find it in the active issues list. I found this PR while filing https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80740 in gcc.
I don't think (3) follows from the standard text. [class.copy]p31 says that there is only one object when copy elision occurs, and the first constructor constructs it. So construction of the object has begun in both cases.
Ah, yes, you're right.
However, that tweak confuses llvm's optimizer, and it no longer miscompiles this (although it still could; see llvm/llvm-bugzilla-archive#11471 ).
It theoretically could. I was under the impression that we intentionally don't use alias-analysis results to optimize pointer-equality checks.
I think this is probably a standard defect, and I'm happy to take it up with WG21; I think the right answer is for the standard to say (something like) "During the construction of an object for which copy-elision has occurred, if the value of the object or any of its subobjects is accessed through a glvalue that would not have referred to the same object had copy-elision not occurred, the value of the object or subobject thus obtained is unspecified." (This is modeled after [class.copy]p14, which also uses an unspecified value rather than undefined behavior.)
The unspecified-value language only makes sense for loads, not stores, and it also doesn't seem to say that the result of your pointer equality check is unspecified, unless that's what you mean by "the value of the object".
I kindof prefer my formalism, actually: copy elision instantaneously ends the lifetime of the source object and begins the lifetime of the destination object, with the additional rule that all pointers to the source object automatically forward to the destination object.
I don't think (3) follows from the standard text. [class.copy]p31 says that there is only one object when copy elision occurs, and the first constructor constructs it. So construction of the object has begun in both cases. (Since they're the same object, if the construction hadn't begun, any reference to the members, direct or otherwise, would be undefined behaviour).
The second example, as it stands, does have undefined behaviour, because the write to o->ok in the constructor has undefined behaviour if copy-elision doesn't happen. That's not the case if the example is tweaked:
bar(bar *o) : ok(true) { if (o == this) { o->ok = false; if (!ok) ok = true; } }
However, that tweak confuses llvm's optimizer, and it no longer miscompiles this (although it still could; see llvm/llvm-bugzilla-archive#11471 ).
I think this is probably a standard defect, and I'm happy to take it up with WG21; I think the right answer is for the standard to say (something like) "During the construction of an object for which copy-elision has occurred, if the value of the object or any of its subobjects is accessed through a glvalue that would not have referred to the same object had copy-elision not occurred, the value of the object or subobject thus obtained is unspecified." (This is modeled after [class.copy]p14, which also uses an unspecified value rather than undefined behaviour.)
Does that seem reasonable?
- It is not really obvious what it means for an object to have a non-trivial constructor. Objects have initializers. Types have constructors.
- If the rule is 'the object's type has a non-trivial constructor', then Richard's first example is valid, but his second is not. We can fix the first example by setting IsAliased more intelligently based on the sort of thing being initialized and whether it has any non-trivial constructors.
- If the rule is 'the object has a non-trivial initializer', both of these examples are invalid.
(fin)
- Therefore, elision does not affect the analysis. It is undefined behavior (or not) regardless of whether elision occurs.
- Copy/move elision is permitted (and now sometimes required). As I understand it, formally this behaves by magically blessing a 'temporary' into the destination object after the temporary's construction finishes. Therefore the object still does not actually exist until the magic blessing point at which the elided constructor would run.
- Formally, an object returned from a function must be copied/moved into place. Therefore, the entire function runs before the copy/move constructor begins execution.
- C++ makes it illegal to access an object with a non-trivial constructor in certain ways before that constructor begins execution.
(Bugzilla doesn't want to accept this comment, so I'm breaking it up)
Erk. Sorry about the confusion above. I am probably too tired to be doing this analysis, but I wanted to ward us away from the general thrust of these comments. Let me let out my argument more clearly.
test
Other places where we would have to disable elision under the suggested rule: base/member initializers, new initializers, initializer lists where we can't prove that the address of any of the earlier objects might have escaped (for example, if we called a non-trivial constructor for one).
Oh, also, none of this saves us because ultimately we do have to call a copy/move constructor.
I generally find it helpful to assume that the committee doesn't know how to write rules very effectively.
I would believe that we might not be allowed to mark constructor arguments noalias, though.
[class.cdtor] forbids accessing members or base classes of an object with a non-trivial constructor before the constructor begins executing. It's not totally clear how this interacts with copy/move elision, nor is it clear how you decide what objects have non-trivial constructors. I would claim, however, that copy/move elision cannot make a program's behavior more defined, and that an object has a non-trivial constructor according to whether its initializer is non-trivial. So I think actually both of your examples are undefined behavior.
Also, I understand that language rules are language rules, but disabling copy/move elision completely for all global objects would be horrific.
Okay; CodeGenFunction::EmitExprAsInit is the relevant code; note the use of AggValueSlot::IsNotAliased.
OK, that makes sense. In that case, we can't do copy elision on at least
- globals with external linkage
- automatic variables whose address is used in their initializer
(That is, any case where the address of the variable might be visible in the initializer)
The sret slot is supposed to be noalias; the x86-64 ABI, for example, has that as a requirement. If there is some scenario where it does alias something, it means that either the code has undefined behavior or we're illegally eliding a copy.
@llvm/issue-subscribers-clang-codegen
Author: None (ec04fc15-fa35-46f2-80e1-5d271f2ef708)
Extended Description
Consider the following:
struct foo { int a, b; double c, d, e; }; extern foo x; foo f() { return { 1, x.a }; } foo x = f();
Depending on what copy elision happens, x is initialized as either {1,0} or {1,1}. With the double members in struct foo, we elide all the copies and an -O0 build initializes x as {1,1}. (Without the double members, we return as i64 and get the resulting value {1,0}). However, we define f as:
define void @​_Z1fv(%struct.foo* noalias sret %agg.result) nounwind uwtable {
This is wrong! %agg.result is not noalias. This results in us incorrectly assuming the write to %agg.result.a and the read of @​x.a do not alias, and producing the result {1,0}. This coincidentally happens to be a legal outcome in this case, but not in general.
Another example:
struct bar { bar(bar *o) : ok(true) { o->ok = false; if (!ok) ok = true; }
bool ok; double make, it, bigger; };
bar f(bar *p) { return p; }
int main() { bar self_reference = f(&self_reference); return !self_reference.ok; }
In a compliant compiler, main must always return 0, whether we elide the copies or not. But in clang at -O3, it returns 1! This is again because we've incorrectly marked the return slot in bar as noalias.
Note that, while the above initializations have undefined behaviour for const objects, by C++11[class.ctor]p14, I believe they have well-defined behaviour in these cases, since the objects are not const.
Still present on current toolchains (arm64-apple-darwin host): clang 22.1.8, 23.1.4, and Apple clang 21.0.0 all miscompile the self-reference example from the description at -O1 and above; -O0 is correct. The first example (global initializer reading x.a) now produces the correct {1,1} on all three, so the live surface is exactly the self-referencing-elision case. GCC 16.1 miscompiles the same example at -O2/-O3 as well (the GCC side of this family was filed as gcc 80740 upthread).
Since the description already pins this on noalias on the sret parameter, here is a frontend-free, single-variable demonstration at the IR level:
define void @bar_ctor(ptr %this, ptr %o) {
entry:
store i8 1, ptr %this, align 8
store i8 0, ptr %o, align 8
%v = load i8, ptr %this, align 8
%.not = icmp eq i8 %v, 0
br i1 %.not, label %set, label %end
set:
store i8 1, ptr %this, align 8
br label %end
end:
ret void
}
define void @f(ptr noalias sret(i8) %dest, ptr %o) {
entry:
call void @bar_ctor(ptr %dest, ptr %o)
ret void
}
define i32 @main() {
entry:
%d = alloca i8, align 8
call void @f(ptr sret(i8) %d, ptr %d)
%r = load i8, ptr %d, align 8
%c = icmp eq i8 %r, 0
ret i32 %c
}
opt -O2 folds main to ret i32 1 (wrong); deleting only the noalias on %dest folds it to ret i32 0 (correct). For completeness, the IR clang itself emits for the C++ example passes the same pointer as both the sret destination and the other argument (call void @_Z1fP3bar(ptr sret(%struct.bar) %2, ptr %2)), so the module violates the noalias its own callee carries — the 2023-era IR quoted in the description, restated on 22/23.
So under guaranteed copy elision the miscompile is entirely attributable to noalias on sret parameters: the returned prvalue is constructed directly into the destination, nothing prevents the initializer from naming that same object, and the sret slot may legitimately alias pointers reachable from the other arguments. dead_on_unwind doesn't help. That matches the conclusion reached upthread in 2011/2017 (rjmccall's "we might not be allowed to mark constructor arguments noalias" / efriedma's x86-64 ABI remark); 15 years on, both clang and GCC still optimize on the unsound assumption.