Reputation: 349
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?
Upvotes: 3
Views: 717
Reputation: 26186
GCC's documentation for __restrict__
(as well as the linked question) mentions that you can actually restrict this
:
You may also specify whether a member function’s
this
pointer is unaliased by using__restrict__
as a member function qualifier.void T::fn () __restrict__ { /* … */ }
Within the body of
T::fn
,this
has the effective definitionT *__restrict__ const this
. Notice that the interpretation of a__restrict__
member function qualifier is different to that ofconst
orvolatile
qualifier, in that it is applied to the pointer rather than the object. This is consistent with other compilers that implement restricted pointers.
Note, however, that marking the this
pointer as such does not prevent the second load.
Upvotes: 3