terralang / terra

Terra is a low-level system programming language that is embedded in and meta-programmed by the Lua programming language.
terralang.org
Other
2.72k stars 201 forks source link

WebAssembly (wasm32/64) Calling Convention Fix #616

Closed PyryM closed 2 years ago

PyryM commented 2 years ago

Fixes, under wasm32- and wasm64- triples, how terra passes aggregates by value, to match clang/emscripten.

WebAssembly only passes single-value structs directly in registers [1], all other structs (and all arrays) are passed indirectly.

It would be nice to have tests for this but I'm not really sure how to go about creating them without pulling in a webassembly VM or Emscripten as dependencies. This does allow my terra->wasm code to link against clang/Emscripten compiled libraries, for what it's worth.

[1] https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md

elliottslaughter commented 2 years ago

Thanks for this. Looks like it needs a pass with ./format.sh (our script for running clang-format) but otherwise it seems good. (You can alternatively apply the diff here: https://github.com/terralang/terra/actions/runs/3258063774/jobs/5356116213 )

I agree that fully testing WASM seems like a lot of work. Though maybe I'm wrong about that if Emscripten emulates enough APIs to make things mostly work. I am not against this in principle, but if it's dramatically more work or becomes a burden on the CI then it may not be worth the effort.

I've thought about ways to test cross-compiled calling conventions, but I don't really have any solutions right now. In principle, it might be enough to compare what Terra emits (at the LLVM IR level) to Clang, but (a) that seems hard / brittle, and (b) I'm pretty sure it'll be too strict in some cases. Multiple LLVM IR patterns map to the same assembly output, so in general I haven't bothered to make Terra match Clang beyond what's required to make it usable (because sometimes the Clang output can be quite convoluted).

elliottslaughter commented 2 years ago

Thanks again!

I'm happy to take additional PRs if you figure out a way to improve / add testing for this.