miscompilation of calls to __attribute__((pure)) virtual functions
| Bugzilla Link | 12758 |
| Version | unspecified |
| OS | Linux |
| CC | @DougGregor,@belkadan |
Extended Description
Consider this code:
struct B { virtual void f() __attribute__((pure)); };
struct D : B { void f(); };
void f(B *p) { p->f(); }
void g() { D b; f(&b); }
Here, B::f() is __attribute__((pure)), but D::f() is not. g++ emits a virtual call within ::f(), but Clang does not. Likewise, g++ emits a call to D::f() within ::g(), but Clang does not.
The GCC docs don't explicitly state what should happen here, but they do say that 'pure' is a property of the function itself, which suggests that g++ is right and clang is wrong.
I disagree. With your interpretation it would only be possible to eliminate the call if a variable was explicitly declared as "B".
That doesn't follow. We can eliminate any call which we can devirtualize to an attribute((pure)) function.
On the other hand, considering [[pure]] as part of the method signature enforces the purity for all subclasses,
But we don't enforce that, and nor does GCC. attribute((pure)) is not part of the type, and is not forced on overriding functions.
The point is, GCC defines this attribute and documents that this is a property of a function. We're treating it as if it were a property of a virtual slot, or as if it were part of a function type. Because this is a GCC attribute, we should implement the GCC semantics.
I disagree. With your interpretation it would only be possible to eliminate the call if a variable was explicitly declared as "B". I think it's rare, however, that a class with virtual functions is used non-virtually (i.e. not through a pointer or reference).
On the other hand, considering [[pure]] as part of the method signature enforces the purity for all subclasses, which lets us do CSE optimization even with a B*. I consider this equivalent to making a const virtual method -- possibly a little restrictive for subclasses, but a reasonable thing to do.
If we don't want to take this route, I would suggest a warning for using [[pure]] (or [[const]], distinct from the usual const) on virtual methods, something like "attribute((pure)) will be ignored for virtual calls".
Alternately, if we /do/ propagate [[pure]] (and [[const]]) to overrides, we might want the opposite warning: "this method may be called fewer times than expected" w/ note "virtual base method is declared __attribute((pure)) here".
(It might be worth noting that [[pure]] is fairly useless for member functions, since reading any member variables violates the "purity". GCC explicitly warns against reading through pointer arguments and this is the same thing. [[const]], however, is not only useful but used throughout the LLVM/Clang codebase on member functions as LLVM_READONLY.)
@llvm/issue-subscribers-clang-codegen
This was apparently fixed in clang 18.
I can still reproduce this: https://godbolt.org/z/346Kz33as