]> git.proxmox.com Git - rustc.git/blame - src/doc/rustc-dev-guide/src/codegen.md
New upstream version 1.43.0+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / src / codegen.md
CommitLineData
a1dfa0c6
XL
1# Code generation
2
3Code generation or "codegen" is the part of the compiler that actually
4generates an executable binary. rustc uses LLVM for code generation.
5
6> NOTE: If you are looking for hints on how to debug code generation bugs,
532ac7d7 7> please see [this section of the debugging chapter][debugging].
a1dfa0c6 8
532ac7d7 9[debugging]: codegen/debugging.html
a1dfa0c6
XL
10
11## What is LLVM?
12
13All of the preceding chapters of this guide have one thing in common: we never
14generated any executable machine code at all! With this chapter, all of that
15changes.
16
17Like most compilers, rustc is composed of a "frontend" and a "backend". The
18"frontend" is responsible for taking raw source code, checking it for
19correctness, and getting it into a format `X` from which we can generate
20executable machine code. The "backend" then takes that format `X` and produces
21(possibly optimized) executable machine code for some platform. All of the
22previous chapters deal with rustc's frontend.
23
24rustc's backend is [LLVM](https://llvm.org), "a collection of modular and
25reusable compiler and toolchain technologies". In particular, the LLVM project
26contains a pluggable compiler backend (also called "LLVM"), which is used by
27many compiler projects, including the `clang` C compiler and our beloved
28`rustc`.
29
30LLVM's "format `X`" is called LLVM IR. It is basically assembly code with
31additional low-level types and annotations added. These annotations are helpful
32for doing optimizations on the LLVM IR and outputted machine code. The end
33result of all this is (at long last) something executable (e.g. an ELF object
34or wasm).
35
36There are a few benefits to using LLVM:
37
38- We don't have to write a whole compiler backend. This reduces implementation
39 and maintenance burden.
40- We benefit from the large suite of advanced optimizations that the LLVM
41 project has been collecting.
dfeec247 42- We can automatically compile Rust to any of the platforms for which LLVM has
a1dfa0c6
XL
43 support. For example, as soon as LLVM added support for wasm, voila! rustc,
44 clang, and a bunch of other languages were able to compile to wasm! (Well,
45 there was some extra stuff to be done, but we were 90% there anyway).
46- We and other compiler projects benefit from each other. For example, when the
47 [Spectre and Meltdown security vulnerabilities][spectre] were discovered,
48 only LLVM needed to be patched.
49
50[spectre]: https://meltdownattack.com/
51
52## Generating LLVM IR
53
54TODO