Using LLVM from Rust to generate WebAssembly binaries

Setup

[dependencies]
llvm-sys = "60.0.2"

Providing our LLVM build to llvm-sys

LLVM_SYS_60_PREFIX=/path/to/llvm cargo build

Generating bitcode

llvm-dis main.bc -o main.ll
; ModuleID = 'main.bc'
source_filename = "main"

WebAssembly? Yes, please!

LLVMSetTarget(module, c_str!("wasm32-unknown-unknown-elf"));
// etc
LLVMWriteBitcodeToFile(module, c_str!("main.bc"));

Compiling LLVM bitcode to WebAssembly

llc -march=wasm32 main.bc -o main.s
s2wasm main.s -o main.wast
(module
(table 0 anyfunc)
(memory $0 1)
(export "memory" (memory $0))
)
s2wasm --emit-binary main.s -o main.wasm

Hello, world.

(module
(type $FUNCSIG$vi (func (param i32)))
(import "env" "log" (func $log (param i32)))
(table 0 anyfunc)
(memory $0 1)
(data (i32.const 16) "hello world\00")
(export "memory" (memory $0))
(export "main" (func $main))
(func $main (; 1 ;)
(call $log
(i32.const 16)
)
)
)

Running the WebAssembly from JavaScript

Summary

Footnotes

llc -march=wasm32 -filetype=obj main.bc -o main.o
lld -flavor wasm --allow-undefined main.o -o main.wasm

--

--

--

WebAssembly • Reactive programming • PL enthusiast • Web Platform @ Netflix

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Successfully Outsource Software Development Projects

Things you don’t expect from netlink

Paradise: The Perfect Pairing Station for Agile Software Development

Lance Walter of Neo4j: 5 Things You Need To Know To Successfully Run a Live Virtual Event

My journey as a non-circuital student to becoming a software engineer

Amazon Web Services (AWS) — Serverless Architecture

Move over VLOOKUP, here comes XLOOKUP — The Excel Club

Runbook Automation for VMSS Windows Instances

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jay Phelps

Jay Phelps

WebAssembly • Reactive programming • PL enthusiast • Web Platform @ Netflix

More from Medium

The ultimate guide to ENARX

Exchange messages with IBM MQ using Rust

Rust Foo: NTP Client (Part 1)

What’s a “Thread Boundary” in Rust’s Async-Await ?