Skip to content

Commit c563f2e

Browse files
committed
Auto merge of #122371 - oli-obk:visit_nested_body, r=tmiasko
Stop walking the bodies of statics for reachability, and evaluate them instead cc `@saethlin` `@RalfJung` cc #119214 This reuses the `DefIdVisitor` from `rustc_privacy`, because they basically try to do the same thing. This PR's changes can probably be extended to constants, too, but let's tackle that separately, it's likely more involved.
2 parents c03ea3d + 746e4ef commit c563f2e

File tree

7 files changed

+118
-41
lines changed

7 files changed

+118
-41
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4400,6 +4400,7 @@ dependencies = [
44004400
"rustc_lexer",
44014401
"rustc_macros",
44024402
"rustc_middle",
4403+
"rustc_privacy",
44034404
"rustc_session",
44044405
"rustc_span",
44054406
"rustc_target",

compiler/rustc_passes/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ rustc_index = { path = "../rustc_index" }
1818
rustc_lexer = { path = "../rustc_lexer" }
1919
rustc_macros = { path = "../rustc_macros" }
2020
rustc_middle = { path = "../rustc_middle" }
21+
rustc_privacy = { path = "../rustc_privacy" }
2122
rustc_session = { path = "../rustc_session" }
2223
rustc_span = { path = "../rustc_span" }
2324
rustc_target = { path = "../rustc_target" }

compiler/rustc_passes/src/reachable.rs

+79-39
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// reachable as well.
77

88
use hir::def_id::LocalDefIdSet;
9+
use rustc_data_structures::stack::ensure_sufficient_stack;
910
use rustc_hir as hir;
1011
use rustc_hir::def::{DefKind, Res};
1112
use rustc_hir::def_id::{DefId, LocalDefId};
@@ -15,7 +16,8 @@ use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}
1516
use rustc_middle::middle::privacy::{self, Level};
1617
use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc};
1718
use rustc_middle::query::Providers;
18-
use rustc_middle::ty::{self, TyCtxt};
19+
use rustc_middle::ty::{self, ExistentialTraitRef, TyCtxt};
20+
use rustc_privacy::DefIdVisitor;
1921
use rustc_session::config::CrateType;
2022
use rustc_target::spec::abi::Abi;
2123

@@ -65,23 +67,8 @@ impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> {
6567
_ => None,
6668
};
6769

68-
if let Some(res) = res
69-
&& let Some(def_id) = res.opt_def_id().and_then(|el| el.as_local())
70-
{
71-
if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
72-
self.worklist.push(def_id);
73-
} else {
74-
match res {
75-
// Reachable constants and reachable statics can have their contents inlined
76-
// into other crates. Mark them as reachable and recurse into their body.
77-
Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
78-
self.worklist.push(def_id);
79-
}
80-
_ => {
81-
self.reachable_symbols.insert(def_id);
82-
}
83-
}
84-
}
70+
if let Some(res) = res {
71+
self.propagate_item(res);
8572
}
8673

8774
intravisit::walk_expr(self, expr)
@@ -198,17 +185,9 @@ impl<'tcx> ReachableContext<'tcx> {
198185
hir::ItemKind::Const(_, _, init) => {
199186
self.visit_nested_body(init);
200187
}
201-
202-
// Reachable statics are inlined if read from another constant or static
203-
// in other crates. Additionally anonymous nested statics may be created
204-
// when evaluating a static, so preserve those, too.
205-
hir::ItemKind::Static(_, _, init) => {
206-
// FIXME(oli-obk): remove this body walking and instead walk the evaluated initializer
207-
// to find nested items that end up in the final value instead of also marking symbols
208-
// as reachable that are only needed for evaluation.
209-
self.visit_nested_body(init);
188+
hir::ItemKind::Static(..) => {
210189
if let Ok(alloc) = self.tcx.eval_static_initializer(item.owner_id.def_id) {
211-
self.propagate_statics_from_alloc(item.owner_id.def_id, alloc);
190+
self.propagate_from_alloc(alloc);
212191
}
213192
}
214193

@@ -279,28 +258,89 @@ impl<'tcx> ReachableContext<'tcx> {
279258
}
280259
}
281260

282-
/// Finds anonymous nested statics created for nested allocations and adds them to `reachable_symbols`.
283-
fn propagate_statics_from_alloc(&mut self, root: LocalDefId, alloc: ConstAllocation<'tcx>) {
261+
/// Finds things to add to `reachable_symbols` within allocations.
262+
/// In contrast to visit_nested_body this ignores things that were only needed to evaluate
263+
/// the allocation.
264+
fn propagate_from_alloc(&mut self, alloc: ConstAllocation<'tcx>) {
284265
if !self.any_library {
285266
return;
286267
}
287268
for (_, prov) in alloc.0.provenance().ptrs().iter() {
288269
match self.tcx.global_alloc(prov.alloc_id()) {
289270
GlobalAlloc::Static(def_id) => {
290-
if let Some(def_id) = def_id.as_local()
291-
&& self.tcx.local_parent(def_id) == root
292-
// This is the main purpose of this function: add the def_id we find
293-
// to `reachable_symbols`.
294-
&& self.reachable_symbols.insert(def_id)
295-
&& let Ok(alloc) = self.tcx.eval_static_initializer(def_id)
296-
{
297-
self.propagate_statics_from_alloc(root, alloc);
271+
self.propagate_item(Res::Def(self.tcx.def_kind(def_id), def_id))
272+
}
273+
GlobalAlloc::Function(instance) => {
274+
// Manually visit to actually see the instance's `DefId`. Type visitors won't see it
275+
self.propagate_item(Res::Def(
276+
self.tcx.def_kind(instance.def_id()),
277+
instance.def_id(),
278+
));
279+
self.visit(instance.args);
280+
}
281+
GlobalAlloc::VTable(ty, trait_ref) => {
282+
self.visit(ty);
283+
// Manually visit to actually see the trait's `DefId`. Type visitors won't see it
284+
if let Some(trait_ref) = trait_ref {
285+
let ExistentialTraitRef { def_id, args } = trait_ref.skip_binder();
286+
self.visit_def_id(def_id, "", &"");
287+
self.visit(args);
298288
}
299289
}
300-
GlobalAlloc::Function(_) | GlobalAlloc::VTable(_, _) | GlobalAlloc::Memory(_) => {}
290+
GlobalAlloc::Memory(alloc) => self.propagate_from_alloc(alloc),
301291
}
302292
}
303293
}
294+
295+
fn propagate_item(&mut self, res: Res) {
296+
let Res::Def(kind, def_id) = res else { return };
297+
let Some(def_id) = def_id.as_local() else { return };
298+
match kind {
299+
DefKind::Static { nested: true, .. } => {
300+
// This is the main purpose of this function: add the def_id we find
301+
// to `reachable_symbols`.
302+
if self.reachable_symbols.insert(def_id) {
303+
if let Ok(alloc) = self.tcx.eval_static_initializer(def_id) {
304+
// This cannot cause infinite recursion, because we abort by inserting into the
305+
// work list once we hit a normal static. Nested statics, even if they somehow
306+
// become recursive, are also not infinitely recursing, because of the
307+
// `reachable_symbols` check above.
308+
// We still need to protect against stack overflow due to deeply nested statics.
309+
ensure_sufficient_stack(|| self.propagate_from_alloc(alloc));
310+
}
311+
}
312+
}
313+
// Reachable constants and reachable statics can have their contents inlined
314+
// into other crates. Mark them as reachable and recurse into their body.
315+
DefKind::Const | DefKind::AssocConst | DefKind::Static { .. } => {
316+
self.worklist.push(def_id);
317+
}
318+
_ => {
319+
if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
320+
self.worklist.push(def_id);
321+
} else {
322+
self.reachable_symbols.insert(def_id);
323+
}
324+
}
325+
}
326+
}
327+
}
328+
329+
impl<'tcx> DefIdVisitor<'tcx> for ReachableContext<'tcx> {
330+
type Result = ();
331+
332+
fn tcx(&self) -> TyCtxt<'tcx> {
333+
self.tcx
334+
}
335+
336+
fn visit_def_id(
337+
&mut self,
338+
def_id: DefId,
339+
_kind: &str,
340+
_descr: &dyn std::fmt::Display,
341+
) -> Self::Result {
342+
self.propagate_item(Res::Def(self.tcx.def_kind(def_id), def_id))
343+
}
304344
}
305345

306346
fn check_item<'tcx>(

compiler/rustc_privacy/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
6767
/// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
6868
/// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
6969
/// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
70-
trait DefIdVisitor<'tcx> {
70+
pub trait DefIdVisitor<'tcx> {
7171
type Result: VisitorResult = ();
7272
const SHALLOW: bool = false;
7373
const SKIP_ASSOC_TYS: bool = false;
@@ -98,7 +98,7 @@ trait DefIdVisitor<'tcx> {
9898
}
9999
}
100100

101-
struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
101+
pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
102102
def_id_visitor: &'v mut V,
103103
visited_opaque_tys: FxHashSet<DefId>,
104104
dummy: PhantomData<TyCtxt<'tcx>>,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
//! This test checks that we do not monomorphize functions that are only
2+
//! used to evaluate static items, but never used in runtime code.
3+
4+
//@compile-flags: --crate-type=lib -Copt-level=0
5+
6+
const fn foo() {}
7+
8+
pub static FOO: () = foo();
9+
10+
// CHECK-NOT: define{{.*}}foo{{.*}}

tests/ui/cross-crate/auxiliary/static_init_aux.rs

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
pub static V: &u32 = &X;
22
pub static F: fn() = f;
33
pub static G: fn() = G0;
4+
pub static H: &(dyn Fn() + Sync) = &h;
5+
pub static I: fn() = Helper(j).mk();
46

57
static X: u32 = 42;
68
static G0: fn() = g;
@@ -12,3 +14,22 @@ pub fn v() -> *const u32 {
1214
fn f() {}
1315

1416
fn g() {}
17+
18+
fn h() {}
19+
20+
#[derive(Copy, Clone)]
21+
struct Helper<T: Copy>(T);
22+
23+
impl<T: Copy + FnOnce()> Helper<T> {
24+
const fn mk(self) -> fn() {
25+
i::<T>
26+
}
27+
}
28+
29+
fn i<T: FnOnce()>() {
30+
assert_eq!(std::mem::size_of::<T>(), 0);
31+
// unsafe to work around the lack of a `Default` impl for function items
32+
unsafe { (std::mem::transmute_copy::<(), T>(&()))() }
33+
}
34+
35+
fn j() {}

tests/ui/cross-crate/static-init.rs

+4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ extern crate static_init_aux as aux;
66
static V: &u32 = aux::V;
77
static F: fn() = aux::F;
88
static G: fn() = aux::G;
9+
static H: &(dyn Fn() + Sync) = aux::H;
10+
static I: fn() = aux::I;
911

1012
fn v() -> *const u32 {
1113
V
@@ -15,4 +17,6 @@ fn main() {
1517
assert_eq!(aux::v(), crate::v());
1618
F();
1719
G();
20+
H();
21+
I();
1822
}

0 commit comments

Comments
 (0)