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 = Variable::new(0);
85//!     let y = Variable::new(1);
86//!     let z = Variable::new(2);
87//!     builder.declare_var(x, I32);
88//!     builder.declare_var(y, I32);
89//!     builder.declare_var(z, I32);
90//!     builder.append_block_params_for_function_params(block0);
91//!
92//!     builder.switch_to_block(block0);
93//!     builder.seal_block(block0);
94//!     {
95//!         let tmp = builder.block_params(block0)[0]; // the first function parameter
96//!         builder.def_var(x, tmp);
97//!     }
98//!     {
99//!         let tmp = builder.ins().iconst(I32, 2);
100//!         builder.def_var(y, tmp);
101//!     }
102//!     {
103//!         let arg1 = builder.use_var(x);
104//!         let arg2 = builder.use_var(y);
105//!         let tmp = builder.ins().iadd(arg1, arg2);
106//!         builder.def_var(z, tmp);
107//!     }
108//!     builder.ins().jump(block1, &[]);
109//!
110//!     builder.switch_to_block(block1);
111//!     {
112//!         let arg1 = builder.use_var(y);
113//!         let arg2 = builder.use_var(z);
114//!         let tmp = builder.ins().iadd(arg1, arg2);
115//!         builder.def_var(z, tmp);
116//!     }
117//!     {
118//!         let arg = builder.use_var(y);
119//!         builder.ins().brif(arg, block3, &[], block2, &[]);
120//!     }
121//!
122//!     builder.switch_to_block(block2);
123//!     builder.seal_block(block2);
124//!     {
125//!         let arg1 = builder.use_var(z);
126//!         let arg2 = builder.use_var(x);
127//!         let tmp = builder.ins().isub(arg1, arg2);
128//!         builder.def_var(z, tmp);
129//!     }
130//!     {
131//!         let arg = builder.use_var(y);
132//!         builder.ins().return_(&[arg]);
133//!     }
134//!
135//!     builder.switch_to_block(block3);
136//!     builder.seal_block(block3);
137//!
138//!     {
139//!         let arg1 = builder.use_var(y);
140//!         let arg2 = builder.use_var(x);
141//!         let tmp = builder.ins().isub(arg1, arg2);
142//!         builder.def_var(y, tmp);
143//!     }
144//!     builder.ins().jump(block1, &[]);
145//!     builder.seal_block(block1);
146//!
147//!     builder.finalize();
148//! }
149//!
150//! let flags = settings::Flags::new(settings::builder());
151//! let res = verify_function(&func, &flags);
152//! println!("{}", func.display());
153//! if let Err(errors) = res {
154//!     panic!("{}", errors);
155//! }
156//! ```
157
158#![deny(missing_docs)]
159#![no_std]
160
161extern crate alloc;
162
163#[cfg(feature = "std")]
164#[macro_use]
165extern crate std;
166
167#[cfg(not(feature = "std"))]
168use hashbrown::{HashMap, HashSet};
169#[cfg(feature = "std")]
170use std::collections::{HashMap, HashSet};
171
172pub use crate::frontend::{FuncInstBuilder, FunctionBuilder, FunctionBuilderContext};
173pub use crate::switch::Switch;
174pub use crate::variable::Variable;
175
176#[cfg(test)]
177macro_rules! assert_eq_output {
178    ( $left:expr, $right:expr $(,)? ) => {{
179        let left = $left;
180        let left = left.trim();
181
182        let right = $right;
183        let right = right.trim();
184
185        assert_eq!(
186            left,
187            right,
188            "assertion failed, output not equal:\n\
189             \n\
190             =========== Diff ===========\n\
191             {}\n\
192             =========== Left ===========\n\
193             {left}\n\
194             =========== Right ===========\n\
195             {right}\n\
196             ",
197            similar::TextDiff::from_lines(left, right)
198                .unified_diff()
199                .header("left", "right")
200        )
201    }};
202}
203
204mod frontend;
205mod ssa;
206mod switch;
207mod variable;
208
209/// Version number of this crate.
210pub const VERSION: &str = env!("CARGO_PKG_VERSION");