On 05/15/2017 04:39 AM, Prathamesh Kulkarni wrote:
Hi,
I have attached a bare-bones prototype patch that propagates malloc attribute in
ipa-pure-const. As far as I understand, from the doc a function could
be annotated
with malloc attribute if it returns a pointer to a newly allocated
memory block (uninitialized or zeroed) and the pointer does not alias
any other valid pointer ?
* Analysis
The analysis used by the patch in malloc_candidate_p is too conservative,
and I would be grateful for suggestions on improving it.
Currently it only checks if:
1) The function returns a value of pointer type.
2) SSA_NAME_DEF_STMT (return_value) is either a function call or a phi, and
SSA_NAME_DEF_STMT(each element of phi) is function call.
3) The return-value has immediate uses only within comparisons (gcond
or gassign) and return_stmt (and likewise a phi arg has immediate use only
within comparison or the phi stmt).
ISTM the return value *must* be either the result of a call to a
function with the malloc attribute or NULL. It can't be a mix of
malloc'd objects or something else (such as a passed-in object).
malloc_candidate_p would determine f to be a candidate for malloc
attribute since it returns the return-value of it's callee
(__builtin_malloc) and the return value is used only within comparison
and return_stmt.
However due to the imprecise analysis it misses this case:
char **g(size_t n)
{
char **p = malloc (sizeof(char *) * 10);
for (int i = 0; i < 10; i++)
p[i] = malloc (sizeof(char) * n);
return p;
}
I suppose g() could be annotated with malloc here ?
I think that's up to us to decide. So the question becomes what makes
the most sense from a user and optimization standpoint.
I would start relatively conservatively and look to add further analysis
to detect more malloc functions over time. You've already identified
comparisons as valid uses, but ISTM the pointer could be passed as an
argument, stored into memory and all kinds of other things.
You'll probably want instrumentation to log cases where something looked
like a potential candidate, but had to be rejected for some reason.
Jeff