Original Post
I'm curious if anyone knows whether a constant function pointer (that is, a function pointer which always points to the same area in memory) can be optimized away? The reason for this rather wierd construct would be for use in self-modifying code. A static code buffer would exist which would be filled with machine code output by an embeddable assembler/compiler (such as SoftWire) which would be specific to a certain use case. The contents of the code buffer would change as the case changes, but the buffer itself would not move. Obviously, using new or malloc would disallow this type of optimization since the buffer would not be at a consistant offset in the application. To get around this, the Code buffer must be a static byte array (or somesuch) within the data section of the executable in the same way that global variables or the string table would be. This code buffer would be over-written with a valid instruction sequence and its address cast as a function pointer for execution. Ultimately, the question comes down to this: Given a consistant location in memory, is the compiler smart enough to treat that memory location, when cast as a function pointer, in such a way as would remove the function pointer indirection? This would essentially make the code buffer equivilant to a regular function who's contents just happen to have changed. Failing that, is it possible to create a function of an arbitrary size, and then overwriting its code with new code to provide the same benefits, namely the loss of the pointer indirection? I'm using C/C++ and I'm aware of the calling convention issues, etc. Just curious to know if the function pointer overhead can be eliminated. Normally I wouldn't worry about it, however my use requires many calls (potentially thousands) to this function per frame while the state of the function changes infrequently (perhaps 2-4 times per frame.) Moving the dynamic behaviour out of call-time and into the state change should prove a win.