4 ms·
Determining local variable lifetimes is a fundamental feature of a compiler. Literally any compiler that does register allocation can and will merge local varia
by 10000truths 5y ago
Determining local variable lifetimes is a fundamental feature of a compiler. Literally any compiler that does register allocation can and will merge local variables that aren't simultaneously live. Because it turns out that the problem of fitting lots of variables into minimum registers is remarkably similar to the problem of fitting lots of variables into minimum registers + minimum stack space.
So yes, you can confidently rely on gcc or clang to merge local variables, even at -O1. If they suddenly don't do that after an update, it's a serious regression, and their mailing lists should be more than happy to receive that bug report.
- tsimionescu 5y agoFor local variables. Once you're passing the data around to other functions, the problem becomes much more complex, and it becomes much less clear when and why the compiler will be able to understand what's happening. Not to mention, in an example like processing packets, the two views of the data WILL be simultaneously live: you're taking raw bytes on one side, interpreting some part of them as a struct to decide what's happening next, then sending the raw bytes somewhere else. EDIT: Basically the code would look something like this: char* buf = new char[100]; read(buf, sizeof(header)); header h; memcpy(&h, buf, sizeof(header)) get_destination(h).write(buf); Will this copy the header or not? How about this? char* buf = new char[100]; read(buf, sizeof(header)); header *h = reinterpret_cast<header*>(buf); //assume we are compiling with "-fno-strict-alias", and that we know there are no alignment/packing concerns get_destination(h).write(buf); Also note that in C we have a somewhat cleaner solution: union buf_header { header h; char buf[100]; } buffer; read(buffer.buf, sizeof(header)); get_destination(buffer.h).write(buffer.buf); This would of course be UB in C++ (reading from a union member that is not the last one written to).
- ncmncm 5y agoIt is perhaps worth noting that G++ specifically provides a C-compatible definition for the final example. As they are allowed to do.
- gpderetta 5y agoBut, assuming header is a standard layout type, the following: header h; read((char*)&h, sizeof(h)); get_destination(h).write((const char*)&h, sizeof(h)); Is well defined even under strict aliasing. (agree about the two views being live at the same time and memcpy being suboptimal here).