Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Practical WebAssembly
Practical WebAssembly

Practical WebAssembly: Explore the fundamentals of WebAssembly programming using Rust

eBook
€21.99 €31.99
Paperback
€38.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Practical WebAssembly

Chapter 1: Understanding LLVM

JavaScript is one of the most popular programming languages. However, JavaScript has two main disadvantages:

  • Unpredictable performance

JavaScript executes inside the environment and runtime provided by JavaScript engines. There are various JavaScript engines (V8, WebKit, and Gecko). All of them were built differently and run the same JavaScript code in a different way. Added to that, JavaScript is dynamically typed. This means JavaScript engines should guess the type while executing the JavaScript code. These factors lead to unpredictable performance in JavaScript execution. The optimizations for one type of JavaScript engine may cause undesirable side effects on other types of JavaScript engines. This leads to unpredictable performance.

  • Bundle size

The JavaScript engine waits until it downloads the entire JavaScript file before parsing and executing. The larger the JavaScript file, the longer the wait will be. This will degrade your application's performance. Bundlers such as webpack help to minimize the bundle size. But when your application grows, the bundle size grows exponentially.

Is there a tool that provides native performance and comes in a much smaller size? Yes, WebAssembly.

WebAssembly is the future of web and node development. WebAssembly is statically typed and precompiled, and thus it provides better performance than JavaScript. Precompilation of the binary provides an option to generate tiny binary bundles. WebAssembly allows languages such as Rust, C, and C++ to be compiled into binaries that run inside the JavaScript engine along with JavaScript. All WebAssembly compilers use LLVM underneath to convert the native code into WebAssembly binary code. Thus, it is important to understand what LLVM is and how it works.

In this chapter, we will learn what the various components of a compiler are and how they work. Then, we will explore what LLVM is and how it helps the compiled languages. Finally, we will see how the LLVM compiler compiles native code. We will cover the following topics in this chapter:

  • Understanding compilers
  • Exploring LLVM
  • LLVM in action

Technical requirements

We will make use of Clang, which is a compiler that compiles C/C++ code into native code.

For Linux and Mac users, Clang should be available out of the box.

For Windows users, Clang can be installed from the following link: https://llvm.org/docs/GettingStarted.html?highlight=installing%20clang%20windows#getting-the-source-code-and-building-llvm to install Clang.

You can find the code files present in this chapter on GitHub at https://github.com/PacktPublishing/Practical-WebAssembly

Understanding compilers

Programming languages are broadly classified into compiled and interpreted languages.

In the compiled world, the code is first compiled into target machine code. This process of converting the code into binary is called compilation. The software program that converts the code into target machine code is called a compiler. During the compilation, the compiler runs a series of checks, passes, and validation on the code written and generates an efficient and optimized binary. A few examples of compiled languages are C, C++, and Rust.

In the interpreted world, the code is read and executed in a single pass. Since the compilation happens at runtime, the generated machine code is not as optimized as its compiled counterpart. Interpreted languages are significantly slower than compiled ones, but they provide dynamic typing and a smaller program size.

In this book, we will focus only on compiled languages.

Compiled languages

A compiler is a translator that translates source code into machine code (or in a more abstract way, converts the code from one programming language to another). A compiler is complicated because it should understand the language in which the source code is written (its syntax, semantics, and context); it should also understand the target machine code (its syntax, semantics, and context) and should create a representation that maps the source code into the target machine code.

A compiler has the following components:

  • Frontend – The frontend is responsible for handling the source language.
  • Optimizer – The optimizer is responsible for optimizing the code.
  • Backend – The backend is responsible for handling the target language.
 Figure 1.1 – Components of a compiler

Figure 1.1 – Components of a compiler

Frontend

The frontend focuses on handling the source language. The frontend parses the code upon receiving it. The code is then checked for any grammar or syntax issues. After that, the code is converted (mapped) into an intermediate representation (IR). Consider IR as a format that represents the code that the compiler processes. The IR is the compiler's version of your code.

Optimizer

The second component in the compiler is the optimizer. This is optional, but as the name indicates, the optimizer analyzes the IR and transforms it into a much more efficient one. Few compilers have multiple IRs. The compiler efficiently optimizes the code on every pass over the IR. The optimizer is an IR-to-IR transformer. The optimizer analyzes, runs passes, and rewrites the IR. The optimizations here include removing redundant computations, eliminating dead code (code that cannot be reached), and various other optimizing options, which will be explored in future chapters. It is important to note that the optimizers need not be language-specific. Since they act on the IR, they can be built as a generic component and reused with multiple languages.

Backend

The backend focuses on producing the target language. The backend receives the generated (optimized) IR and converts it into another language (such as machine code). It is also possible to chain multiple backends that convert the code into some other languages. The backend is responsible for generating the target machine code from the IR. This machine code is the actual code that runs on the bare metal. In order to produce efficient machine code, the backend should understand the architecture in which the code is executed.

Machine code is a set of instructions that instructs the machine to store some values in registers and do some computation on them. For example, the generated machine code is responsible for efficiently storing a 64-bit number in 32-bit architecture in a free register (and things like that). The backend should understand the target environment to efficiently create a set of instructions and properly select and schedule the instructions to increase the performance of the application execution.

Compiler efficiency

The faster the execution, the better the performance.

The efficiency of the compiler depends on how it selects the instruction, allocates the register, and schedules the instruction execution in the given architecture. An instruction set is a set of operations supported by a processor, and this overall design is called an Instruction Set Architecture (ISA). The ISA is an abstract model of a computer and is often referred to as computer architecture. Various processors convert the ISA in different implementations. The different implementations may vary in performance. The ISA is an interface between the hardware and the software.

If you are implementing a new programming language and you want this language to be running on different architectures (or, more abstractly, different processors), then you should build the backend for each of these architectures/targets. But building these backends for every architecture is difficult and will take time, cost, and effort to embark on a language creation journey.

What if we create a common IR and build a compiler that converts this IR into machine code that runs efficiently on various architecture? Let's call this compiler a low-level virtual machine. Now, the role of your frontend in the compiler chain is just to convert the source code into an IR that is compatible with a low-level virtual machine (such as LLVM). Now, the general purpose of a low-level virtual machine is to be a common reusable component that maps the IR into native code for various targets. But the low-level virtual machine will only understand the common IR. This IR is called the LLVM IR and the compiler is called LLVM.

Exploring LLVM

LLVM is a part of the LLVM Project. The LLVM Project hosts compilers and toolchain technologies. The LLVM core is a part of the LLVM Project. The LLVM core is responsible for providing source- and target-independent optimization and for generating code for many CPU architectures. This enables language developers to just create a frontend that generates an LLVM-compatible IR or LLVM IR from the source language.

Did You Know?

LLVM is not an acronym. When the project was started as a research project, it meant Low-Level Virtual Machine. But later, it was decided to use the name as it is rather than as an acronym.

The main advantages of LLVM are as follows:

  • LLVM uses a simple low-level language that looks similar to C.
  • LLVM is strongly typed.
  • LLVM has strictly defined semantics.
  • LLVM has accurate and precise garbage collection.
  • LLVM provides various optimizations that you can choose based on the requirement. It has aggressive, scalar, inter-procedural, simple-loop, and profile-driven optimizations.
  • LLVM provides various compilation models. They are link time, install time, runtime, and offline.
  • LLVM generates machine code for various target architectures.
  • LLVM provides DWARF debugging information.

    Note

    DWARF is a debugging file format used by many compilers and debuggers to support source-level debugging. DWARF is architecture-independent and applicable to any processor or operating system. It uses a data structure called a Debugging Information Entry (DIE) to represent each variable, type, procedure, and so on.

    If you want to explore more about DWARF, refer to http://dwarfstd.org/doc/Debugging%20using%20DWARF-2012.pdf.

    Important Note

    LLVM is not a single monolithic project. It is a collection of subprojects and other projects. These projects are used by various languages, such as Ruby, Python, Haskell, Rust, and D, for compilation.

Now that we have an understanding of compilers and LLVM, we will see how it is used.

LLVM in action

In this section, let's use LLVM's Clang compiler to compile native code into LLVM IR. This will give a better idea of how LLVM works and will be useful for understanding how the compilers use LLVM in future chapters.

We first create a C file called sum.c and enter the following contents:

 $ touch sum.c
 // sum.c
 unsigned sum(unsigned a, unsigned b) {
    return a + b;
}

The sum.c file contains a simple sum function that takes in two unsigned integers and returns the sum of them. LLVM provides the Clang LLVM compiler to compile the C source code. In order to generate the LLVM IR, run the following command:

$ clang -S -O3 -emit-llvm sum.c

We provided the Clang compiler with the -S, -O3, and -emit-llvm options:

  • The -S option specifies for the compiler to only run the preprocess and compilation steps.
  • The -O3 option specifies for the compiler to generate a well-optimized binary.
  • The -emit-llvm option specifies for the compiler to emit the LLVM IR while generating the machine code.

The preceding code will print out the following LLVM IR:

define i32 @sum(i32, i32) local_unnamed_addr #0 {
  %3 = add i32 %1, %0
  ret i32 %3
}

The syntax of the LLVM IR is structurally much closer to C. The define keyword defines the beginning of a function. Next to that is the return type of the function, i32. Next, we have the name of the function, @sum.

Important Note

Note the @ symbol there? LLVM uses @ to identify the global variables and function. It uses % to identify the local variables.

After the function name, we state the types of the input argument (i32 in this case). The local_unnamed_addr attribute indicates that the address is known not to be significant within the module. The variables in the LLVM IR are immutable. That is, once you define them, you cannot change them. So inside the `block`, we create a new local value, %3, and assign it the value of add. add is an opcode that takes in the `type` of the arguments followed by the two arguments, %0 and %1. %0 and %1 denote the first and second local variables. Finally, we return %3 with the ret keyword followed by the `type`.

This IR is transformable; that is, the IR can be transformed from the textual representation into memory and then into actual bit code that run on the bare metal. Also, from bit code, you can transform them back to the textual representation.

Imagine that you are writing a new language. The success of the language depends on how versatile the language is at performing on various architectures. Generating optimized byte codes for various architectures (such as x86, ARM, and others) takes a long time and it is not easy. LLVM provides an easy way to achieve it. Instead of targeting the different architecture, create a compiler frontend that converts the source code into an LLVM compatible IR. Then, LLVM will convert the IR into efficient and optimized byte code that runs on any architecture.

Note

LLVM is an umbrella project. It has so many components that you could write a set of books on them. Covering the whole of LLVM and how to install and run them is beyond the scope of this book. If you are interested in learning more about various components of LLVM, how they work, and how to use them, then check out the website: https://llvm.org.

Summary

In this chapter, we have seen how compiled languages work and how LLVM helps to compile them. We have compiled a sample program with LLVM to understand how it works. In the next chapter, we'll explore Emscripten, a tool that converts C/C++ into a WebAssembly module. Emscripten uses the LLVM backend to do the compilation.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand the Rust programming language and WebAssembly concepts for web development
  • Build web, mobile, and embedded apps using WebAssembly
  • Enhance the scalability and resilience of your web apps

Description

Rust is an open source language tuned toward safety, concurrency, and performance. WebAssembly brings all the capabilities of the native world into the JavaScript world. Together, Rust and WebAssembly provide a way to create robust and performant web applications. They help make your web applications blazingly fast and have small binaries. Developers working with JavaScript will be able to put their knowledge to work with this practical guide to developing faster and maintainable code. Complete with step-by-step explanations of essential concepts, examples, and self-assessment questions, you’ll begin by exploring WebAssembly, using the various tools provided by the ecosystem, and understanding how to use WebAssembly and JavaScript together to build a high-performing application. You’ll then learn binary code to work with a variety of tools that help you to convert native code into WebAssembly. The book will introduce you to the world of Rust and the ecosystem that makes it easy to build/ship WebAssembly-based applications. By the end of this WebAssembly Rust book, you’ll be able to create and ship your own WebAssembly applications using Rust and JavaScript, understand how to debug, and use the right tools to optimize and deliver high-performing applications.

Who is this book for?

This book is for JavaScript developers who want to deliver better performance and ship type-safe code. Rust developers or backend engineers looking to build full-stack applications without worrying too much about JavaScript programming will also find the book useful.

What you will learn

  • Explore WebAssembly and the different tools available in the WebAssembly ecosystem
  • Understand the raw WebAssembly binary and the WebAssembly text format
  • Use the Web and JavaScript API with wasm-bindgen
  • Optimize Rust and WebAssembly for high performance
  • Run and debug WebAssembly and Rust code
  • Explore various tools available in the RustWASM ecosystem

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 02, 2022
Length: 232 pages
Edition : 1st
Language : English
ISBN-13 : 9781838828004
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 02, 2022
Length: 232 pages
Edition : 1st
Language : English
ISBN-13 : 9781838828004
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 95.97
Practical WebAssembly
€38.99
Game Development with Rust and WebAssembly
€32.99
Rust Web Development with Rocket
€23.99
Total 95.97 Stars icon

Table of Contents

14 Chapters
Section 1: Introduction to WebAssembly Chevron down icon Chevron up icon
Chapter 1: Understanding LLVM Chevron down icon Chevron up icon
Chapter 2: Understanding Emscripten Chevron down icon Chevron up icon
Chapter 3: Exploring WebAssembly Modules Chevron down icon Chevron up icon
Section 2: WebAssembly Tools Chevron down icon Chevron up icon
Chapter 4: Understanding WebAssembly Binary Toolkit Chevron down icon Chevron up icon
Chapter 5: Understanding Sections in WebAssembly Modules Chevron down icon Chevron up icon
Chapter 6: Installing and Using Binaryen Chevron down icon Chevron up icon
Section 3: Rust and WebAssembly Chevron down icon Chevron up icon
Chapter 7: Integrating Rust with WebAssembly Chevron down icon Chevron up icon
Chapter 8: Bundling WebAssembly Using wasm-pack Chevron down icon Chevron up icon
Chapter 9: Crossing the Boundary between Rust and WebAssembly Chevron down icon Chevron up icon
Chapter 10: Optimizing Rust and WebAssembly Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(4 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Sami Jul 18, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Sendil does a great job explaining the ins and out of WebAssembly, how it relates to the JavaScript you already know and how to generate WASM from other languages, such as C, C++ and rust (without presuming that you know any of these).What I appreciated most about the book, was its logical progression, where Sendil first takes you through some background (but not too much) and then lets you get your hands dirty with code examples. And they work (mostly; some minor Mac-to-Windows translation is needed, unless you're using WSL)!Great book! Well worth my time!
Amazon Verified review Amazon
L. Smith Jun 20, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I haven't finished reading it yet (it's a relatively short book but I'm swapped with work). From what I've read so far though I would recommend the book (especially if you're a Rust programmer / developer). It's written in a way which I think anyone can understand if they have the desire to learn. The title (Practical Web Assembly) is VERY accurate! I'll try to leave an update after I finish reading the rest of the book.
Amazon Verified review Amazon
Rhonda Jenkins Clark Oct 05, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a programmer and developer who uses JavaScript, this book interests me because of its usefulness to help optimize and get better performance out of JavaScript. I have always wanted to explore WebAssembly but did not because I thought it was overly complex. I like that this book is well written and has code examples to follow. I would recommend it to anyone wanting to write better, more performant code.
Amazon Verified review Amazon
Amazon Customer Dec 25, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I greatly enjoyed this book - it's a very healthy summary of the mechanics of WebAssembly and the processes and code that make running native code in browsers possible. I had worked through and built WebAssembly's Game of Life tutorial for Rust online using wasm-pack, and had lots of fun doing so, working with the wasm-pack bundler.But this book takes the reader on a sequential, iterative journey through the fundamental layers and steps necessary to generate WASM modules and then talk to them in web browsers from JavaScript (and vice versa). It's a good discussion if you want to learn how things work under the hood and get some very helpful programming examples with useful patterns, too, that you can use in your own projects.Compilation, bundling, project structure, dependencies, optimization and distribution are adequately covered. It's a great read!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.