by turbinerneiter · 6y ago · 0 comments
Can wasm be optimized as much as llvm? Just wondering if we could have just put llvm in the browser.
Other commenters are correct that LLVM IR has more information in it than WebAssembly, but that is working as intended. The idea is that toolchains will do the heavy optimization work so that WebAssembly engines can be simpler and just do the final code generation.
[1] https://developer.chrome.com/native-client/nacl-and-pnacl
In contrast, LLVM IR is designed to be cpu- and OS-specific. Take a look at the very first line in the example: ‘target triple = "i386-pc-linux-gnu"’. Decidedly not web-friendly, though perhaps you could try to make a web triple?
The target triple isn't actually relevant in this demo, try setting it to "42" and it will still compile and run. For documentation so you know I'm not just bullshitting http://llvm.org/docs/LangRef.html#target-triple note that it's optional and can be overriden at compile time (which is what is happening here).
In a true browser implementation the target triple would be set to whatever platform the browser is running on, that way the browser compiled the web distributed IR straight to native code.
Google's PNACL, a precursor to WASM which shipped in Chrome, did exactly the above using LLVM IR. A web target triple was not needed as the LLVM IR was the web representation and the platform the browser was running on was the target triple. No need for a new web intermediary.
WASM works the same way, you distribute the representation and the browser converts it into a native target via compilation. WASM was designed to be less foreign to browser data structures/types and easier to implement in existing browser JS engines though. It's also easier to implement tiered compilation on. There are other reasons WASM was made instead of continuing to use LLVM IR but it's not because IR was CPU/OS specific.
LLVM does have web target triples though nowadays, wasm32 and wasm64. Previously it also had an asmjs target (which worked with standard JS engines at slower speeds without modification).