Skip to content

Commit 53bfc67

Browse files
committed
Centralize all configuration into config.rs
1 parent 1ee0aa9 commit 53bfc67

File tree

10 files changed

+94
-57
lines changed

10 files changed

+94
-57
lines changed

Readme.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,10 @@ This will build your project with rustc_codegen_cranelift instead of the usual L
4444

4545
For additional ways to use rustc_codegen_cranelift like the JIT mode see [usage.md](docs/usage.md).
4646

47-
## Env vars
47+
## Configuration
4848

49-
See [env_vars.md](docs/env_vars.md) for all env vars used by rustc_codegen_cranelift.
49+
See the documentation on the `BackendConfig` struct in [config.rs](src/config.rs) for all
50+
configuration options.
5051

5152
## Not yet supported
5253

docs/env_vars.md

-15
This file was deleted.

scripts/ext_config.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
set -e
66

77
export CG_CLIF_DISPLAY_CG_TIME=1
8-
export CG_CLIF_INCR_CACHE_DISABLED=1
8+
export CG_CLIF_DISABLE_INCR_CACHE=1
99

1010
export HOST_TRIPLE=$(rustc -vV | grep host | cut -d: -f2 | tr -d " ")
1111
export TARGET_TRIPLE=${TARGET_TRIPLE:-$HOST_TRIPLE}

src/backend.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ use std::convert::{TryFrom, TryInto};
55
use rustc_data_structures::fx::FxHashMap;
66
use rustc_session::Session;
77

8+
use cranelift_codegen::isa::TargetIsa;
89
use cranelift_module::FuncId;
10+
use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
911

1012
use object::write::*;
1113
use object::{RelocationEncoding, SectionKind, SymbolFlags};
1214

13-
use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
14-
1515
use gimli::SectionId;
1616

1717
use crate::debuginfo::{DebugReloc, DebugRelocName};
@@ -113,7 +113,7 @@ impl WriteDebugInfo for ObjectProduct {
113113
}
114114

115115
pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object)) -> Vec<u8> {
116-
let triple = crate::build_isa(sess).triple().clone();
116+
let triple = crate::target_triple(sess);
117117

118118
let binary_format = match triple.binary_format {
119119
target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf,
@@ -141,9 +141,9 @@ pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object
141141
metadata_object.write().unwrap()
142142
}
143143

144-
pub(crate) fn make_module(sess: &Session, name: String) -> ObjectModule {
144+
pub(crate) fn make_module(sess: &Session, isa: Box<dyn TargetIsa>, name: String) -> ObjectModule {
145145
let mut builder = ObjectBuilder::new(
146-
crate::build_isa(sess),
146+
isa,
147147
name + ".o",
148148
cranelift_module::default_libcall_names(),
149149
)

src/config.rs

+59-7
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
1+
use std::env;
12
use std::str::FromStr;
23

4+
fn bool_env_var(key: &str) -> bool {
5+
env::var(key).as_ref().map(|val| &**val) == Ok("1")
6+
}
7+
38
#[derive(Copy, Clone, Debug)]
49
pub enum CodegenMode {
510
Aot,
611
Jit,
712
JitLazy,
813
}
914

10-
impl Default for CodegenMode {
11-
fn default() -> Self {
12-
CodegenMode::Aot
13-
}
14-
}
15-
1615
impl FromStr for CodegenMode {
1716
type Err = String;
1817

@@ -26,24 +25,77 @@ impl FromStr for CodegenMode {
2625
}
2726
}
2827

29-
#[derive(Copy, Clone, Debug, Default)]
28+
#[derive(Clone, Debug)]
3029
pub struct BackendConfig {
30+
/// Should the crate be AOT compiled or JIT executed.
31+
///
32+
/// Defaults to AOT compilation. Can be set using `-Cllvm-args=mode=...`.
3133
pub codegen_mode: CodegenMode,
34+
35+
/// When JIT mode is enable pass these arguments to the program.
36+
///
37+
/// Defaults to the value of `CG_CLIF_JIT_ARGS`.
38+
pub jit_args: Vec<String>,
39+
40+
/// Display the time it took to perform codegen for a crate.
41+
///
42+
/// Defaults to true when the `CG_CLIF_DISPLAY_CG_TIME` env var is set to 1 or false otherwise.
43+
/// Can be set using `-Cllvm-args=display_cg_time=...`.
44+
pub display_cg_time: bool,
45+
46+
/// Enable the Cranelift ir verifier for all compilation passes. If not set it will only run
47+
/// once before passing the clif ir to Cranelift for compilation.
48+
///
49+
/// Defaults to true when the `CG_CLIF_ENABLE_VERIFIER` env var is set to 1 or when cg_clif is
50+
/// compiled with debug assertions enabled or false otherwise. Can be set using
51+
/// `-Cllvm-args=enable_verifier=...`.
52+
pub enable_verifier: bool,
53+
54+
/// Don't cache object files in the incremental cache. Useful during development of cg_clif
55+
/// to make it possible to use incremental mode for all analyses performed by rustc without
56+
/// caching object files when their content should have been changed by a change to cg_clif.
57+
///
58+
/// Defaults to true when the `CG_CLIF_DISABLE_INCR_CACHE` env var is set to 1 or false
59+
/// otherwise. Can be set using `-Cllvm-args=disable_incr_cache=...`.
60+
pub disable_incr_cache: bool,
61+
}
62+
63+
impl Default for BackendConfig {
64+
fn default() -> Self {
65+
BackendConfig {
66+
codegen_mode: CodegenMode::Aot,
67+
jit_args: {
68+
let args = std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
69+
args.split(' ').map(|arg| arg.to_string()).collect()
70+
},
71+
display_cg_time: bool_env_var("CG_CLIF_DISPLAY_CG_TIME"),
72+
enable_verifier: cfg!(debug_assertions) || bool_env_var("CG_CLIF_ENABLE_VERIFIER"),
73+
disable_incr_cache: bool_env_var("CG_CLIF_DISABLE_INCR_CACHE"),
74+
}
75+
}
3276
}
3377

3478
impl BackendConfig {
3579
pub fn from_opts(opts: &[String]) -> Result<Self, String> {
80+
fn parse_bool(name: &str, value: &str) -> Result<bool, String> {
81+
value.parse().map_err(|_| format!("failed to parse value `{}` for {}", value, name))
82+
}
83+
3684
let mut config = BackendConfig::default();
3785
for opt in opts {
3886
if let Some((name, value)) = opt.split_once('=') {
3987
match name {
4088
"mode" => config.codegen_mode = value.parse()?,
89+
"display_cg_time" => config.display_cg_time = parse_bool(name, value)?,
90+
"enable_verifier" => config.enable_verifier = parse_bool(name, value)?,
91+
"disable_incr_cache" => config.disable_incr_cache = parse_bool(name, value)?,
4192
_ => return Err(format!("Unknown option `{}`", name)),
4293
}
4394
} else {
4495
return Err(format!("Invalid option `{}`", opt));
4596
}
4697
}
98+
4799
Ok(config)
48100
}
49101
}

src/driver/aot.rs

+14-13
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,6 @@ use cranelift_object::ObjectModule;
1616

1717
use crate::{prelude::*, BackendConfig};
1818

19-
fn new_module(tcx: TyCtxt<'_>, name: String) -> ObjectModule {
20-
let module = crate::backend::make_module(tcx.sess, name);
21-
assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
22-
module
23-
}
24-
2519
struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
2620

2721
impl<HCX> HashStable<HCX> for ModuleCodegenResult {
@@ -32,6 +26,7 @@ impl<HCX> HashStable<HCX> for ModuleCodegenResult {
3226

3327
fn emit_module(
3428
tcx: TyCtxt<'_>,
29+
backend_config: &BackendConfig,
3530
name: String,
3631
kind: ModuleKind,
3732
module: ObjectModule,
@@ -52,7 +47,7 @@ fn emit_module(
5247
tcx.sess.fatal(&format!("error writing object file: {}", err));
5348
}
5449

55-
let work_product = if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() {
50+
let work_product = if backend_config.disable_incr_cache {
5651
None
5752
} else {
5853
rustc_incremental::copy_cgu_workproduct_to_incr_comp_cache_dir(
@@ -110,11 +105,13 @@ fn module_codegen(
110105
let cgu = tcx.codegen_unit(cgu_name);
111106
let mono_items = cgu.items_in_deterministic_order(tcx);
112107

113-
let mut module = new_module(tcx, cgu_name.as_str().to_string());
108+
let isa = crate::build_isa(tcx.sess, &backend_config);
109+
let mut module = crate::backend::make_module(tcx.sess, isa, cgu_name.as_str().to_string());
110+
assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
114111

115112
let mut cx = crate::CodegenCx::new(
116113
tcx,
117-
backend_config,
114+
backend_config.clone(),
118115
&mut module,
119116
tcx.sess.opts.debuginfo != DebugInfo::None,
120117
);
@@ -144,6 +141,7 @@ fn module_codegen(
144141

145142
let codegen_result = emit_module(
146143
tcx,
144+
&backend_config,
147145
cgu.name().as_str().to_string(),
148146
ModuleKind::Regular,
149147
module,
@@ -193,14 +191,14 @@ pub(super) fn run_aot(
193191
}
194192
}
195193

196-
let modules = super::time(tcx, "codegen mono items", || {
194+
let modules = super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
197195
cgus.iter()
198196
.map(|cgu| {
199197
let cgu_reuse = determine_cgu_reuse(tcx, cgu);
200198
tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
201199

202200
match cgu_reuse {
203-
_ if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() => {}
201+
_ if backend_config.disable_incr_cache => {}
204202
CguReuse::No => {}
205203
CguReuse::PreLto => {
206204
return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
@@ -212,7 +210,7 @@ pub(super) fn run_aot(
212210
let (ModuleCodegenResult(module, work_product), _) = tcx.dep_graph.with_task(
213211
dep_node,
214212
tcx,
215-
(backend_config, cgu.name()),
213+
(backend_config.clone(), cgu.name()),
216214
module_codegen,
217215
rustc_middle::dep_graph::hash_result,
218216
);
@@ -228,14 +226,17 @@ pub(super) fn run_aot(
228226

229227
tcx.sess.abort_if_errors();
230228

231-
let mut allocator_module = new_module(tcx, "allocator_shim".to_string());
229+
let isa = crate::build_isa(tcx.sess, &backend_config);
230+
let mut allocator_module = crate::backend::make_module(tcx.sess, isa, "allocator_shim".to_string());
231+
assert_eq!(pointer_ty(tcx), allocator_module.target_config().pointer_type());
232232
let mut allocator_unwind_context = UnwindContext::new(tcx, allocator_module.isa(), true);
233233
let created_alloc_shim =
234234
crate::allocator::codegen(tcx, &mut allocator_module, &mut allocator_unwind_context);
235235

236236
let allocator_module = if created_alloc_shim {
237237
let ModuleCodegenResult(module, work_product) = emit_module(
238238
tcx,
239+
&backend_config,
239240
"allocator_shim".to_string(),
240241
ModuleKind::Allocator,
241242
allocator_module,

src/driver/jit.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
2727

2828
let imported_symbols = load_imported_symbols_for_jit(tcx);
2929

30-
let mut jit_builder =
31-
JITBuilder::with_isa(crate::build_isa(tcx.sess), cranelift_module::default_libcall_names());
30+
let isa = crate::build_isa(tcx.sess, &backend_config);
31+
let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
3232
jit_builder.hotswap(matches!(backend_config.codegen_mode, CodegenMode::JitLazy));
3333
crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
3434
jit_builder.symbols(imported_symbols);
@@ -44,9 +44,9 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
4444
.into_iter()
4545
.collect::<Vec<(_, (_, _))>>();
4646

47-
let mut cx = crate::CodegenCx::new(tcx, backend_config, &mut jit_module, false);
47+
let mut cx = crate::CodegenCx::new(tcx, backend_config.clone(), &mut jit_module, false);
4848

49-
super::time(tcx, "codegen mono items", || {
49+
super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
5050
super::predefine_mono_items(&mut cx, &mono_items);
5151
for (mono_item, _) in mono_items {
5252
match mono_item {
@@ -87,9 +87,8 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
8787
"Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
8888
);
8989

90-
let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
9190
let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
92-
.chain(args.split(' '))
91+
.chain(backend_config.jit_args.iter().map(|arg| &**arg))
9392
.map(|arg| CString::new(arg).unwrap())
9493
.collect::<Vec<_>>();
9594
let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();

src/driver/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ fn predefine_mono_items<'tcx>(
6565
});
6666
}
6767

68-
fn time<R>(tcx: TyCtxt<'_>, name: &'static str, f: impl FnOnce() -> R) -> R {
69-
if std::env::var("CG_CLIF_DISPLAY_CG_TIME").as_ref().map(|val| &**val) == Ok("1") {
68+
fn time<R>(tcx: TyCtxt<'_>, display: bool, name: &'static str, f: impl FnOnce() -> R) -> R {
69+
if display {
7070
println!("[{:<30}: {}] start", tcx.crate_name(LOCAL_CRATE), name);
7171
let before = std::time::Instant::now();
7272
let res = tcx.sess.time(name, f);

src/lib.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
193193
metadata: EncodedMetadata,
194194
need_metadata_module: bool,
195195
) -> Box<dyn Any> {
196-
let config = if let Some(config) = self.config {
196+
let config = if let Some(config) = self.config.clone() {
197197
config
198198
} else {
199199
BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
@@ -237,17 +237,16 @@ fn target_triple(sess: &Session) -> target_lexicon::Triple {
237237
sess.target.llvm_target.parse().unwrap()
238238
}
239239

240-
fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
240+
fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
241241
use target_lexicon::BinaryFormat;
242242

243243
let target_triple = crate::target_triple(sess);
244244

245245
let mut flags_builder = settings::builder();
246246
flags_builder.enable("is_pic").unwrap();
247247
flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
248-
let enable_verifier =
249-
cfg!(debug_assertions) || std::env::var("CG_CLIF_ENABLE_VERIFIER").is_ok();
250-
flags_builder.set("enable_verifier", if enable_verifier { "true" } else { "false" }).unwrap();
248+
let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
249+
flags_builder.set("enable_verifier", enable_verifier).unwrap();
251250

252251
let tls_model = match target_triple.binary_format {
253252
BinaryFormat::Elf => "elf_gd",

src/pretty_clif.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ pub(crate) fn write_clif_file<'tcx>(
248248
&mut clif,
249249
&context.func,
250250
&DisplayFunctionAnnotations {
251-
isa: Some(&*crate::build_isa(tcx.sess)),
251+
isa,
252252
value_ranges: value_ranges.as_ref(),
253253
},
254254
)

0 commit comments

Comments
 (0)