Loading and running WebAssembly code - WebAssembly

Loading and running WebAssembly code
====================================

To use WebAssembly in JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for the different mechanisms that can be used to fetch WebAssembly bytecode, as well as how to compile/instantiate then run it.

What are the options?
---------------------

WebAssembly is not yet integrated with `<script type='module'>` or `import` statements, thus there is not a path to have the browser fetch modules for you using imports.

The older `WebAssembly.compile`/`WebAssembly.instantiate` methods require you to create an `ArrayBuffer` containing your WebAssembly module binary after fetching the raw bytes, and then compile/instantiate it. This is analogous to `new Function(string)`, except that we are substituting a string of characters (JavaScript source code) with an array buffer of bytes (WebAssembly source code).

The newer `WebAssembly.compileStreaming`/`WebAssembly.instantiateStreaming` methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the `ArrayBuffer` step.

So how do we get those bytes into an array buffer and compiled? The following sections explain.

Using Fetch
-----------

Fetch is a convenient, modern API for fetching network resources.

The quickest, most efficient way to fetch a Wasm module is using the newer `WebAssembly.instantiateStreaming()` method, which can take a `fetch()` call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server:

```js
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (results) => {
    // Do something with the results!
  },
);
```

If we used the older `WebAssembly.instantiate()` method, which doesn't work on the direct stream, we'd need an extra step of converting the fetched byte code to an `ArrayBuffer`, like so:

```js
fetch("module.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.instantiate(bytes, importObject))
  .then((results) => {
    // Do something with the results!
  });
```

### Aside on instantiate() overloads

The `WebAssembly.instantiate()` function has two overload forms — the one shown above takes the byte code to compile as an argument and returns a Promise that resolves to an object containing both the compiled module object and an instantiated instance of it. The object looks like this:

```js
{
  module: Module, // The newly compiled WebAssembly.Module object,
  instance: Instance, // A new WebAssembly.Instance of the module object
}
```

**Note:** Usually we only care about the instance, but it's useful to have the module in case we want to cache it, share it with another worker or window via `postMessage()`, or create more instances.

**Note:** The second overload form takes a `WebAssembly.Module` object as an argument, and returns a promise directly containing the instance object as the result. See the Second overload example.

### Running your WebAssembly code

Once you've got your WebAssembly instance available in your JavaScript, you can then start using features of it that have been exported via the `WebAssembly.Instance.exports` property. Your code might look something like this:

```js
WebAssembly.instantiateStreaming(fetch("myModule.wasm"), importObject).then(
  (obj) => {
    // Call an exported function:
    obj.instance.exports.exported\_func();

    // or access the buffer contents of an exported memory:
    const i32 = new Uint32Array(obj.instance.exports.memory.buffer);

    // or access the elements of an exported table:
    const table = obj.instance.exports.table;
    console.log(table.get(0)());
  },
);
```

**Note:** For more information on how exporting from a WebAssembly module works, have a read of Using the WebAssembly JavaScript API, and Understanding WebAssembly text format.

Using XMLHttpRequest
--------------------

`XMLHttpRequest` is somewhat older than Fetch, but can still be happily used to get a typed array. Again, assuming our module is called `simple.wasm`:

1. Create a new `XMLHttpRequest()` instance, and use its `open()` method to open a request, setting the request method to `GET`, and declaring the path to the file we want to fetch.
2. The key part of this is to set the response type to `'arraybuffer'` using the `responseType` property.
3. Next, send the request using `XMLHttpRequest.send()`.
4. We then use the `load` event handler to invoke a function when the response has finished downloading — in this function we get the array buffer from the `response` property, and then feed that into our `WebAssembly.instantiate()` method as we did with Fetch.

The final code looks like this:

```js
const request = new XMLHttpRequest();
request.open("GET", "simple.wasm");
request.responseType = "arraybuffer";
request.send();

request.onload = () => {
  const bytes = request.response;
  WebAssembly.instantiate(bytes, importObject).then((results) => {
    results.instance.exports.exported\_func();
  });
};
```

**Note:** You can see an example of this in action in xhr-wasm.html.


WebAssembly instruction reference - WebAssembly

WebAssembly instruction reference
=================================

* `Numeric instructions`
* `Vector/SIMD instructions`
* `Reference instructions`
* `Variable instructions`
* `Table instructions`
* `Memory instructions`
* `Control flow instructions`


Compiling a New C/C++ Module to WebAssembly - WebAssembly

Compiling a New C/C++ Module to WebAssembly
===========================================

When you've written a new code module in a language like C/C++, you can compile it into WebAssembly using a tool like Emscripten. Let's look at how it works.

Emscripten Environment Setup
----------------------------

First, let's set up the required development environment.

### Prerequisites

Get the Emscripten SDK, using these instructions: https://emscripten.org/docs/getting\_started/downloads.html

Compiling an example
--------------------

With the environment set up, let's look at how to use it to compile a C example to Wasm. There are a number of options available when compiling with Emscripten, but the main two scenarios we'll cover are:

* Compiling to Wasm and creating HTML to run our code in, plus all the JavaScript "glue" code needed to run the Wasm in the web environment.
* Compiling to Wasm and just creating the JavaScript.

We will look at both below.

### Creating HTML and JavaScript

This is the simplest case we'll look at, whereby you get emscripten to generate everything you need to run your code, as WebAssembly, in the browser.

1. First we need an example to compile. Take a copy of the following simple C example, and save it in a file called `hello.c` in a new directory on your local drive:

```cpp
#include <stdio.h>

int main() {
    printf("Hello World\n");
    return 0;
}
```

2. Now, using the terminal window you used to enter the Emscripten compiler environment, navigate to the same directory as your `hello.c` file, and run the following command:

```bash
emcc hello.c -o hello.html
```

The options we've passed in with the command are as follows:

* `-o hello.html` — Specifies that we want Emscripten to generate an HTML page to run our code in (and a filename to use), as well as the Wasm module and the JavaScript "glue" code to compile and instantiate the Wasm so it can be used in the web environment.

At this point in your source directory you should have:

* The binary Wasm module code (`hello.wasm`)
* A JavaScript file containing glue code to translate between the native C functions, and JavaScript/Wasm (`hello.js`)
* An HTML file to load, compile, and instantiate your Wasm code, and display its output in the browser (`hello.html`)
### Running your example

Now all that remains is for you to load the resulting `hello.html` in a browser that supports WebAssembly. It is enabled by default from Firefox 52, Chrome 57, Edge 57, Opera 44.

**Note:** If you try to open generated HTML file (`hello.html`) directly from your local hard drive (e.g. `file://your_path/hello.html`), you will end up with an error message along the lines of *`both async and sync fetching of the wasm failed`.* You need to run your HTML file through an HTTP server (`http://`) — see How do you set up a local testing server? for more information.

 If everything has worked as planned, you should see "Hello world" output in the Emscripten console appearing on the web page, and your browser's JavaScript console. Congratulations, you've just compiled C to WebAssembly and run it in your browser!

 ![image](/en-US/docs/WebAssembly/C_to_Wasm/helloworld.png)

### Using a custom HTML template

Sometimes you will want to use a custom HTML template. Let's look at how we can do this.

1. First of all, save the following C code in a file called `hello2.c`, in a new directory:

```cpp
#include <stdio.h>

int main() {
    printf("Hello World\n");
    return 0;
}
```

2. Search for the file `shell_minimal.html` in your emsdk repo. Copy it into a subdirectory called `html_template` inside your previous new directory.
3. Now navigate into your new directory (again, in your Emscripten compiler environment terminal window), and run the following command:

```bash
emcc -o hello2.html hello2.c -O3 --shell-file html_template/shell_minimal.html
```

The options we've passed are slightly different this time:
    * We've specified `-o hello2.html`, meaning that the compiler will still output the JavaScript glue code and `.html`.
    * We've specified `-O3`, which is used to optimize the code. Emcc has optimization levels like any other C compiler, including: `-O0` (no optimization), `-O1`, `-O2`, `-Os`, `-Oz`, `-Og`, and `-O3`. `-O3` is a good setting for release builds.
    * We've also specified `--shell-file html_template/shell_minimal.html` — this provides the path to the HTML template you want to use to create the HTML you will run your example through.
4. Now let's run this example. The above command will have generated `hello2.html`, which will have much the same content as the template with some glue code added into load the generated Wasm, run it, etc. Open it in your browser and you'll see much the same output as the last example.

**Note:** You could specify outputting just the JavaScript "glue" file\* rather than the full HTML by specifying a .js file instead of an HTML file in the `-o` flag, e.g. `emcc -o hello2.js hello2.c -O3`. You could then build your custom HTML completely from scratch, although this is an advanced approach; it is usually easier to use the provided HTML template.

* Emscripten requires a large variety of JavaScript "glue" code to handle memory allocation, memory leaks, and a host of other problems

### Calling a custom function defined in C

If you have a function defined in your C code that you want to call as needed from JavaScript, you can do this using the Emscripten `ccall()` function, and the `EMSCRIPTEN_KEEPALIVE` declaration (which adds your functions to the exported functions list (see Why do functions in my C/C++ source code vanish when I compile to JavaScript, and/or I get No functions to process?)). Let's look at how this works.

1. To start with, save the following code as `hello3.c` in a new directory:

```cpp
#include <stdio.h>
#include <emscripten/emscripten.h>

int main() {
    printf("Hello World\n");
    return 0;
}

#ifdef \_\_cplusplus
#define EXTERN extern "C"
#else
#define EXTERN
#endif

EXTERN EMSCRIPTEN_KEEPALIVE void myFunction(int argc, char \*\* argv) {
    printf("MyFunction Called\n");
}
```

By default, Emscripten-generated code always just calls the `main()` function, and other functions are eliminated as dead code. Putting `EMSCRIPTEN_KEEPALIVE` before a function name stops this from happening. You also need to import the `emscripten.h` library to use `EMSCRIPTEN_KEEPALIVE`.

**Note:** We are including the `#ifdef` blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would otherwise break, but here we are setting it so that it treats it as an external C function if you are using C++.
2. Now add `html_template/shell_minimal.html` with `{{{ SCRIPT }}}` as content into this new directory too, just for convenience (you'd obviously put this in a central place in your real dev environment).
3. Now let's run the compilation step again. From inside your latest directory (and while inside your Emscripten compiler environment terminal window), compile your C code with the following command. Note that we need to compile with `NO_EXIT_RUNTIME`: otherwise, when `main()` exits, the runtime would be shut down and it wouldn't be valid to call compiled code. This is necessary for proper C emulation: for example, to ensure that `atexit()` functions are called.

```bash
emcc -o hello3.html hello3.c --shell-file html_template/shell_minimal.html -s NO\_EXIT\_RUNTIME=1 -s "EXPORTED\_RUNTIME\_METHODS=['ccall']"
```

4. If you load the example in your browser again, you'll see the same thing as before!
5. Now we need to run our new `myFunction()` function from JavaScript. First of all, open up your hello3.html file in a text editor.
6. Add a `<button>` element as shown below, just above the first opening `<script type='text/javascript'>` tag.

```html
<button id="mybutton">Run myFunction</button>
```

7. Now add the following code at the end of the first `<script>` element:

```js
document.getElementById("mybutton").addEventListener("click", () => {
  alert("check console");
  const result = Module.ccall(
    "myFunction", // name of C function
    null, // return type
    null, // argument types
    null, // arguments
  );
});
```

This illustrates how `ccall()` is used to call the exported function.

See also
--------

* emscripten.org — learn more about Emscripten and its large variety of options.
* Calling compiled C functions from JavaScript using ccall/cwrap
* Why do functions in my C/C++ source code vanish when I compile to JavaScript, and/or I get No functions to process?
* WebAssembly on Mozilla Research
* Compiling an Existing C Module to WebAssembly


WebAssembly - WebAssembly

WebAssembly
===========

The **`WebAssembly`** JavaScript object acts as the namespace for all WebAssembly-related functionality.

Unlike most other global objects, `WebAssembly` is not a constructor (it is not a function object). You can compare it to `Math`, which is also a namespace object for mathematical constants and functions, or to `Intl` which is the namespace object for internationalization constructors and other language-sensitive functions.

Description
-----------

The primary uses for the `WebAssembly` object are:

* Loading WebAssembly code, using the `WebAssembly.instantiate()` function.
* Creating new memory and table instances via the `WebAssembly.Memory()`/`WebAssembly.Table()` constructors.
* Providing facilities to handle errors that occur in WebAssembly via the `WebAssembly.CompileError()`/`WebAssembly.LinkError()`/`WebAssembly.RuntimeError()` constructors.
Constructor properties
----------------------

`WebAssembly.CompileError()`

Indicates an error during WebAssembly decoding or validation.

`WebAssembly.Global()`

Represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more `WebAssembly.Module` instances. This allows dynamic linking of multiple modules.

`WebAssembly.Instance()`

Is a stateful, executable instance of a `WebAssembly.Module`

`WebAssembly.LinkError()`

Indicates an error during module instantiation (besides traps from the start function).

`WebAssembly.Memory()`

An object whose `buffer` property is a resizable `ArrayBuffer` that holds the raw bytes of memory accessed by a WebAssembly `Instance`.

`WebAssembly.Module()`

Contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times.

`WebAssembly.RuntimeError()`

Error type that is thrown whenever WebAssembly specifies a trap.

`WebAssembly.Table()`

An array-like structure representing a WebAssembly Table, which stores references, such as function references.

`WebAssembly.Tag()`

An object that represents a type of WebAssembly exception.

`WebAssembly.Exception()`

A WebAssembly exception object that can be thrown, caught, and rethrown both within and across WebAssembly/JavaScript boundaries.

Static methods
--------------

`WebAssembly.instantiate()`

The primary API for compiling and instantiating WebAssembly code, returning both a `Module` and its first `Instance`.

`WebAssembly.instantiateStreaming()`

Compiles and instantiates a WebAssembly module directly from a streamed underlying source, returning both a `Module` and its first `Instance`.

`WebAssembly.compile()`

Compiles a `WebAssembly.Module` from WebAssembly binary code, leaving instantiation as a separate step.

`WebAssembly.compileStreaming()`

compiles a `WebAssembly.Module` directly from a streamed underlying source, leaving instantiation as a separate step.

`WebAssembly.validate()`

Validates a given typed array of WebAssembly binary code, returning whether the bytes are valid WebAssembly code (`true`) or not (`false`).

Examples
--------

### Stream a Wasm module then compile and instantiate it

The following example (see our instantiate-streaming.html demo on GitHub, and view it live also) directly streams a Wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a `ResultObject`. Because the `instantiateStreaming()` function accepts a promise for a `Response` object, you can directly pass it a `fetch()` call, and it will pass the response into the function when it fulfills.

```js
const importObject = { imports: { imported\_func: (arg) => console.log(arg) } };

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported\_func(),
);
```

The `ResultObject`'s `.instance` property is then accessed, and the contained exported function invoked.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # webassembly-namespace |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly Concepts - WebAssembly

WebAssembly Concepts
====================

This article explains the concepts behind how WebAssembly works including its goals, the problems it solves, and how it runs inside the web browser's JavaScript engine.

What is WebAssembly?
--------------------

WebAssembly is a new type of code that can be run in modern web browsers and provides new features and major gains in performance. It is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for source languages like C, C++, Rust, etc.

This has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn't have done so.

What's more, you don't even have to know how to create WebAssembly code to take advantage of it. WebAssembly modules can be imported into a web (or Node.js) app, exposing WebAssembly functions for use via JavaScript. JavaScript frameworks could make use of WebAssembly to confer massive performance advantages and new features while still making functionality easily available to web developers.

WebAssembly goals
-----------------

WebAssembly is being created as an open standard inside the W3C WebAssembly Community Group with the following goals:

* Be fast, efficient, and portable — WebAssembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities.
* Be readable and debuggable — WebAssembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand.
* Keep secure — WebAssembly is specified to be run in a safe, sandboxed execution environment. Like other web code, it will enforce the browser's same-origin and permissions policies.
* Don't break the web — WebAssembly is designed so that it plays nicely with other web technologies and maintains backwards compatibility.

**Note:** WebAssembly will also have uses outside web and JavaScript environments (see Non-web embeddings).

How does WebAssembly fit into the web platform?
-----------------------------------------------

The web platform can be thought of as having two parts:

* A virtual machine (VM) that runs the Web app's code, e.g. the JavaScript code that powers your apps.
* A set of Web APIs that the Web app can call to control web browser/device functionality and make things happen (DOM, CSSOM, WebGL, IndexedDB, Web Audio API, etc.).

Historically, the VM has been able to load only JavaScript. This has worked well for us as JavaScript is powerful enough to solve most problems people have on the Web today. We have run into performance problems, however, when trying to use JavaScript for more intensive use cases like 3D games, Virtual and Augmented Reality, computer vision, image/video editing, and a number of other domains that demand native performance (see WebAssembly use cases for more ideas).

Additionally, the cost of downloading, parsing, and compiling very large JavaScript applications can be prohibitive. Mobile and other resource-constrained platforms can further amplify these performance bottlenecks.

WebAssembly is a different language from JavaScript, but it is not intended as a replacement. Instead, it is designed to complement and work alongside JavaScript, allowing web developers to take advantage of both languages' strong points:

* JavaScript is a high-level language, flexible and expressive enough to write web applications. It has many advantages — it is dynamically typed, requires no compile step, and has a huge ecosystem that provides powerful frameworks, libraries, and other tools.
* WebAssembly is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with low-level memory models such as C++ and Rust with a compilation target so that they can run on the web. (Note that WebAssembly has the high-level goal of supporting languages with garbage-collected memory models in the future.)

With the advent of WebAssembly appearing in browsers, the virtual machine that we talked about earlier will now load and run two types of code — JavaScript AND WebAssembly.

The different code types can call each other as required — the WebAssembly JavaScript API wraps exported WebAssembly code with JavaScript functions that can be called normally, and WebAssembly code can import and synchronously call normal JavaScript functions. In fact, the basic unit of WebAssembly code is called a module and WebAssembly modules are symmetric in many ways to ES modules.

### WebAssembly key concepts

There are several key concepts needed to understand how WebAssembly runs in the browser. All of these concepts are reflected 1:1 in the WebAssembly JavaScript API.

* **Module**: Represents a WebAssembly binary that has been compiled by the browser into executable machine code. A Module is stateless and thus, like a `Blob`, can be explicitly shared between windows and workers (via `postMessage()`). A Module declares imports and exports just like an ES module.
* **Memory**: A resizable ArrayBuffer that contains the linear array of bytes read and written by WebAssembly's low-level memory access instructions.
* **Table**: A resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in Memory (for safety and portability reasons).
* **Instance**: A Module paired with all the state it uses at runtime including a Memory, Table, and set of imported values. An Instance is like an ES module that has been loaded into a particular global with a particular set of imports.

The JavaScript API provides developers with the ability to create modules, memories, tables, and instances. Given a WebAssembly instance, JavaScript code can synchronously call its exports, which are exposed as normal JavaScript functions. Arbitrary JavaScript functions can also be synchronously called by WebAssembly code by passing in those JavaScript functions as the imports to a WebAssembly instance.

Since JavaScript has complete control over how WebAssembly code is downloaded, compiled and run, JavaScript developers could even think of WebAssembly as just a JavaScript feature for efficiently generating high-performance functions.

In the future, WebAssembly modules will be loadable just like ES modules (using `<script type='module'>`), meaning that JavaScript will be able to fetch, compile, and import a WebAssembly module as easily as an ES module.

How do I use WebAssembly in my app?
-----------------------------------

Above we talked about the raw primitives that WebAssembly adds to the Web platform: a binary format for code and APIs for loading and running this binary code. Now let's talk about how we can use these primitives in practice.

The WebAssembly ecosystem is at a nascent stage; more tools will undoubtedly emerge going forward. Right now, there are four main entry points:

* Porting a C/C++ application with Emscripten.
* Writing or generating WebAssembly directly at the assembly level.
* Writing a Rust application and targeting WebAssembly as its output.
* Using AssemblyScript which looks similar to TypeScript and compiles to WebAssembly binary.

Let's talk about these options:

### Porting from C/C++

Two of the many options for creating Wasm code are an online Wasm assembler or Emscripten. There are a number of online Wasm assembler choices, such as:

* WasmFiddle++
* WasmExplorer

These are great resources for people who are trying to figure out where to start, but they lack some of the tooling and optimizations of Emscripten.

The Emscripten tool is able to take just about any C/C++ source code and compile it into a Wasm module, plus the necessary JavaScript "glue" code for loading and running the module, and an HTML document to display the results of the code.

![Diagram: Emscripten compiles C/C++ source code and into a Wasm module, an HTML document along with the JavaScript glue code.](/en-US/docs/WebAssembly/Concepts/emscripten-diagram.png)

In a nutshell, the process works as follows:

1. Emscripten first feeds the C/C++ into clang+LLVM — a mature open-source C/C++ compiler toolchain, shipped as part of XCode on OSX for example.
2. Emscripten transforms the compiled result of clang+LLVM into a Wasm binary.
3. By itself, WebAssembly cannot currently directly access the DOM; it can only call JavaScript, passing in integer and floating point primitive data types. Thus, to access any Web API, WebAssembly needs to call out to JavaScript, which then makes the Web API call. Emscripten therefore creates the HTML and JavaScript glue code needed to achieve this.

**Note:** There are future plans to allow WebAssembly to call Web APIs directly.

The JavaScript glue code is not as simple as you might imagine. For a start, Emscripten implements popular C/C++ libraries like SDL, OpenGL, OpenAL, and parts of POSIX. These libraries are implemented in terms of Web APIs and thus each one requires some JavaScript glue code to connect WebAssembly to the underlying Web API.

So part of the glue code is implementing the functionality of each respective library used by the C/C++ code. The glue code also contains the logic for calling the above-mentioned WebAssembly JavaScript APIs to fetch, load and run the Wasm file.

The generated HTML document loads the JavaScript glue file and writes stdout to a `<textarea>`. If the application uses OpenGL, the HTML also contains a `<canvas>` element that is used as the rendering target. It's very easy to modify the Emscripten output and turn it into whatever web app you require.

You can find full documentation on Emscripten at emscripten.org, and a guide to implementing the toolchain and compiling your own C/C++ app across to Wasm at Compiling from C/C++ to WebAssembly.

### Writing WebAssembly directly

Do you want to build your own compiler, or your own tools, or make a JavaScript library that generates WebAssembly at runtime?

In the same fashion as physical assembly languages, the WebAssembly binary format has a text representation — the two have a 1:1 correspondence. You can write or generate this format by hand and then convert it into the binary format with any of several WebAssembly text-to-binary tools.

For a simple guide on how to do this, see our Converting WebAssembly text format to Wasm article.

### Writing Rust Targeting WebAssembly

It is also possible to write Rust code and compile over to WebAssembly, thanks to the tireless work of the Rust WebAssembly Working Group. You can get started with installing the necessary toolchain, compiling a sample Rust program to a WebAssembly npm package, and using that in a sample web app, over at our Compiling from Rust to WebAssembly article.

### Using AssemblyScript

For web developers who want to try WebAssembly without needing to learn the details of C or Rust, staying in the comfort of a familiar language like TypeScript, AssemblyScript will be the best option. AssemblyScript compiles a strict variant of TypeScript to WebAssembly, allowing web developers to keep using TypeScript-compatible tooling they are familiar with — such as Prettier, ESLint, VS Code IntelliSense, etc. You can check its documentation on https://www.assemblyscript.org/.

Summary
-------

This article has given you an explanation of what WebAssembly is, why it is so useful, how it fits into the web, and how you can make use of it.

See also
--------

* WebAssembly articles on Mozilla Hacks blog
* WebAssembly on Mozilla Research
* Loading and running WebAssembly code — find out how to load your own WebAssembly module into a web page.
* Using the WebAssembly JavaScript API — find out how to use the other major features of the WebAssembly JavaScript API.


Understanding WebAssembly text format - WebAssembly

Understanding WebAssembly text format
=====================================

To enable WebAssembly to be read and edited by humans, there is a textual representation of the Wasm binary format. This is an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents — and the wrapper objects representing Wasm in JavaScript.

**Note:** This is potentially overkill if you are a web developer who just wants to load a Wasm module into a page and use it in your code (see Using the WebAssembly JavaScript API), but it is more useful if for example, you want to write Wasm modules to optimize the performance of your JavaScript library, or build your own WebAssembly compiler.

S-expressions
-------------

In both the binary and textual formats, the fundamental unit of code in WebAssembly is a module. In the text format, a module is represented as one big S-expression. S-expressions are a very old and very simple textual format for representing trees, and thus we can think of a module as a tree of nodes that describe the module's structure and its code. Unlike the Abstract Syntax Tree of a programming language, though, WebAssembly's tree is pretty flat, mostly consisting of lists of instructions.

First, let's see what an S-expression looks like. Each node in the tree goes inside a pair of parentheses — `( ... )`. The first label inside the parenthesis tells you what type of node it is, and after that there is a space-separated list of either attributes or child nodes. So that means the WebAssembly S-expression:

```wasm
(module (memory 1) (func))
```

represents a tree with the root node "module" and two child nodes, a "memory" node with the attribute "1" and a "func" node. We'll see shortly what these nodes actually mean.

### The simplest module

Let's start with the simplest, shortest possible Wasm module.

```wasm
(module)
```

This module is totally empty, but is still a valid module.

If we convert our module to binary now (see Converting WebAssembly text format to Wasm), we'll see just the 8 byte module header described in the binary format:

```wasm
0000000: 0061 736d              ; WASM_BINARY_MAGIC
0000004: 0100 0000              ; WASM_BINARY_VERSION
```

### Adding functionality to your module

Ok, that's not very interesting, let's add some executable code to this module.

All code in a webassembly module is grouped into functions, which have the following pseudocode structure:

```wasm
( func <signature> <locals> <body> )
```

* The **signature** declares what the function takes (parameters) and returns (return values).
* The **locals** are like vars in JavaScript, but with explicit types declared.
* The **body** is just a linear list of low-level instructions.

So this is similar to functions in other languages, even if it looks different because it is an S-expression.

Signatures and parameters
-------------------------

The signature is a sequence of parameter type declarations followed by a list of return type declarations. It is worth noting here that:

* The absence of a `(result)` means the function doesn't return anything.
* In the current iteration, there can be at most 1 return type, but later this will be relaxed to any number.

 Each parameter has a type explicitly declared; Wasm Number types, Reference types, Vector types.
 The number types are:

* `i32`: 32-bit integer
* `i64`: 64-bit integer
* `f32`: 32-bit float
* `f64`: 64-bit float

A single parameter is written `(param i32)` and the return type is written `(result i32)`, hence a binary function that takes two 32-bit integers and returns a 64-bit float would be written like this:

```wasm
(func (param i32) (param i32) (result f64) ...)
```

After the signature, locals are listed with their type, for example `(local i32)`. Parameters are basically just locals that are initialized with the value of the corresponding argument passed by the caller.

Getting and setting locals and parameters
-----------------------------------------

Locals/parameters can be read and written by the body of the function with the `local.get` and `local.set` instructions.

The `local.get`/`local.set` commands refer to the item to be got/set by its numeric index: parameters are referred to first, in order of their declaration, followed by locals in order of their declaration. So given the following function:

```wasm
(func (param i32) (param f32) (local f64)
  local.get 0
  local.get 1
  local.get 2)
```

The instruction `local.get 0` would get the i32 parameter, `local.get 1` would get the f32 parameter, and `local.get 2` would get the f64 local.

There is another issue here — using numeric indices to refer to items can be confusing and annoying, so the text format allows you to name parameters, locals, and most other items by including a name prefixed by a dollar symbol (`$`) just before the type declaration.

Thus, you could rewrite our previous signature like so:

```wasm
(func (param $p1 i32) (param $p2 f32) (local $loc f64) …)
```

And then could write `local.get $p1` instead of `local.get 0`, etc. (Note that when this text gets converted to binary, though, the binary will contain only the integer.)

Stack machines
--------------

Before we can write a function body, we have to talk about one more thing: **stack machines**. Although the browser compiles it to something more efficient, Wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of `i32`/`i64`/`f32`/`f64` values to/from a stack.

For example, `local.get` is defined to push the value of the local it read onto the stack, and `i32.add` pops two `i32` values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) and pushes the resulting i32 value.

When a function is called, it starts with an empty stack which is gradually filled up and emptied as the body's instructions are executed. So for example, after executing the following function:

```wasm
(func (param $p i32)
  (result i32)
  local.get $p
  local.get $p
  i32.add)
```

The stack contains exactly one `i32` value — the result of the expression (`$p + $p`), which is handled by `i32.add`. The return value of a function is just the final value left on the stack.

The WebAssembly validation rules ensure the stack matches exactly: if you declare a `(result f32)`, then the stack must contain exactly one `f32` at the end. If there is no result type, the stack must be empty.

Our first function body
-----------------------

As mentioned before, the function body is a list of instructions that are followed as the function is called. Putting this together with what we have already learned, we can finally define a module containing our own simple function:

```wasm
(module
  (func (param $lhs i32) (param $rhs i32) (result i32)
    local.get $lhs
    local.get $rhs
    i32.add))
```

This function gets two parameters, adds them together, and returns the result.

There are a lot more things that can be put inside function bodies, but we will start off simple for now, and you'll see a lot more examples as you go along. For a full list of the available opcodes, consult the webassembly.org Semantics reference.

### Calling the function

Our function won't do very much on its own — now we need to call it. How do we do that? Like in an ES module, Wasm functions must be explicitly exported by an `export` statement inside the module.

Like locals, functions are identified by an index by default, but for convenience, they can be named. Let's start by doing this — first, we'll add a name preceded by a dollar sign, just after the `func` keyword:

```wasm
(func $add …)
```

Now we need to add an export declaration — this looks like so:

```wasm
(export "add" (func $add))
```

Here, `add` is the name the function will be identified by in JavaScript whereas `$add` picks out which WebAssembly function inside the Module is being exported.

So our final module (for now) looks like this:

```wasm
(module
  (func $add (param $lhs i32) (param $rhs i32) (result i32)
    local.get $lhs
    local.get $rhs
    i32.add)
  (export "add" (func $add))
)
```

If you want to follow along with the example, save the above our module into a file called `add.wat`, then convert it into a binary file called `add.wasm` using wabt (see Converting WebAssembly text format to Wasm for details).

Next, we'll asynchronously instantiate our binary (see Loading and running WebAssembly code) and execute our `add` function in JavaScript (we can now find `add()` in the `exports` property of the instance):

```js
WebAssembly.instantiateStreaming(fetch("add.wasm")).then((obj) => {
  console.log(obj.instance.exports.add(1, 2)); // "3"
});
```

**Note:** You can find this example in GitHub as add.html (see it live also). Also see `WebAssembly.instantiateStreaming()` for more details about the instantiate function.

Exploring fundamentals
----------------------

Now we've covered the real basics, let's move on to look at some more advanced features.

### Calling functions from other functions in the same module

The `call` instruction calls a single function, given its index or name. For example, the following module contains two functions — one just returns the value 42, the other returns the result of calling the first plus one:

```wasm
(module
  (func $getAnswer (result i32)
    i32.const 42)
  (func (export "getAnswerPlus1") (result i32)
    call $getAnswer
    i32.const 1
    i32.add))
```

**Note:** `i32.const` just defines a 32-bit integer and pushes it onto the stack. You could swap out the `i32` for any of the other available types, and change the value of the const to whatever you like (here we've set the value to `42`).

In this example you'll notice an `(export "getAnswerPlus1")` section, declared just after the `func` statement in the second function — this is a shorthand way of declaring that we want to export this function, and defining the name we want to export it as.

This is functionally equivalent to including a separate function statement outside the function, elsewhere in the module in the same manner as we did before, e.g.:

```wasm
(export "getAnswerPlus1" (func $functionName))
```

The JavaScript code to call our above module looks like so:

```js
WebAssembly.instantiateStreaming(fetch("call.wasm")).then((obj) => {
  console.log(obj.instance.exports.getAnswerPlus1()); // "43"
});
```

### Importing functions from JavaScript

We have already seen JavaScript calling WebAssembly functions, but what about WebAssembly calling JavaScript functions? WebAssembly doesn't actually have any built-in knowledge of JavaScript, but it does have a general way to import functions that can accept either JavaScript or Wasm functions. Let's look at an example:

```wasm
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "logIt")
    i32.const 13
    call $log))
```

WebAssembly has a two-level namespace so the import statement here is saying that we're asking to import the `log` function from the `console` module. You can also see that the exported `logIt` function calls the imported function using the `call` instruction we introduced above.

Imported functions are just like normal functions: they have a signature that WebAssembly validation checks statically, and they are given an index and can be named and called.

JavaScript functions have no notion of signature, so any JavaScript function can be passed, regardless of the import's declared signature. Once a module declares an import, the caller of `WebAssembly.instantiate()` must pass in an import object that has the corresponding properties.

For the above, we need an object (let's call it `importObject`) such that `importObject.console.log` is a JavaScript function.

This would look like the following:

```js
const importObject = {
  console: {
    log(arg) {
      console.log(arg);
    },
  },
};

WebAssembly.instantiateStreaming(fetch("logger.wasm"), importObject).then(
  (obj) => {
    obj.instance.exports.logIt();
  },
);
```

**Note:** You can find this example on GitHub as logger.html (see it live also).

### Declaring globals in WebAssembly

WebAssembly has the ability to create global variable instances, accessible from both JavaScript and importable/exportable across one or more `WebAssembly.Module` instances. This is very useful, as it allows dynamic linking of multiple modules.

In WebAssembly text format, it looks something like this (see global.wat in our GitHub repo; also see global.html for a live JavaScript example):

```wasm
(module
   (global $g (import "js" "global") (mut i32))
   (func (export "getGlobal") (result i32)
        (global.get $g))
   (func (export "incGlobal")
        (global.set $g
            (i32.add (global.get $g) (i32.const 1))))
)
```

This looks similar to what we've seen before, except that we specify a global value using the keyword `global`, and we also specify the keyword `mut` along with the value's datatype if we want it to be mutable.

To create an equivalent value using JavaScript, you'd use the `WebAssembly.Global()` constructor:

```js
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
```

### WebAssembly Memory

The above example is a pretty terrible logging function: it only prints a single integer! What if we wanted to log a text string? To deal with strings and other more complex data types, WebAssembly provides **memory** (although we also have Reference types in newer implementation of WebAssembly). According to WebAssembly, memory is just a large array of bytes that can grow over time. WebAssembly contains instructions like `i32.load` and `i32.store` for reading and writing from linear memory.

From JavaScript's point of view, it's as though memory is all inside one big (resizable) `ArrayBuffer`. That's literally all that asm.js has to play with (except that it isn't resizable; see the asm.js Programming model).

So a string is just a sequence of bytes somewhere inside this linear memory. Let's assume that we've written a suitable string of bytes to memory; how do we pass that string out to JavaScript?

The key is that JavaScript can create WebAssembly linear memory instances via the `WebAssembly.Memory()` interface, and access an existing memory instance (currently you can only have one per module instance) using the associated instance methods. Memory instances have a `buffer` getter, which returns an `ArrayBuffer` that points at the whole linear memory.

Memory instances can also grow, for example via the `Memory.grow()` method in JavaScript. When growth occurs, since `ArrayBuffer`s can't change size, the current `ArrayBuffer` is detached and a new `ArrayBuffer` is created to point to the newer, bigger memory. This means all we need to do to pass a string to JavaScript is to pass out the offset of the string in linear memory along with some way to indicate the length.

While there are many ways to encode a string's length in the string itself (for example, C strings); for simplicity here we just pass both offset and length as parameters:

```wasm
(import "console" "log" (func $log (param i32) (param i32)))
```

On the JavaScript side, we can use the TextDecoder API to easily decode our bytes into a JavaScript string. (We specify `utf8` here, but many other encodings are supported.)

```js
function consoleLogString(offset, length) {
  const bytes = new Uint8Array(memory.buffer, offset, length);
  const string = new TextDecoder("utf8").decode(bytes);
  console.log(string);
}
```

The last missing piece of the puzzle is where `consoleLogString` gets access to the WebAssembly `memory`. WebAssembly gives us a lot of flexibility here: we can either create a `Memory` object in JavaScript and have the WebAssembly module import the memory, or we can have the WebAssembly module create the memory and export it to JavaScript.

For simplicity, let's create it in JavaScript then import it into WebAssembly. Our `import` statement is written as follows:

```wasm
(import "js" "mem" (memory 1))
```

The `1` indicates that the imported memory must have at least 1 page of memory (WebAssembly defines a page to be 64KB.)

So let's see a complete module that prints the string "Hi". In a normal compiled C program, you'd call a function to allocate some memory for the string, but since we're just writing our own assembly here and we own the entire linear memory, we can just write the string contents into global memory using a `data` section. Data sections allow a string of bytes to be written at a given offset at instantiation time and are similar to the `.data` sections in native executable formats.

Our final Wasm module looks like this:

```wasm
(module
  (import "console" "log" (func $log (param i32 i32)))
  (import "js" "mem" (memory 1))
  (data (i32.const 0) "Hi")
  (func (export "writeHi")
    i32.const 0  ;; pass offset 0 to log
    i32.const 2  ;; pass length 2 to log
    call $log))
```

**Note:** Above, note the double semicolon syntax (`;;`) for allowing comments in WebAssembly files.

Now from JavaScript we can create a Memory with 1 page and pass it in. This results in "Hi" being printed to the console:

```js
const memory = new WebAssembly.Memory({ initial: 1 });

const importObject = {
  console: { log: consoleLogString },
  js: { mem: memory },
};

WebAssembly.instantiateStreaming(fetch("logger2.wasm"), importObject).then(
  (obj) => {
    obj.instance.exports.writeHi();
  },
);
```

**Note:** You can find the full source on GitHub as logger2.html (also see it live).

### WebAssembly tables

To finish this tour of the WebAssembly text format, let's look at the most intricate, and often confusing, part of WebAssembly: **tables**. Tables are basically resizable arrays of references that can be accessed by index from WebAssembly code.

To see why tables are needed, we need to first observe that the `call` instruction we saw earlier (see Calling functions from other functions in the same module) takes a static function index and thus can only ever call one function — but what if the callee is a runtime value?

* In JavaScript, we see this all the time: functions are first-class values.
* In C/C++, we see this with function pointers.
* In C++, we see this with virtual functions.

WebAssembly needed a type of call instruction to achieve this, so we gave it `call_indirect`, which takes a dynamic function operand. The problem is that the only types we have to give operands in WebAssembly are (currently) `i32`/`i64`/`f32`/`f64`.

WebAssembly could add an `anyfunc` type ("any" because the type could hold functions of any signature), but unfortunately this `anyfunc` type couldn't be stored in linear memory for security reasons. Linear memory exposes the raw contents of stored values as bytes and this would allow Wasm content to arbitrarily observe and corrupt raw function addresses, which is something that cannot be allowed on the web.

The solution was to store function references in a table and pass around table indices instead, which are just i32 values. `call_indirect`'s operand can therefore be an i32 index value.

#### Defining a table in Wasm

So how do we place Wasm functions in our table? Just like `data` sections can be used to initialize regions of linear memory with bytes, `elem` sections can be used to initialize regions of tables with functions:

```wasm
(module
  (table 2 funcref)
  (elem (i32.const 0) $f1 $f2)
  (func $f1 (result i32)
    i32.const 42)
  (func $f2 (result i32)
    i32.const 13)
  ...
)
```

* In `(table 2 funcref)`, the 2 is the initial size of the table (meaning it will store two references) and `funcref` declares that the element type of these references are function reference.
* The functions (`func`) sections are just like any other declared Wasm functions. These are the functions we are going to refer to in our table (for example's sake, each one just returns a constant value). Note that the order the sections are declared in doesn't matter here — you can declare your functions anywhere and still refer to them in your `elem` section.
* The `elem` section can list any subset of the functions in a module, in any order, allowing duplicates. This is a list of the functions that are to be referenced by the table, in the order they are to be referenced.
* The `(i32.const 0)` value inside the `elem` section is an offset — this needs to be declared at the start of the section, and specifies at what index in the table function references start to be populated. Here we've specified 0, and a size of 2 (see above), so we can fill in two references at indexes 0 and 1. If we wanted to start writing our references at offset 1, we'd have to write `(i32.const 1)`, and the table size would have to be 3.

**Note:** Uninitialized elements are given a default throw-on-call value.

In JavaScript, the equivalent calls to create such a table instance would look something like this:

```js
function () {
  // table section
  const tbl = new WebAssembly.Table({initial: 2, element: "anyfunc"});

  // function sections:
  const f1 = ... /\* some imported WebAssembly function \*/
  const f2 = ... /\* some imported WebAssembly function \*/

  // elem section
  tbl.set(0, f1);
  tbl.set(1, f2);
};
```

#### Using the table

Moving on, now we've defined the table we need to use it somehow. Let's use this section of code to do so:

```wasm
(type $return\_i32 (func (result i32))) ;; if this was f32, type checking would fail
(func (export "callByIndex") (param $i i32) (result i32)
  local.get $i
  call\_indirect (type $return\_i32))
```

* The `(type $return_i32 (func (result i32)))` block specifies a type, with a reference name. This type is used when performing type checking of the table function reference calls later on. Here we are saying that the references need to be functions that return an `i32` as a result.
* Next, we define a function that will be exported with the name `callByIndex`. This will take one `i32` as a parameter, which is given the argument name `$i`.
* Inside the function, we add one value to the stack — whatever value is passed in as the parameter `$i`.
* Finally, we use `call_indirect` to call a function from the table — it implicitly pops the value of `$i` off the stack. The net result of this is that the `callByIndex` function invokes the `$i`'th function in the table.

You could also declare the `call_indirect` parameter explicitly during the command call instead of before it, like this:

```wasm
(call\_indirect (type $return\_i32) (local.get $i))
```

In a higher level, more expressive language like JavaScript, you could imagine doing the same thing with an array (or probably more likely, object) containing functions. The pseudocode would look something like `tbl[i]()`.

So, back to the typechecking. Since WebAssembly is type checked, and the `funcref` can be potentially any function signature, we have to supply the presumed signature of the callee at the callsite, hence we include the `$return_i32` type, to tell the program a function returning an `i32` is expected. If the callee doesn't have a matching signature (say an `f32` is returned instead), a `WebAssembly.RuntimeError` is thrown.

So what links the `call_indirect` to the table we are calling? The answer is that there is only one table allowed right now per module instance, and that is what `call_indirect` is implicitly calling. In the future, when multiple tables are allowed, we would also need to specify a table identifier of some kind, along the lines of

```wasm
call\_indirect $my\_spicy\_table (type $i32\_to\_void)
```

The full module all together looks like this, and can be found in our wasm-table.wat example file:

```wasm
(module
  (table 2 funcref)
  (func $f1 (result i32)
    i32.const 42)
  (func $f2 (result i32)
    i32.const 13)
  (elem (i32.const 0) $f1 $f2)
  (type $return\_i32 (func (result i32)))
  (func (export "callByIndex") (param $i i32) (result i32)
    local.get $i
    call\_indirect (type $return\_i32))
)
```

We load it into a webpage using the following JavaScript:

```js
WebAssembly.instantiateStreaming(fetch("wasm-table.wasm")).then((obj) => {
  console.log(obj.instance.exports.callByIndex(0)); // returns 42
  console.log(obj.instance.exports.callByIndex(1)); // returns 13
  console.log(obj.instance.exports.callByIndex(2)); // returns an error, because there is no index position 2 in the table
});
```

**Note:** You can find this example on GitHub as wasm-table.html (see it live also).

**Note:** Just like Memory, Tables can also be created from JavaScript (see `WebAssembly.Table()`) as well as imported to/from another Wasm module.

### Mutating tables and dynamic linking

Because JavaScript has full access to function references, the Table object can be mutated from JavaScript using the `grow()`, `get()` and `set()` methods. And WebAssembly code is itself able to manipulate tables using instructions added as part of Reference types, such as `table.get` and `table.set`.

Because tables are mutable, they can be used to implement sophisticated load-time and run-time dynamic linking schemes. When a program is dynamically linked, multiple instances share the same memory and table. This is symmetric to a native application where multiple compiled `.dll`s share a single process's address space.

To see this in action, we'll create a single import object containing a Memory object and a Table object, and pass this same import object to multiple `instantiate()` calls.

Our `.wat` examples look like so:

`shared0.wat`:

```wasm
(module
  (import "js" "memory" (memory 1))
  (import "js" "table" (table 1 funcref))
  (elem (i32.const 0) $shared0func)
  (func $shared0func (result i32)
   i32.const 0
   i32.load)
)
```

`shared1.wat`:

```wasm
(module
  (import "js" "memory" (memory 1))
  (import "js" "table" (table 1 funcref))
  (type $void\_to\_i32 (func (result i32)))
  (func (export "doIt") (result i32)
   i32.const 0
   i32.const 42
   i32.store  ;; store 42 at address 0
   i32.const 0
   call\_indirect (type $void\_to\_i32))
)
```

These work as follows:

1. The function `shared0func` is defined in `shared0.wat`, and stored in our imported table.
2. This function creates a constant containing the value `0`, and then uses the `i32.load` command to load the value contained in the provided memory index. The index provided is `0` — again, it implicitly pops the previous value off the stack. So `shared0func` loads and returns the value stored at memory index `0`.
3. In `shared1.wat`, we export a function called `doIt` — this function creates two constants containing the values `0` and `42`, then calls `i32.store` to store a provided value at a provided index of the imported memory. Again, it implicitly pops these values off the stack, so the result is that it stores the value `42` in memory index `0`,
4. In the last part of the function, we create a constant with value `0`, then call the function at this index 0 of the table, which is `shared0func`, stored there earlier by the `elem` block in `shared0.wat`.
5. When called, `shared0func` loads the `42` we stored in memory using the `i32.store` command in `shared1.wat`.

**Note:** The above expressions again pop values from the stack implicitly, but you could declare these explicitly inside the command calls instead, for example:

```wasm
(i32.store (i32.const 0) (i32.const 42))
(call\_indirect (type $void\_to\_i32) (i32.const 0))
```

After converting to assembly, we then use `shared0.wasm` and `shared1.wasm` in JavaScript via the following code:

```js
const importObj = {
  js: {
    memory: new WebAssembly.Memory({ initial: 1 }),
    table: new WebAssembly.Table({ initial: 1, element: "anyfunc" }),
  },
};

Promise.all([
  WebAssembly.instantiateStreaming(fetch("shared0.wasm"), importObj),
  WebAssembly.instantiateStreaming(fetch("shared1.wasm"), importObj),
]).then((results) => {
  console.log(results[1].instance.exports.doIt()); // prints 42
});
```

Each of the modules that is being compiled can import the same memory and table objects and thus share the same linear memory and table "address space".

**Note:** You can find this example on GitHub as shared-address-space.html (see it live also).

Bulk memory operations
----------------------

Bulk memory operations are a newer addition to the language (for example, in Firefox 79) — seven new built-in operations are provided for bulk memory operations such as copying and initializing, to allow WebAssembly to model native functions such as `memcpy` and `memmove` in a more efficient, performant way.

The new operations are:

* `data.drop`: Discard the data in an data segment.
* `elem.drop`: Discard the data in an element segment.
* `memory.copy`: Copy from one region of linear memory to another.
* `memory.fill`: Fill a region of linear memory with a given byte value.
* `memory.init`: Copy a region from a data segment.
* `table.copy`: Copy from one region of a table to another.
* `table.init`: Copy a region from an element segment.

**Note:** You can find more information in the Bulk Memory Operations and Conditional Segment Initialization proposal.

Types
-----

### Number types

WebAssembly currently has four available *number types*:

* `i32`: 32-bit integer
* `i64`: 64-bit integer
* `f32`: 32-bit float
* `f64`: 64-bit float
### Vector types

* `v128`: 128 bit vector of packed integer, floating-point data, or a single 128 bit type.
### Reference types

The reference types proposal (supported in Firefox 79) provides two main features:

* A new type, `externref`, which can hold *any* JavaScript value, for example strings, DOM references, objects, etc. `externref` is opaque from the point of view of WebAssembly — a Wasm module can't access and manipulate these values and instead can only receive them and pass them back out. But this is very useful for allowing Wasm modules to call JavaScript functions, DOM APIs, etc., and generally to pave the way for easier interoperability with the host environment. `externref` can be used for value types and table elements.
* A number of new instructions that allow Wasm modules to directly manipulate WebAssembly tables, rather than having to do it via the JavaScript API.

**Note:** The wasm-bindgen documentation contains some useful information on how to take advantage of `externref` from Rust.

Multi-value WebAssembly
-----------------------

Another more recent addition to the language (for example, in Firefox 78) is WebAssembly multi-value, meaning that WebAssembly functions can now return multiple values, and instruction sequences can consume and produce multiple stack values.

At the time of writing (June 2020) this is at an early stage, and the only multi-value instructions available are calls to functions that themselves return multiple values. For example:

```wasm
(module
  (func $get\_two\_numbers (result i32 i32)
    i32.const 1
    i32.const 2
  )
  (func (export "add\_two\_numbers") (result i32)
    call $get\_two\_numbers
    i32.add
  )
)
```

But this will pave the way for more useful instruction types, and other things besides. For a useful write-up of progress so far and how this works, see Multi-Value All The Wasm! by Nick Fitzgerald.

WebAssembly threads
-------------------

WebAssembly Threads (supported in Firefox 79 onwards) allow WebAssembly Memory objects to be shared across multiple WebAssembly instances running in separate Web Workers, in the same fashion as `SharedArrayBuffer`s in JavaScript. This allows very fast communication between Workers, and significant performance gains in web applications.

The threads proposal has two parts, shared memories and atomic memory accesses.

### Shared memories

As described above, you can create shared WebAssembly `Memory` objects, which can be transferred between Window and Worker contexts using `postMessage()`, in the same fashion as a `SharedArrayBuffer`.

Over on the JavaScript API side, the `WebAssembly.Memory()` constructor's initialization object now has a `shared` property, which when set to `true` will create a shared memory:

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
  shared: true,
});
```

the memory's `buffer` property will now return a `SharedArrayBuffer`, instead of the usual `ArrayBuffer`:

```js
memory.buffer; // returns SharedArrayBuffer
```

Over in the text format, you can create a shared memory using the `shared` keyword, like this:

```wasm
(memory 1 2 shared)
```

Unlike unshared memories, shared memories must specify a "maximum" size, in both the JavaScript API constructor and Wasm text format.

**Note:** You can find a lot more details in the Threading proposal for WebAssembly.

### Atomic memory accesses

A number of new Wasm instructions have been added that can be used to implement higher level features like mutexes, condition variables, etc. You can find them listed here. These instructions are allowed on non-shared memories as of Firefox 80.

**Note:** The Emscripten Pthreads support page shows how to take advantage of this new functionality from Emscripten.

Summary
-------

This finishes our high-level tour of the major components of the WebAssembly text format and how they get reflected in the WebAssembly JS API.

See also
--------

* The main thing that wasn't included is a comprehensive list of all the instructions that can occur in function bodies. See the WebAssembly semantics for a treatment of each instruction.
* See also the grammar of the text format that is implemented by the spec interpreter.


WebAssembly control flow instructions - WebAssembly

WebAssembly control flow instructions
=====================================

WebAssembly control flow instructions.

`block`

Creates a label that can later be branched out of with a `br`.

`br`

Branches to a loop or block.

`call`

Calls a function.

`drop`

Pops a value from the stack, and discards it.

`end`

Can be used to end a `block`, `loop`, `if`, or `else`.

`if...else`

Executes a statement if the last item on the stack is true (`1`).

`loop`

Creates a label that can later be branched to with a `br`.

`nop`

Does nothing.

`return`

Returns from a function.

`select`

Selects one of its first two operands based on a boolean condition.

`unreachable`

Denotes a point in code that should not be reachable.


WebAssembly variable instructions - WebAssembly

WebAssembly variable instructions
=================================

WebAssembly variable instructions.

`Declare local`

Declare a new local variable.

`Get local`

Load the value of a local variable onto the stack.

`Set local`

Set the value of a local variable.

`Tee local`

Set the value of a local variable and keep the value on the stack.

`Declare global`

Declare a new global variable.

`Get global`

Load the value of a global variable onto the stack.

`Set global`

Set the value of a global variable.


WebAssembly memory instructions - WebAssembly

WebAssembly memory instructions
===============================

WebAssembly memory instructions.

`Grow`

Increase the size of the memory instance.

`Size`

Get the size of the memory instance.

`Load`

Load a number from memory.

`Store`

Store a number in memory.


WebAssembly numeric instructions - WebAssembly

WebAssembly numeric instructions
================================

WebAssembly numeric instructions.

Constants
---------

`Const`

Declare a constant numbers.

Comparison
----------

`Equal`

Check if two numbers are equal.

`Not equal`

Check if two numbers are not equal.

`Greater than`

Check if a number is greater than another number.

`Less than`

Check if a number is less than another number.

`Greater or equal`

Check if a number is greater than or equal to another number.

`Less or equal`

Check if a number is less than or equal to another number.

Arithmetic
----------

`Addition`

Add up two numbers.

`Subtraction`

Subtract one number from another number.

`Multiplication`

Multiply one number by another number.

`Division`

Divide one number by another number.

`Remainder`

Calculate the remainder left over when one integer is divided by another integer.

Conversion
----------

`Extend`

Convert (extend) `i32` to `i64`.

`Wrap`

Convert (wrap) `i64` to `i32`.

`Promote`

Convert (promote) `f32` to `f64`.

`Demote`

Convert (demote) `f64` to `f32`.

`Convert`

Convert integers to floating points.

`Truncate (float to int)`

Convert (truncate fractional part) floating points to integers.

`Reinterpret`

Reinterpret the bytes of integers as floating points and vice versa.

Floating point specific instructions
------------------------------------

`Min`

Get the lower of two numbers.

`Max`

Get the higher of two numbers.

`Nearest`

Round a number to the nearest integer.

`Ceil`

Round up a number.

`Floor`

Round down a number.

`Truncate (float to float)`

Discard the fractional part of a number.

`Absolute`

Get the absolute value of a number.

`Negate`

Negate a number.

`Square root`

Get the square root of a number.

`Copy sign`

Copy just the sign bit from one number to another.

Bitwise
-------

`AND`

Used for performing a bitwise AND.

`OR`

Used for performing a bitwise OR.

`XOR`

Used for performing a bitwise XOR.

`Left shift`

Used for performing a bitwise left-shift.

`Right shift`

Used for performing a bitwise right-shift.

`Left rotate`

Used for performing a bitwise left-rotate.

`Right rotate`

Used for performing a bitwise right-rotate.

`Count leading zeros`

Count the amount of leading zeros in a numbers binary representation.

`Count trailing zeros`

Count the amount of trailing zeros in a numbers binary representation.

`Population count`

Count the total amount of 1s in a numbers binary representation.


unreachable - WebAssembly

unreachable
===========

**`unreachable`** is used to denote a point in code that should not be reachable. `unreachable` is an unconditional trap: in the case where an `unreachable` is reached and executed, the instruction traps.

Try it
------

Syntax
------

```wasm
unreachable
```

| Instruction | Binary opcode |
| --- | --- |
| `unreachable` | `0x00` |


if...else - WebAssembly

if...else
=========

The **`if`** statement executes a statement if the last item on the stack is true (1). If the condition is false (0), another statement can be executed

Try it
------

Syntax
------

```wasm
i32.const 0
(if
  (then
    ;; do something
  )
  (else
    ;; do something else
  )
)
```

| Instruction | Binary opcode |
| --- | --- |
| `if` | `0x04` |
| `else` | `0x05` |


block - WebAssembly

block
=====

The **`block`** statement creates a label that can later be branched out of with a `br`.

The **`loop`** statement is the opposite of the `block` statement, in the sense that while branching to a `loop` jumps to the beginning of the loop, branching to a `block` jumps to the end of the block; that is, out of the block.

Try it
------

Syntax
------

```wasm
;; label the block so that it can be branched to.
(block $my\_block

  ;; branch to the block.
  ;; most of the time you'll want to put this in an if statement and only branch on condition,
  ;; otherwise the following control flow are unreachable.
  br $my\_block

  ;; this will never be reached, since the br jumped out of the block already.
  unreachable

)
```

| Instruction | Binary opcode |
| --- | --- |
| `block` | `0x02` |


call - WebAssembly

call
====

**`call`** calls a function, `return_call` being the tail-call version of it. `call_indirect` calls a function in a table with the `return_call_indirect` tail-call version as well.

Try it
------

Syntax
------

```wasm
call $greet
```

| Instruction | Binary opcode |
| --- | --- |
| `call` | `0x10` |
| `call_indirect` | `0x11` |
| `return_call` | `0x12` |
| `return_call_indirect` | `0x13` |

See also
--------

* Tail Call Extension proposal overview
* V8 on WebAssembly tail calls support


return - WebAssembly

return
======

**`return`** returns from a function.

* If there are no values left on the stack, it returns nothing/void.
* If there are the same amount of values left on the stack as specified in the function's type signature, it returns those values.
* If there are more values that the function's return type specifies, then the excess values are popped from the stack and discarded, and the last N values are returned.
Try it
------

Syntax
------

```wasm
f32.const 4.3
return
```

```wasm
i32.const 7
f32.const 4.3
return
```

| Instruction | Binary opcode |
| --- | --- |
| `return` | `0x0f` |


loop - WebAssembly

loop
====

The **`loop`** statement creates a label that can later be branched to with a `br`. The loop instruction doesn't loop by itself; you need to branch to it to actually create a loop.

The **`loop`** statement is the opposite of the `block` statement, in the sense that while branching to a `loop` jumps to the beginning of the loop, branching to a `block` jumps to the end of the block, that is, out of the block.

Try it
------

Syntax
------

```wasm
;; label the loop so that it can be branched to
(loop $my\_loop

  ;; branch to the loop.
  ;; most of the time you'll want to put this in an if statement and only branch on condition,
  ;; otherwise you have an infinite loop.
  br $my\_loop

)
```

| Instruction | Binary opcode |
| --- | --- |
| `loop` | `0x03` |


Select - WebAssembly

Select
======

The **`select`** instruction, selects one of its first two operands based on whether its third operand is zero or not. It shares some similarities with the ternary operator in other languages (e.g. `false ? 10 : 20`), but doesn't short-circuit. The instruction may be followed by an immediate value type: `select (result T)`. `select (result T)` uses a different binary opcode, and allows types besides those introduced by the WebAssembly MVP (`i32`, `i64`, `f32`, `f64`), for example, it allows selection between two `externref` values.

Try it
------

Syntax
------

```wasm
;; push two values onto the stack
i32.const 10
i32.const 20

;; change to `1` (true) to get the first value (`10`)
i32.const 0
select
```

```
f32.const nan
f32.const -54.1

;; change to `1` (true) to get the first value (`nan`)
i32.const 0
select (result f32)
```

| Instruction | Binary opcode |
| --- | --- |
| `select` | `0x1b` |
| `select t` | `0x1c` |


Drop - WebAssembly

Drop
====

The **`drop`** instruction, pops a value from the stack, and discards it.

Try it
------

Syntax
------

```wasm
;; push multiple values onto the stack
i32.const 1
i32.const 2
i32.const 3

;; drop the top item from the stack (`3`)
drop

;; the top item on the stack will now be `2`
```

| Instruction | Binary opcode |
| --- | --- |
| `drop` | `0x1a` |


end - WebAssembly

end
===

**`end`** is used to end a `block`, `loop`, `if`, or `else`. In the other examples we used the s-expression syntax which doesn't require the `end`, so you won't find it in the other examples here. However, it's still useful to know about since this is what the browsers display in devtools.

Try it
------

Syntax
------

```wasm
i32.const 0
if
  ;; do something
end
```

| Instruction | Binary opcode |
| --- | --- |
| `end` | `0x0b` |


nop - WebAssembly

nop
===

**`nop`** stands for no-operation. It literally does nothing.

Try it
------

Syntax
------

```wasm
nop
```

| Instruction | Binary opcode |
| --- | --- |
| `nop` | `0x01` |


br - WebAssembly

br
==

The **`br`** statement branches to a loop, block, or if.

Other variants of `br` are `br_if` for branching on condition, and `br_table` for branching to different blocks based on an argument.

Try it
------

Syntax
------

```wasm
;; label the loop so that it can be branched to
(loop $my\_loop

  ;; branch to the loop.
  ;; most of the time you'll want to put this in an if statement and only branch on condition,
  ;; otherwise you have an infinite loop.
  br $my\_loop

)
```

| Instruction | Binary opcode |
| --- | --- |
| `br` | `0x0c` |
| `br_if` | `0x0d` |
| `br_table` | `0x0e` |


Local set - WebAssembly

Local set
=========

The **`local.set`** instruction sets the values of a local variable.

Try it
------

Syntax
------

```wasm
;; load the number 2 onto the stack
i32.const 2

;; store the number 2 in the variable $val
local.set $val
```

| Instruction | Binary opcode |
| --- | --- |
| `local.set` | `0x21` |


Global get - WebAssembly

Global get
==========

The **`global.get`** instruction loads the value of a global variable onto the stack.

Try it
------

Syntax
------

```wasm
;; load the value of a global variable onto the stack
global.get $val
```

| Instruction | Binary opcode |
| --- | --- |
| `global.get` | `0x23` |


Local - WebAssembly

Local
=====

The **`local`** instruction declares a new local variable.

Try it
------

Syntax
------

```wasm
;; declare new variable named $val of type i32
(local $val i32)
```


Local tee - WebAssembly

Local tee
=========

The **`local.tee`** instruction sets the value of a local variable and loads the value onto the stack.

The instruction is named after the T-splitter used in plumbing.

Try it
------

Syntax
------

```wasm
;; load the number 2 onto the stack
i32.const 2

;; store the number 2 in the variable $val and load it on the stack
local.tee $val
```

| Instruction | Binary opcode |
| --- | --- |
| `local.tee` | `0x22` |


Global - WebAssembly

Global
======

The **`global`** instruction declares a new global variable.

Try it
------

Syntax
------

```wasm
;; declare new variable named $val of type i32
(global $val i32)
```


Global set - WebAssembly

Global set
==========

The **`global.set`** instruction sets the values of a global variable.

Try it
------

Syntax
------

```wasm
;; load the number 2 onto the stack
i32.const 2

;; store the number 2 in the variable $val
global.set $val
```

| Instruction | Binary opcode |
| --- | --- |
| `global.set` | `0x24` |


Local get - WebAssembly

Local get
=========

The **`local.get`** instruction loads the value of a local variable onto the stack.

Try it
------

Syntax
------

```wasm
;; load the value of a local variable onto the stack
local.get $val
```

| Instruction | Binary opcode |
| --- | --- |
| `local.get` | `0x20` |


Greater or equal - WebAssembly

Greater or equal
================

The **`ge`** instructions, short for *greater or equal*, check if a number is greater than or equal to another number. If the first number is greater than or equal to the second number equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

The integer types have separate greater or equal instructions for signed (**`ge_s`**) and unsigned (**`ge_u`**) numbers.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is greater than or equal to '2'
i32.ge\_u

;; if $num is greater than or equal to the `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.ge_s` | `0x4e` |
| `i32.ge_u` | `0x4f` |
| `i64.ge_s` | `0x59` |
| `i64.ge_u` | `0x5a` |
| `f32.ge` | `0x60` |
| `f64.ge` | `0x66` |


Addition - WebAssembly

Addition
========

The **`add`** instructions, are used for adding up two numbers, similar to the **`+`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 10
i32.const 3

;; add up both numbers
i32.add

;; the top item on the stack will now be 13 (10 + 3 = 13)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.add` | `0x6a` |
| `i64.add` | `0x7c` |
| `f32.add` | `0x92` |
| `f64.add` | `0xa0` |


Square root - WebAssembly

Square root
===========

The **`sqrt`** instructions, short for *square root*, are used to get the square root of a number.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const 289

;; get the square root of 289
f32.sqrt

;; the top item on the stack will now be 17
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.sqrt` | `0x91` |
| `f64.sqrt` | `0x9f` |


Truncate (float to int) - WebAssembly

Truncate (float to int)
=======================

The **`trunc`** instructions, are used for converting floating points to integers. It's named truncate since it truncates the fractional part of the number when doing the conversion. There are signed and unsigned versions of this instruction.

There's another **`trunc`** instruction that truncates the fractional part of a floating point without converting it to and integer.

Try it
------

Syntax
------

```wasm
;; push an f32 onto the stack
f32.const 10.5

;; convert from f32 to signed i32 rounding towards zero (.5 will be lost)
i32.trunc_f32_s

;; the top item on the stack will now be the value 10 of type f32
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.trunc_f32_s` | `0xa8` |
| `i32.trunc_f32_u` | `0xa9` |
| `i32.trunc_f64_s` | `0xaa` |
| `i32.trunc_f64_u` | `0xab` |
| `i64.trunc_f32_s` | `0xae` |
| `i64.trunc_f32_u` | `0xaf` |
| `i64.trunc_f64_s` | `0xb0` |
| `i64.trunc_f64_u` | `0xb1` |


Nearest - WebAssembly

Nearest
=======

The **`nearest`** instructions, are used for getting the value of a number rounded to the nearest integer.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const -2.7

;; round to the nearest integer
f32.nearest

;; the top item on the stack will now be -3
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.nearest` | `0x90` |
| `f64.nearest` | `0x9e` |


Multiplication - WebAssembly

Multiplication
==============

The **`mul`** instructions, short for *multiplication*, are used for multiplying one number by another number, similar to the **`*`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 10
i32.const 3

;; multiply one number by the other
i32.mul

;; the top item on the stack will now be 30 (10 \* 3 = 30)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.mul` | `0x6c` |
| `i64.mul` | `0x7e` |
| `f32.mul` | `0x94` |
| `f64.mul` | `0xa2` |


XOR - WebAssembly

XOR
===

The **`xor`** instructions, are used for performing a bitwise XOR, similar to the **`^`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 5   ;; 00000101
i32.const 3   ;; 00000011

;; perform a bitwise XOR
i32.xor

;; the top item on the stack will now be 6 (00000110)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.xor` | `0x73` |
| `i64.xor` | `0x85` |


Not equal - WebAssembly

Not equal
=========

The **`ne`** instructions, short for *not equal*, check if two numbers are not equal. If the numbers are not equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is not equal to '2'
i32.ne

;; if $num is not equal to `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.ne` | `0x47` |
| `i64.ne` | `0x52` |
| `f32.ne` | `0x5c` |
| `f64.ne` | `0x62` |


Less than - WebAssembly

Less than
=========

The **`lt`** instructions, short for *less than*, check if a number is less than another number. If the first number is less than the second number equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

The integer types have separate less than instructions for signed (**`lt_s`**) and unsigned (**`lt_u`**) numbers.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is less then '2'
i32.lt\_u

;; if $num is less than the `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.lt_s` | `0x48` |
| `i32.lt_u` | `0x49` |
| `i64.lt_s` | `0x53` |
| `i64.lt_u` | `0x54` |
| `f32.lt` | `0x5d` |
| `f64.lt` | `0x63` |


Const - WebAssembly

Const
=====

The **`const`** instructions, are used to declare numbers.

Try it
------

Syntax
------

```wasm
;; push `5` onto the stack
i32.const 5
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.const` | `0x41` |
| `i64.const` | `0x42` |
| `f32.const` | `0x43` |
| `f64.const` | `0x44` |


Subtraction - WebAssembly

Subtraction
===========

The **`sub`** instructions, short for *subtraction*, are used for subtracting one number from another number, similar to the **`-`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 10
i32.const 3

;; subtract one number from the other
i32.sub

;; the top item on the stack will now be 7 (10 - 3 = 7)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.sub` | `0x6b` |
| `i64.sub` | `0x7d` |
| `f32.sub` | `0x93` |
| `f64.sub` | `0xa1` |


Left shift - WebAssembly

Left shift
==========

The **`shl`** instructions, short for *shift-left*, are used for performing a bitwise left-shift, similar to the **`<<`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 7   ;; 00000111
i32.const 1   ;; left shift one spot

;; perform a bitwise left-shift
i32.shl

;; the top item on the stack will now be 14 (00001110)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.shl` | `0x74` |
| `i64.shl` | `0x86` |


Less or equal - WebAssembly

Less or equal
=============

The **`le`** instructions, short for *less or equal*, check if a number is less than or equal to another number. If the first number is less than or equal to the second number equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

The integer types have separate less or equal instructions for signed (**`le_s`**) and unsigned (**`le_u`**) numbers.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is less then or equal to '2'
i32.le\_u

;; if $num is less than or equal to the `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.le_s` | `0x4C` |
| `i32.le_u` | `0x4D` |
| `i64.le_s` | `0x57` |
| `i64.le_u` | `0x58` |
| `f32.le` | `0x5F` |
| `f64.le` | `0x65` |


Division - WebAssembly

Division
========

The **`div`** instructions, short for *division*, are used for dividing one number by another, similar to the **`/`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 12
i32.const 3

;; divide one number by the other
i32.div\_u

;; the top item on the stack will now be 4 (12 / 3 = 4)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.div_s` | `0x6d` |
| `i32.div_u` | `0x6e` |
| `i64.div_s` | `0x7f` |
| `i64.div_u` | `0x80` |
| `f32.div` | `0x95` |
| `f64.div` | `0xa3` |


Reinterpret - WebAssembly

Reinterpret
===========

The **`reinterpret`** instructions, are used to reinterpret the bits of a number as a different type.

Try it
------

Syntax
------

```wasm
;; the value `10000000\_00000000\_00000000\_00000000` in binary
;; maps to `-0` as a floating point and to `-2147483648` as an integer

;; push an f32 onto the stack
f32.const -0

;; reinterpret the bytes of the f32 as i32
i32.reinterpret_f32

;; the top item on the stack will now be the value -2147483648 of type i32
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.reinterpret_f32` | `0xbc` |
| `i64.reinterpret_f64` | `0xbd` |
| `f32.reinterpret_i32` | `0xbe` |
| `f64.reinterpret_i64` | `0xbf` |


Right rotate - WebAssembly

Right rotate
============

The **`rotr`** instructions, short for *rotate-right*, are used for performing a bitwise right-rotate.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 7   ;; 00000000\_00000000\_00000000\_00000111
i32.const 1   ;; right rotate one spot

;; perform a bitwise right-rotate
i32.rotr

;; the top item on the stack will now be 2147483651
;; (10000000\_00000000\_00000000\_00000011)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.rotr` | `0x78` |
| `i64.rotr` | `0x8a` |


AND - WebAssembly

AND
===

The **`and`** instructions, are used for performing a bitwise AND, similar to the **`&`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 5   ;; 00000101
i32.const 3   ;; 00000011

;; perform a bitwise AND
i32.and

;; the top item on the stack will now be 1 (00000001)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.and` | `0x71` |
| `i64.and` | `0x83` |


Right shift - WebAssembly

Right shift
===========

The **`shr`** instructions, short for *shift-right*, are used for performing a bitwise right-shift, similar to the **`>>>`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 7   ;; 00000111
i32.const 1   ;; right shift one spot

;; perform a bitwise right-shift
i32.shr\_u

;; the top item on the stack will now be 3 (00000011)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.shr_s` | `0x75` |
| `i32.shr_u` | `0x76` |
| `i64.shr_s` | `0x87` |
| `i64.shr_u` | `0x88` |


Ceil - WebAssembly

Ceil
====

The **`ceil`** instructions, are used for getting the value of a number rounded up to the next integer.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const 2.7

;; round up
f32.ceil

;; the top item on the stack will now be 3
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.ceil` | `0x8d` |
| `f64.ceil` | `0x9b` |


Count trailing zeros - WebAssembly

Count trailing zeros
====================

The **`ctz`** instructions, short for *count trailing zeros*, are used to count the amount of zeros at the end of the numbers binary representation.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
i32.const 8388608 ;; 00000000\_10000000\_00000000\_00000000

;; count trailing zeros
i32.ctz

;; the top item on the stack will now be 23
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.ctz` | `0x68` |
| `i64.ctz` | `0x7a` |


OR - WebAssembly

OR
==

The **`or`** instructions, are used for performing a bitwise OR, similar to the **`|`** operator in other languages.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 5   ;; 00000101
i32.const 3   ;; 00000011

;; perform a bitwise OR
i32.or

;; the top item on the stack will now be 7 (00000111)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.or` | `0x72` |
| `i64.or` | `0x84` |


Wrap - WebAssembly

Wrap
====

The **`wrap`** instruction, is used to convert numbers of type `i64` to type `i32`. If the number is larger than what an `i32` can hold this operation will wrap, resulting in a different number.

One can think of wrap either as reducing the value mod 232, or as discarding the high 32 bits to produce a value containing just the low 32 bits.

Try it
------

Syntax
------

```wasm
;; push an i64 onto the stack
i64.const 10

;; wrap from i64 to i32
i32.wrap_i64

;; the top item on the stack will now be the value 10 of type `i32`
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.wrap_i64` | `0xa7` |


Absolute - WebAssembly

Absolute
========

The **`abs`** instructions, short for *absolute*, are used to get the absolute value of a number. That is, it returns x if x is positive, and the negation of x if x is negative.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const -2

;; absolute
f32.abs

;; the top item on the stack will now be 2
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.abs` | `0x8b` |
| `f64.abs` | `0x99` |


Equal - WebAssembly

Equal
=====

The **`eq`** instructions, short for *equal*, check if two numbers are equal. If both numbers are equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

Similarly, the **`eqz`** instructions check if a number is equal to zero, the **`eqz`** instructions are only available for the integer types and not for the floating point types.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is equal to '2'
i32.eq

;; if $num is equal to `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.eqz` | `0x45` |
| `i32.eq` | `0x46` |
| `i64.eqz` | `0x50` |
| `i64.eq` | `0x51` |
| `f32.eq` | `0x5b` |
| `f64.eq` | `0x61` |


Count leading zeros - WebAssembly

Count leading zeros
===================

The **`clz`** instructions, short for *count leading zeros*, are used to count the amount of zeros at the start of the numbers binary representation.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
i32.const 8388608 ;; 00000000\_10000000\_00000000\_00000000

;; count leading zeros
i32.clz

;; the top item on the stack will now be 8
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.clz` | `0x67` |
| `i64.clz` | `0x79` |


Convert - WebAssembly

Convert
=======

The **`convert`** instructions, are used for converting integer numbers to floating point numbers. There are signed and unsigned versions of this instruction.

Try it
------

Syntax
------

```wasm
;; push an i32 onto the stack
i32.const 10

;; convert from signed i32 to f32
f32.convert_i32_s

;; the top item on the stack will now be the value 10 of type f32
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.convert_i32_s` | `0xb2` |
| `f32.convert_i32_u` | `0xb3` |
| `f32.convert_i64_s` | `0xb4` |
| `f32.convert_i64_u` | `0xb5` |
| `f64.convert_i32_s` | `0xb7` |
| `f64.convert_i32_u` | `0xb8` |
| `f64.convert_i64_s` | `0xb9` |
| `f64.convert_i64_u` | `0xba` |


Greater than - WebAssembly

Greater than
============

The **`gt`** instructions, short for *greater than*, check if a number is greater than another number. If the first number is greater than the second number equal `1` will be pushed on to the stack, otherwise `0` will be pushed on to the stack.

The integer types have separate greater than instructions for signed (**`gt_s`**) and unsigned (**`gt_u`**) numbers.

Try it
------

Syntax
------

```wasm
;; load 2 numbers on to the stack
local.get $num
i32.const 2

;; check if $num is greater than '2'
i32.gt\_u

;; if $num is greater than the `2`, `1` will be pushed on to the stack,
;; otherwise `0` will be pushed on to the stack.
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.gt_s` | `0x4a` |
| `i32.gt_u` | `0x4b` |
| `i64.gt_s` | `0x55` |
| `i64.gt_u` | `0x56` |
| `f32.gt` | `0x5e` |
| `f64.gt` | `0x64` |


Promote - WebAssembly

Promote
=======

The **`promote`** instruction, is used to convert (promote) numbers of type `f32` to type `f64`.

Try it
------

Syntax
------

```wasm
;; push an f32 onto the stack
f32.const 10.5

;; promote from f32 to f64
f64.promote_f32

;; the top item on the stack will now be the value 10.5 of type f64
```

| Instruction | Binary opcode |
| --- | --- |
| `f64.promote_f32` | `0xbb` |


Min - WebAssembly

Min
===

The **`min`** instructions, are used for getting the lower of two numbers.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
f32.const 10
f32.const 3

;; get lower number
f32.min

;; the top item on the stack will now be 3
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.min` | `0x96` |
| `f64.min` | `0xa4` |


Max - WebAssembly

Max
===

The **`max`** instructions, are used for getting the higher of two numbers.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
f32.const 10
f32.const 3

;; get higher number
f32.max

;; the top item on the stack will now be 10
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.max` | `0x97` |
| `f64.max` | `0xa5` |


Left rotate - WebAssembly

Left rotate
===========

The **`rotl`** instructions, short for *rotate-left*, are used for performing a bitwise left-rotate.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 3758096384 ;; 11100000\_00000000\_00000000\_00000000
i32.const 1          ;; left rotate one spot

;; perform a bitwise left-rotate
i32.rotl

;; the top item on the stack will now be 3221225473
;; (11000000\_00000000\_00000000\_00000001)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.rotl` | `0x77` |
| `i64.rotl` | `0x89` |


Remainder - WebAssembly

Remainder
=========

The **`rem`** instructions, short for *remainder*, are used to calculate the remainder left over when one integer is divided by another integer, similar to the **`%`** operator in other languages. The **`rem`** instructions are only available for the integer types and not for the floating point types.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
i32.const 10
i32.const 3

;; calculate the remainder of dividing one number by the other
i32.rem

;; the top item on the stack will now be 1 (10 % 3 = 1)
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.rem_s` | `0x6f` |
| `i32.rem_u` | `0x70` |
| `i64.rem_s` | `0x81` |
| `i64.rem_u` | `0x82` |


Negate - WebAssembly

Negate
======

The **`neg`** instructions, short for *negate*, are used to negate a number. That is, turn a positive number into a negative number and a negative number into a positive number.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const 2.7

;; negate
f32.neg

;; the top item on the stack will now be -2.7
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.neg` | `0x8c` |
| `f64.neg` | `0x9a` |


Population count - WebAssembly

Population count
================

The **`popcnt`** instructions, short for *population count*, are used to count the amount of `1`s in a numbers binary representation.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
i32.const 130 ;; 10000010

;; count the 1s
i32.popcnt

;; the top item on the stack will now be 2
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.popcnt` | `0x69` |
| `i64.popcnt` | `0x7b` |


Extend - WebAssembly

Extend
======

The **`extend`** instructions, are used to convert (extend) numbers of type `i32` to type `i64`. There are signed and unsigned versions of this instruction.

Try it
------

Syntax
------

```wasm
;; push an i32 onto the stack
i32.const 10

;; sign-extend from i32 to i64
i64.extend_i32_s

;; the top item on the stack will now be the value 10 of type i64
```

| Instruction | Binary opcode |
| --- | --- |
| `i64.extend_i32_s` | `0xac` |
| `i64.extend_i32_u` | `0xad` |


Copy sign - WebAssembly

Copy sign
=========

The **`copysign`** instructions, are used to copy just the sign bit from one number to another.

Try it
------

Syntax
------

```wasm
;; load two numbers onto the stack
f32.const 10
f32.const -1

;; copy just the sign bit from the second number (-1) to the first (10)
f32.copysign

;; the top item on the stack will now be -10
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.copysign` | `0x98` |
| `f64.copysign` | `0xa6` |


Demote - WebAssembly

Demote
======

The **`demote`** instruction, is used to convert (demote) numbers of type `f64` to type `f32`.

Try it
------

Syntax
------

```wasm
;; push an f64 onto the stack
f64.const 10.5

;; demote from f64 to f32
f32.demote_f64

;; the top item on the stack will now be the value 10.5 of type f32
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.demote_f64` | `0xb6` |


Floor - WebAssembly

Floor
=====

The **`floor`** instructions, are used for getting the value of a number rounded down to the next integer.

**`floor`** differs from **`trunc`** when used on negative numbers, **`floor`** will round down in those cases while **`trunc`** will round up.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const -2.7

;; round down
f32.floor

;; the top item on the stack will now be -3
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.floor` | `0x8e` |
| `f64.floor` | `0x9c` |


Truncate (float to float) - WebAssembly

Truncate (float to float)
=========================

The **`trunc`** instructions, short for *truncate*, are used for getting the value of a number without its fractional part.

**`trunc`** differs from **`floor`** when used on negative numbers, **`floor`** will round down in those cases while **`trunc`** will round up.

There's another **`trunc`** instruction that truncates the fractional part of a floating point and converts it to an integer.

Try it
------

Syntax
------

```wasm
;; load a number onto the stack
f32.const 2.7

;; discard the fractional part (.7)
f32.trunc

;; the top item on the stack will now be 2
```

| Instruction | Binary opcode |
| --- | --- |
| `f32.trunc` | `0x8f` |
| `f64.trunc` | `0x9d` |