cranelift_frontend/
lib.rs

1//! Cranelift IR builder library.
2//!
3//! Provides a straightforward way to create a Cranelift IR function and fill it with instructions
4//! corresponding to your source program written in another language.
5//!
6//! To get started, create an [`FunctionBuilderContext`](struct.FunctionBuilderContext.html) and
7//! pass it as an argument to a [`FunctionBuilder`].
8//!
9//! # Mutable variables and Cranelift IR values
10//!
11//! The most interesting feature of this API is that it provides a single way to deal with all your
12//! variable problems. Indeed, the [`FunctionBuilder`] struct has a
13//! type `Variable` that should be an index of your source language variables. Then, through
14//! calling the functions
15//! [`declare_var`](FunctionBuilder::declare_var), [`def_var`](FunctionBuilder::def_var) and
16//! [`use_var`](FunctionBuilder::use_var), the [`FunctionBuilder`] will create for you all the
17//! Cranelift IR values corresponding to your variables.
18//!
19//! This API has been designed to help you translate your mutable variables into
20//! [`SSA`](https://en.wikipedia.org/wiki/Static_single_assignment_form) form.
21//! [`use_var`](FunctionBuilder::use_var) will return the Cranelift IR value
22//! that corresponds to your mutable variable at a precise point in the program. However, if you know
23//! beforehand that one of your variables is defined only once, for instance if it is the result
24//! of an intermediate expression in an expression-based language, then you can translate it
25//! directly by the Cranelift IR value returned by the instruction builder. Using the
26//! [`use_var`](FunctionBuilder::use_var) API for such an immutable variable
27//! would also work but with a slight additional overhead (the SSA algorithm does not know
28//! beforehand if a variable is immutable or not).
29//!
30//! The moral is that you should use these three functions to handle all your mutable variables,
31//! even those that are not present in the source code but artifacts of the translation. It is up
32//! to you to keep a mapping between the mutable variables of your language and their [`Variable`]
33//! index that is used by Cranelift. Caution: as the [`Variable`] is used by Cranelift to index an
34//! array containing information about your mutable variables, when you create a new [`Variable`]
35//! with `Variable::new(var_index)` you should make sure that `var_index`
36//! is provided by a counter incremented by 1 each time you encounter a new mutable variable.
37//!
38//! # Example
39//!
40//! Here is a pseudo-program we want to transform into Cranelift IR:
41//!
42//! ```clif
43//! function(x) {
44//! x, y, z : i32
45//! block0:
46//!    y = 2;
47//!    z = x + y;
48//!    jump block1
49//! block1:
50//!    z = z + y;
51//!    brif y, block3, block2
52//! block2:
53//!    z = z - x;
54//!    return y
55//! block3:
56//!    y = y - x
57//!    jump block1
58//! }
59//! ```
60//!
61//! Here is how you build the corresponding Cranelift IR function using [`FunctionBuilderContext`]:
62//!
63//! ```rust
64//! use cranelift_codegen::entity::EntityRef;
65//! use cranelift_codegen::ir::types::*;
66//! use cranelift_codegen::ir::{AbiParam, UserFuncName, Function, InstBuilder, Signature};
67//! use cranelift_codegen::isa::CallConv;
68//! use cranelift_codegen::settings;
69//! use cranelift_codegen::verifier::verify_function;
70//! use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
71//!
72//! let mut sig = Signature::new(CallConv::SystemV);
73//! sig.returns.push(AbiParam::new(I32));
74//! sig.params.push(AbiParam::new(I32));
75//! let mut fn_builder_ctx = FunctionBuilderContext::new();
76//! let mut func = Function::with_name_signature(UserFuncName::user(0, 0), sig);
77//! {
78//!     let mut builder = FunctionBuilder::new(&mut func, &mut fn_builder_ctx);
79//!
80//!     let block0 = builder.create_block();
81//!     let block1 = builder.create_block();
82//!     let block2 = builder.create_block();
83//!     let block3 = builder.create_block();
84//!     let x = builder.declare_var(I32);
85//!     let y = builder.declare_var(I32);
86//!     let z = builder.declare_var(I32);
87//!     builder.append_block_params_for_function_params(block0);
88//!
89//!     builder.switch_to_block(block0);
90//!     builder.seal_block(block0);
91//!     {
92//!         let tmp = builder.block_params(block0)[0]; // the first function parameter
93//!         builder.def_var(x, tmp);
94//!     }
95//!     {
96//!         let tmp = builder.ins().iconst(I32, 2);
97//!         builder.def_var(y, tmp);
98//!     }
99//!     {
100//!         let arg1 = builder.use_var(x);
101//!         let arg2 = builder.use_var(y);
102//!         let tmp = builder.ins().iadd(arg1, arg2);
103//!         builder.def_var(z, tmp);
104//!     }
105//!     builder.ins().jump(block1, &[]);
106//!
107//!     builder.switch_to_block(block1);
108//!     {
109//!         let arg1 = builder.use_var(y);
110//!         let arg2 = builder.use_var(z);
111//!         let tmp = builder.ins().iadd(arg1, arg2);
112//!         builder.def_var(z, tmp);
113//!     }
114//!     {
115//!         let arg = builder.use_var(y);
116//!         builder.ins().brif(arg, block3, &[], block2, &[]);
117//!     }
118//!
119//!     builder.switch_to_block(block2);
120//!     builder.seal_block(block2);
121//!     {
122//!         let arg1 = builder.use_var(z);
123//!         let arg2 = builder.use_var(x);
124//!         let tmp = builder.ins().isub(arg1, arg2);
125//!         builder.def_var(z, tmp);
126//!     }
127//!     {
128//!         let arg = builder.use_var(y);
129//!         builder.ins().return_(&[arg]);
130//!     }
131//!
132//!     builder.switch_to_block(block3);
133//!     builder.seal_block(block3);
134//!
135//!     {
136//!         let arg1 = builder.use_var(y);
137//!         let arg2 = builder.use_var(x);
138//!         let tmp = builder.ins().isub(arg1, arg2);
139//!         builder.def_var(y, tmp);
140//!     }
141//!     builder.ins().jump(block1, &[]);
142//!     builder.seal_block(block1);
143//!
144//!     builder.finalize();
145//! }
146//!
147//! let flags = settings::Flags::new(settings::builder());
148//! let res = verify_function(&func, &flags);
149//! println!("{}", func.display());
150//! if let Err(errors) = res {
151//!     panic!("{}", errors);
152//! }
153//! ```
154
155#![deny(missing_docs)]
156#![no_std]
157
158extern crate alloc;
159
160#[cfg(feature = "std")]
161#[macro_use]
162extern crate std;
163
164#[cfg(not(feature = "std"))]
165use hashbrown::{HashMap, HashSet};
166#[cfg(feature = "std")]
167use std::collections::{HashMap, HashSet};
168
169pub use crate::frontend::{FuncInstBuilder, FunctionBuilder, FunctionBuilderContext};
170pub use crate::switch::Switch;
171pub use crate::variable::Variable;
172
173#[cfg(test)]
174macro_rules! assert_eq_output {
175    ( $left:expr, $right:expr $(,)? ) => {{
176        let left = $left;
177        let left = left.trim();
178
179        let right = $right;
180        let right = right.trim();
181
182        assert_eq!(
183            left,
184            right,
185            "assertion failed, output not equal:\n\
186             \n\
187             =========== Diff ===========\n\
188             {}\n\
189             =========== Left ===========\n\
190             {left}\n\
191             =========== Right ===========\n\
192             {right}\n\
193             ",
194            similar::TextDiff::from_lines(left, right)
195                .unified_diff()
196                .header("left", "right")
197        )
198    }};
199}
200
201mod frontend;
202mod ssa;
203mod switch;
204mod variable;
205
206/// Version number of this crate.
207pub const VERSION: &str = env!("CARGO_PKG_VERSION");