This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Comparing function pointers
- From: Bruno Haible <bruno at clisp dot org>
- To: gcc at gcc dot gnu dot org
- Cc: Andreas Jaeger <aj at suse dot de>
- Date: Sun, 15 Jun 2003 17:51:23 +0200
- Subject: Comparing function pointers
Hi,
In gccsummit2003-proceedings.pdf p. 116 Andreas Jaeger writes that on IA-64
the result of comparing function pointers is unspecified. He explains it
by saying that a function pointer is actually a pointer to a
struct function_descriptor {
void* code_addr;
void* gp_value;
}
He goes on to recommend to avoid comparing function pointers in portable
programs.
But programmers are justified in comparing function pointers. ISO C 99
specifies exactly what comparing function pointers should do:
(ISO C 99 section 6.5.9.6)
"Two pointers compare equal if and only if both are null pointers,
both are pointers to the same object (...) or function,
both are pointers to one past the last element of the same array object,
or one is a pointer to one past the end of one array object and the
other is a pointer to the start of a different array object that happens
to immediately follow the first array object in the address space."
I.e. the comparison of two function pointers must return true if and only if
they point to the same function.
So it is actually a bug in gcc. Where gcc currently compares function
pointers like this
bool equals (struct function_descriptor *fp1, struct function_descriptor *fp2)
{
return fp1 == fp2;
}
it should use a comparison function like this:
bool equals (struct function_descriptor *fp1, struct function_descriptor *fp2)
{
return fp1 == fp2
|| (fp1 != NULL && fp2 != NULL && fp1->code_addr == fp2->code_addr);
}
Then there would be no reason any more to recommend to avoid comparing
function pointers.
Bruno
------------------------------------------------------------------------
Appendix: How to reproduce:
$ cat foo.c
typedef int (*function)(int,int);
int equals (function fp1, function fp2) { return fp1 == fp2; }
$ gcc -O2 -S foo.c
$ cat foo.s
.file "foo.c"
.pred.safe_across_calls p1-p5,p16-p63
.text
.align 16
.global equals#
.proc equals#
equals:
.prologue
.body
.mfb
cmp.eq p6, p7 = r33, r32
nop.f 0
nop.b 0
;;
.mib
(p6) addl r8 = 1, r0
(p7) mov r8 = r0
br.ret.sptk.many b0
.endp equals#
.ident "GCC: (GNU) 3.2.2"
You see, this code compares the function descriptor addresses, not
the code addresses.