3 ms·
Why does the function declare which parameters are "comptime"? Recently, I was thinking about a language, where the user could decide which parameters to make
by qznc 10y ago
Why does the function declare which parameters are "comptime"?
Recently, I was thinking about a language, where the user could decide which parameters to make comptime. Examples:
Normal function call: foo(a, b)
Function call with comptime: foo(comptime 42, b)
What actually happens at runtime: fooVariant(b)
The compiler makes a duplicate of foo, where the first parameter is removed and the constant 42 used instead. Compiler writers may know this as the transparent "procedure cloning" optimization.
This increases flexibility, because the writer of a function does not have to decide which parameters are comptime and which are not. This sometimes leads to duplications, for example with regular expressions, where the pattern is very often comptime, but not always.
- skissane 10y agoOne issue I see is how far to propagate the comptime? If I have one complex function which calls 50 other functions, do I clone all of them too? And what about functions called indirectly? The amount of cloning could become massive, and it might lead to worse performance (e.g. so much code is cloned that the code no longer fits in the CPU caches.) Conversely, if I am only cloning the function I am calling, then that might not be a very useful feature, because the function I am calling might do very little – it might just be a thin wrapper around another function. The advantage of doing it on the function parameter declaration is the function author has to work out the propagation aspect themselves (by deciding whether to make the arguments of the indirectly called functions comptime or not.)
- DannyBee 10y ago"Why does the function declare which parameters are "comptime"? " Because it's at least exponential time and space otherwise, and sometimes much more :) (becasue you may have to duplicate the entire call path rooted at foo)
- ttd 10y agoSomething similar is "partial evaluation", and LLVM (for example) supports it via a component called LLPE [1,2]. One of its main drawbacks is it falls under the category of interprocedural optimization (as opposed to intraprocedural) which can quickly balloon into a practically intractable problem for large programs. Also, it's just difficult to imagine it working in many non-cherry-picked examples. You have to prove that a given parameter is constant over all callsites to a function, which can be difficult e.g. in the presence of indirect/virtual function calls. [1] http://www.llpe.org/ http://www.llpe.org/ [2] http://llvm.org/devmtg/2015-04/slides/LLPE.pdf http://llvm.org/devmtg/2015-04/slides/LLPE.pdf