Skip to content

Commit f6263d1

Browse files
committed
(crudely) implement MIR-only rlibs
1 parent 4ccbb7d commit f6263d1

File tree

13 files changed

+191
-19
lines changed

13 files changed

+191
-19
lines changed

Diff for: compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+32-2
Original file line numberDiff line numberDiff line change
@@ -222,8 +222,14 @@ fn exported_symbols_provider_local(
222222
if allocator_kind_for_codegen(tcx).is_some() {
223223
for symbol_name in ALLOCATOR_METHODS
224224
.iter()
225-
.map(|method| format!("__rust_{}", method.name))
226-
.chain(["__rust_alloc_error_handler".to_string(), OomStrategy::SYMBOL.to_string()])
225+
.flat_map(|method| {
226+
[format!("__rust_{}", method.name), format!("__rdl_{}", method.name)]
227+
})
228+
.chain([
229+
"__rust_alloc_error_handler".to_string(),
230+
OomStrategy::SYMBOL.to_string(),
231+
"__rg_oom".to_string(),
232+
])
227233
{
228234
let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
229235

@@ -374,6 +380,30 @@ fn exported_symbols_provider_local(
374380
}
375381
}
376382

383+
if tcx.building_mir_only_rlib() {
384+
for def_id in tcx.mir_keys(()) {
385+
if !matches!(tcx.def_kind(def_id.to_def_id()), DefKind::Static(_)) {
386+
continue;
387+
}
388+
if tcx.is_reachable_non_generic(def_id.to_def_id()) {
389+
continue;
390+
}
391+
let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
392+
symbols.push((
393+
ExportedSymbol::NonGeneric(def_id.to_def_id()),
394+
SymbolExportInfo {
395+
level: symbol_export_level(tcx, def_id.to_def_id()),
396+
kind: if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
397+
SymbolExportKind::Tls
398+
} else {
399+
SymbolExportKind::Data
400+
},
401+
used: true,
402+
},
403+
));
404+
}
405+
}
406+
377407
// Sort so we get a stable incr. comp. hash.
378408
symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
379409

Diff for: compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,7 @@ fn test_unstable_options_tracking_hash() {
785785
tracked!(mir_emit_retag, true);
786786
tracked!(mir_enable_passes, vec![("DestProp".to_string(), false)]);
787787
tracked!(mir_keep_place_mention, true);
788+
tracked!(mir_only_rlibs, true);
788789
tracked!(mir_opt_level, Some(4));
789790
tracked!(move_size_limit, Some(4096));
790791
tracked!(mutable_noalias, false);

Diff for: compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+8
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,14 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
529529
.filter_map(|(cnum, data)| data.used().then_some(cnum)),
530530
)
531531
},
532+
mir_only_crates: |tcx, ()| {
533+
tcx.untracked().cstore.freeze();
534+
let store = CStore::from_tcx(tcx);
535+
let crates = store
536+
.iter_crate_data()
537+
.filter_map(|(cnum, data)| if data.root.is_mir_only { Some(cnum) } else { None });
538+
tcx.arena.alloc_from_iter(crates)
539+
},
532540
..providers.queries
533541
};
534542
provide_extern(&mut providers.extern_queries);

Diff for: compiler/rustc_metadata/src/rmeta/encoder.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
739739
impls,
740740
incoherent_impls,
741741
exported_symbols,
742+
is_mir_only: tcx.building_mir_only_rlib(),
742743
interpret_alloc_index,
743744
tables,
744745
syntax_contexts,
@@ -1049,12 +1050,13 @@ fn should_encode_mir(
10491050
reachable_set: &LocalDefIdSet,
10501051
def_id: LocalDefId,
10511052
) -> (bool, bool) {
1053+
let opts = &tcx.sess.opts;
1054+
let mir_required = opts.unstable_opts.always_encode_mir || tcx.building_mir_only_rlib();
10521055
match tcx.def_kind(def_id) {
10531056
// Constructors
10541057
DefKind::Ctor(_, _) => {
1055-
let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1056-
|| tcx.sess.opts.unstable_opts.always_encode_mir;
1057-
(true, mir_opt_base)
1058+
let opt = mir_required || opts.output_types.should_codegen();
1059+
(true, opt)
10581060
}
10591061
// Constants
10601062
DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
@@ -1065,7 +1067,7 @@ fn should_encode_mir(
10651067
// Full-fledged functions + closures
10661068
DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
10671069
let generics = tcx.generics_of(def_id);
1068-
let mut opt = tcx.sess.opts.unstable_opts.always_encode_mir
1070+
let mut opt = mir_required
10691071
|| (tcx.sess.opts.output_types.should_codegen()
10701072
&& reachable_set.contains(&def_id)
10711073
&& (generics.requires_monomorphization(tcx)

Diff for: compiler/rustc_metadata/src/rmeta/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ pub(crate) struct CrateRoot {
276276
debugger_visualizers: LazyArray<DebuggerVisualizerFile>,
277277

278278
exported_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
279+
is_mir_only: bool,
279280

280281
syntax_contexts: SyntaxContextTable,
281282
expn_data: ExpnDataTable,

Diff for: compiler/rustc_middle/src/mir/mono.rs

+11
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,17 @@ impl<'tcx> MonoItem<'tcx> {
9999
}
100100

101101
pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
102+
// Always do LocalCopy codegen when building a MIR-only rlib
103+
if tcx.building_mir_only_rlib() {
104+
return InstantiationMode::LocalCopy;
105+
}
106+
// If this is a monomorphization from a MIR-only rlib and we are building another lib, do
107+
// local codegen.
108+
if tcx.mir_only_crates(()).iter().any(|c| *c == self.def_id().krate)
109+
&& tcx.crate_types() == &[rustc_session::config::CrateType::Rlib]
110+
{
111+
return InstantiationMode::LocalCopy;
112+
}
102113
let generate_cgu_internal_copies = tcx
103114
.sess
104115
.opts

Diff for: compiler/rustc_middle/src/query/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -2228,6 +2228,11 @@ rustc_queries! {
22282228
query find_field((def_id, ident): (DefId, rustc_span::symbol::Ident)) -> Option<rustc_target::abi::FieldIdx> {
22292229
desc { |tcx| "find the index of maybe nested field `{ident}` in `{}`", tcx.def_path_str(def_id) }
22302230
}
2231+
2232+
query mir_only_crates(_: ()) -> &'tcx [CrateNum] {
2233+
eval_always
2234+
desc { "fetching all foreign crates built in mir-only mode" }
2235+
}
22312236
}
22322237

22332238
rustc_query_append! { define_callbacks! }

Diff for: compiler/rustc_middle/src/ty/context.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1078,6 +1078,10 @@ impl<'tcx> TyCtxt<'tcx> {
10781078
pub fn dcx(self) -> &'tcx DiagCtxt {
10791079
self.sess.dcx()
10801080
}
1081+
1082+
pub fn building_mir_only_rlib(self) -> bool {
1083+
self.sess.opts.unstable_opts.mir_only_rlibs && self.crate_types() == &[CrateType::Rlib]
1084+
}
10811085
}
10821086

10831087
impl<'tcx> TyCtxtAt<'tcx> {

Diff for: compiler/rustc_monomorphize/src/collector.rs

+95-7
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ use rustc_hir as hir;
170170
use rustc_hir::def::DefKind;
171171
use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
172172
use rustc_hir::lang_items::LangItem;
173+
use rustc_middle::middle::exported_symbols::ExportedSymbol;
173174
use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar};
174175
use rustc_middle::mir::mono::{InstantiationMode, MonoItem};
175176
use rustc_middle::mir::visit::Visitor as MirVisitor;
@@ -184,6 +185,7 @@ use rustc_middle::ty::{
184185
};
185186
use rustc_middle::ty::{GenericArgKind, GenericArgs};
186187
use rustc_middle::{middle::codegen_fn_attrs::CodegenFnAttrFlags, mir::visit::TyContext};
188+
use rustc_session::config::CrateType;
187189
use rustc_session::config::EntryFnType;
188190
use rustc_session::lint::builtin::LARGE_ASSIGNMENTS;
189191
use rustc_session::Limit;
@@ -316,6 +318,7 @@ fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionMode) -> Vec<MonoItem<
316318
}
317319

318320
collector.push_extra_entry_roots();
321+
collector.push_extra_roots_from_mir_only_rlibs();
319322
}
320323

321324
// We can only codegen items that are instantiable - items all of
@@ -1015,9 +1018,24 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: &Instance<'tcx>) ->
10151018
return true;
10161019
};
10171020

1021+
let def_is_for_mir_only_rlib = if def_id.krate == rustc_hir::def_id::LOCAL_CRATE {
1022+
tcx.building_mir_only_rlib()
1023+
} else {
1024+
tcx.mir_only_crates(()).iter().any(|c| *c == def_id.krate)
1025+
};
1026+
10181027
if tcx.is_foreign_item(def_id) {
1019-
// Foreign items are always linked against, there's no way of instantiating them.
1020-
return false;
1028+
if def_is_for_mir_only_rlib {
1029+
return tcx.is_mir_available(instance.def_id());
1030+
} else {
1031+
// Foreign items are always linked against, there's no way of instantiating them.
1032+
return false;
1033+
}
1034+
}
1035+
1036+
if def_is_for_mir_only_rlib {
1037+
let has_mir = tcx.is_mir_available(instance.def_id());
1038+
return has_mir || matches!(tcx.def_kind(instance.def_id()), DefKind::Static(_));
10211039
}
10221040

10231041
if tcx.intrinsic(def_id).is_some_and(|i| i.must_be_overridden) {
@@ -1030,18 +1048,18 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: &Instance<'tcx>) ->
10301048
return true;
10311049
}
10321050

1051+
if let DefKind::Static(_) = tcx.def_kind(def_id) {
1052+
// We cannot monomorphize statics from upstream crates.
1053+
return false;
1054+
}
1055+
10331056
if tcx.is_reachable_non_generic(def_id)
10341057
|| instance.polymorphize(tcx).upstream_monomorphization(tcx).is_some()
10351058
{
10361059
// We can link to the item in question, no instance needed in this crate.
10371060
return false;
10381061
}
10391062

1040-
if let DefKind::Static(_) = tcx.def_kind(def_id) {
1041-
// We cannot monomorphize statics from upstream crates.
1042-
return false;
1043-
}
1044-
10451063
if !tcx.is_mir_available(def_id) {
10461064
tcx.dcx().emit_fatal(NoOptimizedMir {
10471065
span: tcx.def_span(def_id),
@@ -1348,6 +1366,76 @@ impl<'v> RootCollector<'_, 'v> {
13481366

13491367
self.output.push(create_fn_mono_item(self.tcx, start_instance, DUMMY_SP));
13501368
}
1369+
1370+
fn push_extra_roots_from_mir_only_rlibs(&mut self) {
1371+
// An upstream extern function may be used anywhere in the dependency tree, so we
1372+
// cannot do any reachability analysis on them. We blindly monomorphize every
1373+
// extern function declared anywhere in our dependency tree. We must give them
1374+
// GloballyShared codegen because we don't know if the only call to an upstream
1375+
// extern function is also upstream: We don't have reachability information. All we
1376+
// can do is codegen all extern functions and pray for the linker to delete the
1377+
// ones that are reachable.
1378+
if !self.tcx.crate_types().iter().any(|c| !matches!(c, CrateType::Rlib)) {
1379+
return;
1380+
}
1381+
1382+
/*
1383+
eprintln!(
1384+
"Monomorphizing upstream crates for {:?}, {:?}",
1385+
self.tcx.crate_name(rustc_span::def_id::LOCAL_CRATE),
1386+
self.tcx.crate_types()
1387+
);
1388+
for krate in self.tcx.mir_only_crates(()) {
1389+
eprintln!("{:?}", self.tcx.crate_name(*krate));
1390+
}
1391+
*/
1392+
1393+
for (symbol, _info) in self
1394+
.tcx
1395+
.mir_only_crates(())
1396+
.into_iter()
1397+
.filter(|krate| {
1398+
if ["alloc", "core", "std"].contains(&self.tcx.crate_name(**krate).as_str())
1399+
&& self.tcx.crate_types() == &[CrateType::ProcMacro]
1400+
{
1401+
false
1402+
} else {
1403+
if self.tcx.crate_types() == &[CrateType::ProcMacro] {
1404+
eprintln!("{:?}", self.tcx.crate_name(**krate).as_str());
1405+
}
1406+
true
1407+
}
1408+
})
1409+
.flat_map(|krate| self.tcx.exported_symbols(*krate))
1410+
{
1411+
let def_id = match symbol {
1412+
ExportedSymbol::NonGeneric(def_id) => def_id,
1413+
ExportedSymbol::ThreadLocalShim(def_id) => {
1414+
//eprintln!("{:?}", def_id);
1415+
let item = MonoItem::Fn(Instance {
1416+
def: InstanceDef::ThreadLocalShim(*def_id),
1417+
args: GenericArgs::empty(),
1418+
});
1419+
self.output.push(dummy_spanned(item));
1420+
continue;
1421+
}
1422+
_ => continue,
1423+
};
1424+
match self.tcx.def_kind(def_id) {
1425+
DefKind::Fn | DefKind::AssocFn => {
1426+
//eprintln!("{:?}", def_id);
1427+
let instance = Instance::mono(self.tcx, *def_id);
1428+
let item = create_fn_mono_item(self.tcx, instance, DUMMY_SP);
1429+
self.output.push(item);
1430+
}
1431+
DefKind::Static(_) => {
1432+
//eprintln!("{:?}", def_id);
1433+
self.output.push(dummy_spanned(MonoItem::Static(*def_id)));
1434+
}
1435+
_ => {}
1436+
}
1437+
}
1438+
}
13511439
}
13521440

13531441
#[instrument(level = "debug", skip(tcx, output))]

Diff for: compiler/rustc_monomorphize/src/partitioning.rs

+22-3
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,12 @@ fn partition<'tcx, I>(
141141
where
142142
I: Iterator<Item = MonoItem<'tcx>>,
143143
{
144+
if tcx.building_mir_only_rlib() {
145+
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
146+
let cgu_name = fallback_cgu_name(cgu_name_builder);
147+
return vec![CodegenUnit::new(cgu_name)];
148+
}
149+
144150
let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
145151

146152
let cx = &PartitioningCx { tcx, usage_map };
@@ -165,6 +171,10 @@ where
165171
debug_dump(tcx, "MERGE", &codegen_units);
166172
}
167173

174+
if !codegen_units.is_sorted_by(|a, b| a.name().as_str() < b.name().as_str()) {
175+
bug!("unsorted CGUs");
176+
}
177+
168178
// Make as many symbols "internal" as possible, so LLVM has more freedom to
169179
// optimize.
170180
if !tcx.sess.link_dead_code() {
@@ -187,7 +197,12 @@ where
187197
for cgu in codegen_units.iter() {
188198
names += &format!("- {}\n", cgu.name());
189199
}
190-
bug!("unsorted CGUs:\n{names}");
200+
codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str()));
201+
let mut sorted_names = String::new();
202+
for cgu in codegen_units.iter() {
203+
sorted_names += &format!("- {}\n", cgu.name());
204+
}
205+
bug!("unsorted CGUs:\n{names}\n{sorted_names}");
191206
}
192207

193208
codegen_units
@@ -211,6 +226,9 @@ where
211226
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
212227
let cgu_name_cache = &mut FxHashMap::default();
213228

229+
let start_fn = cx.tcx.lang_items().start_fn();
230+
let entry_fn = cx.tcx.entry_fn(()).map(|(id, _)| id);
231+
214232
for mono_item in mono_items {
215233
// Handle only root (GloballyShared) items directly here. Inlined (LocalCopy) items
216234
// are handled at the bottom of the loop based on reachability, with one exception.
@@ -219,7 +237,8 @@ where
219237
match mono_item.instantiation_mode(cx.tcx) {
220238
InstantiationMode::GloballyShared { .. } => {}
221239
InstantiationMode::LocalCopy => {
222-
if Some(mono_item.def_id()) != cx.tcx.lang_items().start_fn() {
240+
let def_id = mono_item.def_id();
241+
if ![start_fn, entry_fn].contains(&Some(def_id)) {
223242
continue;
224243
}
225244
}
@@ -241,7 +260,7 @@ where
241260

242261
let cgu = codegen_units.entry(cgu_name).or_insert_with(|| CodegenUnit::new(cgu_name));
243262

244-
let mut can_be_internalized = true;
263+
let mut can_be_internalized = false;
245264
let (linkage, visibility) = mono_item_linkage_and_visibility(
246265
cx.tcx,
247266
&mono_item,

Diff for: compiler/rustc_session/src/options.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1745,6 +1745,8 @@ options! {
17451745
mir_keep_place_mention: bool = (false, parse_bool, [TRACKED],
17461746
"keep place mention MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
17471747
(default: no)"),
1748+
mir_only_rlibs: bool = (false, parse_bool, [TRACKED],
1749+
"only generate MIR when building rlibs (default: no)"),
17481750
#[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
17491751
mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
17501752
"MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),

Diff for: library/std/Cargo.toml

-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@ repository = "https://github.com/rust-lang/rust.git"
88
description = "The Rust Standard Library"
99
edition = "2021"
1010

11-
[lib]
12-
crate-type = ["dylib", "rlib"]
13-
1411
[dependencies]
1512
alloc = { path = "../alloc", public = true }
1613
cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] }

0 commit comments

Comments
 (0)