goto [variable], and address of code labels

Dmitry Olshansky dmitry.olsh at gmail.com
Fri Oct 28 12:16:39 PDT 2011


On 28.10.2011 20:30, Manu wrote:
> Hi people.
>
> I'd like to propose support for taking the address of code labels, and
> supporting variable goto statements.
> This is a feature I have found extremely useful, implemented as a GCC
> specific extension.
>
> I've used this to get great speedups and simplify code while writing
> emulators/vm's. Perhaps also useful in efficient state machine type code
> too...
>

Yes, mostly efficient VMs. Maybe for JIT, though it would depend on some 
hacks.
But custom made state machines usually do fixed jumps anyway.

>
> Simple example:
>
> void *opcodes[] = { &OP_ADDA, &OP_SUBA, &OP_MOVA, &OP_JMPA, &OP_etc... };
>

I gather this should be somewhere inside exec, or it will be *extremely* 
unsafe.

> void exec()
> {

i.e. :
      enum opcodes[] = { ... };

>    // begin execution
>    goto opcodes[ pProgram[regs.PC++] ];
>
> OP_ADDA:
>    regs.A += pProgram[regs.PC++];
>    goto opcodes[ pProgram[regs.PC++] ];
>
> OP_SUBA:
>    regs.A -= pProgram[regs.PC++];
>    goto opcodes[ pProgram[regs.PC++] ];
>
> OP_MOVA:
>    regs.A = pProgram[regs.PC++];
>    goto opcodes[ pProgram[regs.PC++] ];
>
> OP_JMPA:
>    regs.PC = regs.A;
>    goto opcodes[ pProgram[regs.PC++] ];
>
> OP_etc:
>    ...
>    goto opcodes[ pProgram[PC++] ];
> }
>
> Notice how this structure completely eliminates branch logic, control
> statements, etc.

Yes, but you'd still have to check correctness, maybe before executing 
the whole VM program.

>
> Note, GCC code labels are void*, but in D, perhaps some special code
> label pointer type should be invented for type safety...

Or just call them void function(void), there are cases where jumping to 
function is OK. It's some pretty low-level stuff, that most people do in 
assembly though.

> One may also expect that function pointers may also be implicitly cast
> to this generalised code pointer type, which might be useful in some
> code where a naked function pointer is used to implement some custom
> calling convention.

Overall, I'd personally welcome this kind of extension, but it's should 
be doable in inline asm even today, which somewhat diminishes it's 
impact. The advantage of computed gotos compared to asm is portability, 
the disadvantage is complicating  backend for a special case.


-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list