Object and struct member access and address offset calculation
Asked Answered
S

1

2

I am writing a simple VM and I have a question on implementing object and structure member access.

Since the begin address of a program is arbitrary on each run, and subsequently the address of each and every of its objects is arbitrary too.

Thus the only way I can think of to access an object or its member object is by accessing an offset from the "base" pointer, which means there is an arithmetic operation needed to access anything in a program structure.

My question is whether this is the way it is done in professional compilers, because obviously this approach adds some overhead to the runtime, and I myself can't think of any way to offload this process from the runtime because of the lack of guarantees for consistency of memory allocation and its address?

Stowe answered 15/7, 2012 at 6:57 Comment(0)
Q
2

Most computers for many decades provide addressing modes that let you specify the address as a combination of a base and an offset, and the actual calculation is carried out in the hardware for no additional cost in CPU clock cycles.

More recent (past few decades) computers offer hardware for virtualizing memory layout, meaning that even through the physical address of an item is different on every run, its address in the virtual address space remains the same. Again, there is no additional cost for using the base address, because the calculations are performed implicitly and invisibly to the executing binary code of a program.

Queenie answered 15/7, 2012 at 7:4 Comment(2)
Thanks. Is this mechanism platform specific or perhaps there is a standardized portable solution? Can you provide any link to information how to take advantage of this feature? Or perhaps a C/C++ implementation?Stowe
@ddriver Addressing modes are CPU-specific. They are not available to C/C++ programmers directly - the compilers take advantage of them while converting your code to assembly (array indexing has been done as base+offset since at least PDP-11 days). For example, if your write int *p = getPointer(); int x = *(p+5), most compilers will generate a very efficient access that does not involve performing addition of five or multiplication by the size of int. A single CPU instruction will be issued to do the "base + offset" addressing.Queenie

© 2022 - 2024 — McMap. All rights reserved.