Sujet : Re: transpiling to low level C
De : antispam (at) *nospam* fricas.org (Waldek Hebisch)
Groupes : comp.lang.cDate : 17. Dec 2024, 19:46:00
Autres entêtes
Organisation : To protect and to server
Message-ID : <vjsgt6$32kfa$1@paganini.bofh.team>
References : 1 2 3 4 5 6 7 8 9 10
User-Agent : tin/2.6.2-20221225 ("Pittyvaich") (Linux/6.1.0-9-amd64 (x86_64))
bart <
bc@freeuk.com> wrote:
If you try to extract any meaning, it is that any control flow can be
expressed either with 'goto' or with 'recursive functions'.
This is what I picked up on. Who on earth would eschew 'goto' and use
such a disproportionately more complex and inefficient method like
recursive functions?
Due to silly conding standard? Or in language that does not have
'goto'.
How would you even express an arbitrary goto from random point X in a
function to random point Y, which may be inside differently nested
blocks, via a recursive function?
AFAICS in C main limitation is that you either pass all variables
as parameters (ugly and verbose) or use only global variables
(much worse than 'goto'). The following silly example shows
that 'if' can be simulated using array of function pointers and
indirect calls:
static int bar(int a) {
return a + 1;
}
static int baz(int a) {
return 2*a;
}
int
silly(int a) {
int (*t[2])(int) = {bar, baz};
return (*t[!!(a > 3)])(a);
}
If you compile it with 'gcc -S -O2' you can see that actually there
are no function calls in generated code (but generated code is clearly
crappy). However, needed optimication is really simple, so
in principle any compiler could do better. OTOH code like
this is rare in practice, so probably compiler writers did not
bother.
In similar way one can simulate dense C 'switch'.
Main point is that function call at the end of say 'F' to function
'G' which retruns in the same way as 'F' can be compiled to some
stack shuffling + goto (this is called 'tail call optimization').
IIUC at least some Scheme and ML compilers keep calls in intermediate
level representation (both have no 'goto') and convert them to
jumps only when emiting machine code.
Similar thing was used by one disassembly system: it generated "high
level code" by converting all jumps in machine code to function
calls. Later the result was cleaned up by transformations, in
particular recursion elimination.
Of course, for orginal purpose of this thread replacing 'if' by
indirect calls is useless
-- Waldek Hebisch