Emscripten
and
WebAssembly



Alon Zakai / @kripken


Dec 9th 2015


an open source LLVM-based compiler from C and C++ to JavaScript


C++    LLVM    Emscripten    JS

  float array[5000]; // C++
  int main() {
    for (int i = 0; i < 5000; ++i) {
      array[i] += 1.0f;
    }
  }

Emscripten

  function main() { // JavaScript
    var a = 0, b = 0;
    do {
      a = (8 + (b << 2)) | 0;
      HEAPF32[a >> 2] = +HEAPF32[a >> 2] + 1.0;
      b = (b + 1) | 0;
    } while ((b | 0) < 5000);
  }

This is asm.js, a low-level subset of JavaScript

Looks kind of hackish ;)

webassembly

(no official logo yet!)


WebAssembly = asm.js done right


Binary executable format for the web


New web standard, multi-vendor cooperation


Not limited by JavaScript, but does integrate properly with the Web


For WebAssembly to succeed we need two things:


1. Browsers to support WebAssembly natively


2. Compilers that emit WebAssembly


I'll talk about the second of those

Already a few compilers in the works:




New WebAssembly backend in LLVM by sunfish and others


ilwasm for .NET/CIL




Longer-term efforts, and we want to test and launch WebAssembly ASAP. What to do?

A hack, of course! :)



C++    Emscripten    asm.js

+

asm.js    ...    WebAssembly

... = asm2wasm: Compile asm.js ⇒ WebAssembly


Part of Binaryen: a WebAssembly infrastructure library, written in C++



Parse and emit WebAssembly

Represent and process WebAssembly

Interpret WebAssembly

wasm2asm: Compile WebAssembly ⇒ asm.js (wip)


Binaryen is extensible and has a convenient commandline interface



https://github.com/WebAssembly/binaryen

The name: WebAssembly is a Binary- format, and we integrate with Emscript-enBinaryen


Rhymes with Targaryen

(only 122 days until Game of Thrones returns)

wasm.js


wasm.js ports Binaryen to JavaScript using Emscripten


For example, it can execute WebAssembly in the Binaryen interpreter in JavaScript, as a (slow) polyfill

wasm.js demo





That's a C program compiled to WebAssembly — including full libc, syscalls, etc. — running in a WebAssembly interpreter written in C++, compiled to JavaScript, and embedded on this HTML page

C++    Emscripten+Binaryen    wasm


Runnable today, using the wasm.js compiled interpreter


And when browsers have native support for WebAssembly, the same build should just work

So Emscripten+Binaryen seems to work. How good is it?


Passes the Emscripten test suite, which is very comprehensive


Interpreter passes the WebAssembly spec test suite


Relatively little new code here, on top of a stable toolchain


Summary



Emscripten+Binaryen provide a C++ to WebAssembly solution, today


Also helping with experiments and prototyping for the WebAssembly design process


Binaryen can help grow the WebAssembly toolchain ecosystem



https://github.com/WebAssembly/binaryen