How can I apply GCC's/Clang's __restrict__
qualifier to the this
pointer of a class?
This question was inspired by Richard Powell's CppCon 2018 talk, "How to Argue(ment)." I saw a similar question "restrict qualifier on member functions (restrict this pointer)." (All code can be found on Compiler Explorer)
void bar();
class Foo {
public:
int this_example() const {
if (value > 0) {
bar();
return value;
} else {
return value;
}
}
private:
int value;
};
The above code generates the following assembly. In it, we can see that value
has to be loaded twice, via the this
pointer. This makes sense, it is a consequence that C++ inherited from C and the restrict qualifier allows the programmer to turn off the behavior. I can find no way to enable the restrict
functionality for the this
pointer.
Foo::this_example() const: # @Foo::this_example() const
push rbx
mov eax, dword ptr [rdi]
test eax, eax
jle .LBB2_2
mov rbx, rdi
call bar()
mov eax, dword ptr [rbx]
.LBB2_2:
pop rbx
ret
On the Compiler Explorer page, I show examples of method arguments using __restrict__
to elide the second load. There is also an example of passing a struct reference to a function and using __restrict__
to elide the second load.
I can imagine a world where the compiler would allow the programmer to mention the implicit this
pointer in the arguments of a method. The compiler could then allow application of qualifiers to the this
pointer. See code below for an example.
class Foo {
public:
int unrestricted(Foo *this);
int restricted(Foo *__restrict__ this);
};
As a follow up question, is there something in the C++ standard or a C++ guideline that would make it so that this
could never have the restrict qualifier?