goto [variable], and address of code labels
bcs
bcs at example.com
Sat Oct 29 09:03:20 PDT 2011
On 10/28/2011 09:30 AM, 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...
>
>
> Simple example:
>
> void *opcodes[] = { &OP_ADDA, &OP_SUBA, &OP_MOVA, &OP_JMPA, &OP_etc... };
>
> void exec()
> {
> // 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[ ];
>
> 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.
>
> Note, GCC code labels are void*, but in D, perhaps some special code
> label pointer type should be invented for type safety...
> 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.
For the given example, this could be re-cases via a switch statement
that ends each case with a "goto case pProgram[regs.PC++];". That is
assuming non-const expression are allowed as the expression. The end
result should be identical.
More information about the Digitalmars-d
mailing list