3 ms·
Function pointers in a union? Now that's a first (for me). One of my coworkers could defeat any idea for a new optimization with "well, what about unions?" whi
by ndesaulniers 7y ago
Function pointers in a union? Now that's a first (for me).
One of my coworkers could defeat any idea for a new optimization with "well, what about unions?" which would typically complicate things quickly...
- saagarjha 7y ago> One of my coworkers could defeat any idea for a new optimization with "well, what about unions?" which would typically complicate things quickly... I'm not sure I follow: they would thwart your attempts at optimizing things by talking about unions?
- kazinator 7y agoCompilers that allow type punning through a union have to basically consider the access to a member of the union to have an effect on any other member. It's conceivable that there are edge cases where that consideration could hamper the optimization of a code which uses unions without perpetrating any sort of type punning. Hmm, like what? Say we have a really contrived function that works with two pointers A and B to the same union type. The compiler cannot prove that A and B are distinct. The function evaluates A->x = expr, and also B->y in several places. Since A and B might be the same pointer, the assignment has to be regarded as clobbering B->y, which interferes with CSE of B->y and register caching. As of C99, a possible solution here would be to declare the pointers restrict; then the compiler assumes they don't overlap: A->x has nothing to do with B->y. If a struct is used, then x and y are different members and have nothing to do with each other for that reason, needless to say, even if A and B are the same pointer.
- TeMPOraL 7y agoGiven that this is C, can the compiler prove in any case that two pointers are distinct? When you're dealing with a structure, it could still be the case that A = B + sizeof(structure.x) (+/- padding).
- kazinator 7y agoHere, the union is being used as a space-saving structure. We only need to store one pointer, but it can be of different types. We access the same one that we most recently stored. Most of the code surrounding this won't contain assignments into the union, so it won't impact optimization. In an interpreted language I wrote this kind of union is initialized when a function object comes to life, and then not mutated again. The union is necessary because a struct would blow up the size of the object significantly (and then it wouldn't fit into the GC heap cell size, requiring an additional piece of malloced memory).