Apart from Dll concept that provides ability of loading/unloading methods or functions at run-time, I'm wondering if a compiler may ever say something like, ok as this particular part of the code takes considerable amount of space in code segment and is never gonna be used again after this point during program execution, it'd be good to generate some code to unload that part of code segment after reaching that particular point during program execution so that overall space took by code segment gets smaller. Is it something just fictional or may that happen?
views:
82answers:
4I don't know of a compiler which does this, but there's no rule prohibiting it. If the compiler can prove that doing so won't change the semantics of the program, then it is allowed under the as-if rule.
It is usually not necessary however, because unused code can already get swapped out as part of the pagefile mechanism associated with virtual memory. (and because you'd probably only save a few KB of memory space)
Sure. There's a technique called overlaying that loads different code into the same bit of address space at different times. Sometimes it was done manually, other times compilers helped. Sometimes the loading is done in software, sometimes in hardware (with address multiplexing, so that e.g. during boot time one bit of address space reads from a ROM chip, but after boot it switches to address RAM or a different ROM instead).
Overlaying was much more common when computers had less memory, e.g. in the early days of DOS where you had 640K at best and often not even that. These days it still has applications for embedded systems where memory and/or address space are at a premium.
A compiler can do anything it wants to, as long as that doesn't violate the standard. If it can figure out that the code is never called again, it can ditch it completely.
It could even replace it with a smaller stub function that would reload the code, were it required.
But you'll be very unlikely to ever see that in a modern OS since the OS itself provides that capability under the covers.
Operating systems (at least the common ones) will swap out your physical pages when memory runs low, and they won't be reloaded until they're needed (usually by a page fault when trying to access them).
Yes, Windows Device Drivers use this technique. The LE file format has certain code segments marked as discardable. The OS can also certain times take such a decision to swap out code segments that have not been used for a long time.
Stricly speaking however, this is not the area for compiler to play around with. It is mostly the linker/loader/OS that affect this.