使用LLVM写WebAssembly

如果你不知道的话,那让我来告诉你编译器社区中有一个小秘密:可以使用LLVM写WebAssembly

LLVM是像Clang和Rust这样的语言使用的工具,它是一种通用的中间表示(IR),可以编译成机器代码输出。Web Assenbly就是其中之一。

今天我将展示将LLVM编译成Web Assenbly是多么简单。让我们从编写IR函数开始:

define i32 @main() {
ret i32 42
}

简单的是吗?一个返回42的函数。经典。

现在这里是魔术:

llc -mtriple = wasm32-unknown-unknown -O3 -filetype = obj main.ll -o main.o
wasm-ld main.o -o main.wasm --no-entry -allow-undefined

这些行正在做两件事:

  1. lcc正在将我们的IR编译成特定架构的机器语言表示。在我们的例子中:它是一个针对Web程序集(目标文件)的二进制格式。
  2. wasm-ld 将此对象文件链接到浏览器可以使用的Web程序集模块

现在,您可以使用Web装配模块并将其加载到浏览器中:

fetch("main.wasm")
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(results => {
window.alert(results.instance.exports.main());
});

查看演示