Eigenstate: myrddin-dev mailing list

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Pointer arithmetic and iterations


On Mon, 4 Dec 2017 10:33:25 +0800, nml <arumakanil@xxxxxxxxx> wrote:

> Hi,
> 
> Myrddin doesn't seem to support pointer arithmetic.
> What is the idiomatic way to express the following C code? Any examples?
> 
> typedef void (*initfn_t)(void);
> > extern initfn_t  *__init_start__;
> > initfn_t fp;
> > for (fp = __init_start__; fp < __init_end__; fp++) {
> >     fp();
> > }

You can take slices off of pointers, if you need to iterate over arbitrary
chunks of memory. Computing the size of the slice is a bit more involved,
since you don't have a length off-hand, and you need to compute it:

	extern const __init_start__ : (-> void)#
	extern const __init_end__ : (-> void)#

	/* compute count */
	var n = ((__init_end__ : std.intptr) - (__init_start__) : std.intptr))/sizeof((-> void))
	for fp : __init__start[:n]
		fp()
	;;

Note that function pointers in Myrddin are 'fat', and come with an
environment, so they're 16 bytes. If they don't capture anything,
as is the case with __init__ (or any other global function), then
it's safe to pass anything there.

So, the naive way of implementing this would generate the following
data for the init funcs:

     .quad 0 /* env */
     .quad __init__$stuff /* func */
     .quad 0 /* env */
     .quad __init__$morestuff /* func */
     ...

With care, you might be able to be a bit more clever with packing it,
but I'll leave that as an puzzle for after the simple generated code
is working :)

-- 
    Ori Bernstein

References:
Pointer arithmetic and iterationsnml <arumakanil@xxxxxxxxx>