GCC Bugzilla – Bug 27336
"this" pointer is not assumed to be not null
Last modified: 2006-11-08 01:05:09 UTC
I noticed that GCC tends to litter the assembly code with null checks and jumps (especially for dynamic casts) even when the pointer cannot be null. This is especially true for "this": unless I am mistaken, calling a nonstatic member with "this" not pointing to an object of the correct type (or a derived type) is undefined behavior. So GCC should assume it is not null. I tried the following testcase with 3.4.6, 4.0.3, and 4.1.0; GCC was never able to optimize the return value to "true" when compiling with -O3. struct A { bool g(); }; bool A::g() { return this; }
Confirmed. The frontend needs to tell the middle-end that the argument is non-NULL. Like by making the methods __attribute__((nonnull(1))).
I tried setting the nonnull attribute, it indeed allowed the optimization. In particular, codes containing dynamic casts are now straight lines. This is a nice improvement. Unfortunately GCC was not able to go further and use this information in the caller in order to optimize it: struct A { bool g() __attribute__((nonnull)); } bool f(A *a) { a->g(); return a; } Am I expecting too much from the nonnull attribute? (The documentation does not seem to cover this point.) Or would it be reasonnable for the middle-end to implement such an optimization?
VRP could extract this information just like it does for loads in void bar(int); int foo(int *i) { bar(*i); return i == NULL; }
Re. comment #2 and comment #3, yes you are expecting too much of the nonnull attribute. The attribute only applies to function arguments, not to function results.
Ehm, right, ignore comment #4. Yes it is possible. No, it's not very practical. Your code looks like, bool f(A *a) { g(a); return a; } to the middle end. It would take a significant amount of extra work to walk through all formal and actual argument lists in a CALL_EXPR to find "attribute nonnull"-arguments in the callee argument list. I'm not sure that's worth the cost.
Though it's also not hard to teach VRP to do this.