Skip to content

Commit 0aa7752

Browse files
committed
Ensure nested allocations in statics do not get deduplicated
1 parent 737208d commit 0aa7752

File tree

17 files changed

+182
-40
lines changed

17 files changed

+182
-40
lines changed

compiler/rustc_codegen_gcc/src/mono_item.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
66
use rustc_middle::mir::mono::{Linkage, Visibility};
77
use rustc_middle::ty::{self, Instance, TypeVisitableExt};
88
use rustc_middle::ty::layout::{FnAbiOf, LayoutOf};
9+
use rustc_hir::def::DefKind;
910

1011
use crate::attributes;
1112
use crate::base;
@@ -17,7 +18,10 @@ impl<'gcc, 'tcx> PreDefineMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
1718
fn predefine_static(&self, def_id: DefId, _linkage: Linkage, visibility: Visibility, symbol_name: &str) {
1819
let attrs = self.tcx.codegen_fn_attrs(def_id);
1920
let instance = Instance::mono(self.tcx, def_id);
20-
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
21+
let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
22+
// Nested statics do not have a type, so pick a random type and let `define_static` figure out
23+
// the llvm type from the actual evaluated initializer.
24+
let ty = if nested { self.tcx.types.unit} else { instance.ty(self.tcx, ty::ParamEnv::reveal_all()) };
2125
let gcc_type = self.layout_of(ty).gcc_type(self);
2226

2327
let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);

compiler/rustc_codegen_llvm/src/consts.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::type_::Type;
99
use crate::type_of::LayoutLlvmExt;
1010
use crate::value::Value;
1111
use rustc_codegen_ssa::traits::*;
12+
use rustc_hir::def::DefKind;
1213
use rustc_hir::def_id::DefId;
1314
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
1415
use rustc_middle::mir::interpret::{
@@ -229,9 +230,17 @@ impl<'ll> CodegenCx<'ll, '_> {
229230
pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
230231
let instance = Instance::mono(self.tcx, def_id);
231232
trace!(?instance);
232-
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
233-
trace!(?ty);
234-
let llty = self.layout_of(ty).llvm_type(self);
233+
234+
let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
235+
// Nested statics do not have a type, so pick a random type and let `define_static` figure out
236+
// the llvm type from the actual evaluated initializer.
237+
let llty = if nested {
238+
self.type_i8()
239+
} else {
240+
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
241+
trace!(?ty);
242+
self.layout_of(ty).llvm_type(self)
243+
};
235244
self.get_static_inner(def_id, llty)
236245
}
237246

@@ -346,6 +355,9 @@ impl<'ll> CodegenCx<'ll, '_> {
346355

347356
fn codegen_static_item(&self, def_id: DefId) {
348357
unsafe {
358+
assert!(
359+
llvm::LLVMGetInitializer(self.statics.borrow().get(&def_id).unwrap()).is_none()
360+
);
349361
let attrs = self.tcx.codegen_fn_attrs(def_id);
350362

351363
let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {

compiler/rustc_codegen_llvm/src/mono_item.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use crate::errors::SymbolAlreadyDefined;
55
use crate::llvm;
66
use crate::type_of::LayoutLlvmExt;
77
use rustc_codegen_ssa::traits::*;
8+
use rustc_hir::def::DefKind;
89
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10+
use rustc_middle::bug;
911
use rustc_middle::mir::mono::{Linkage, Visibility};
1012
use rustc_middle::ty::layout::{FnAbiOf, LayoutOf};
1113
use rustc_middle::ty::{self, Instance, TypeVisitableExt};
@@ -21,7 +23,14 @@ impl<'tcx> PreDefineMethods<'tcx> for CodegenCx<'_, 'tcx> {
2123
symbol_name: &str,
2224
) {
2325
let instance = Instance::mono(self.tcx, def_id);
24-
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
26+
let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
27+
// Nested statics do not have a type, so pick a random type and let `define_static` figure out
28+
// the llvm type from the actual evaluated initializer.
29+
let ty = if nested {
30+
self.tcx.types.unit
31+
} else {
32+
instance.ty(self.tcx, ty::ParamEnv::reveal_all())
33+
};
2534
let llty = self.layout_of(ty).llvm_type(self);
2635

2736
let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {

compiler/rustc_const_eval/src/const_eval/eval_queries.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
5959
};
6060

6161
let ret = if let InternKind::Static(_) = intern_kind {
62-
create_static_alloc(ecx, cid.instance.def_id(), layout)?
62+
create_static_alloc(ecx, cid.instance.def_id().expect_local(), layout)?
6363
} else {
6464
ecx.allocate(layout, MemoryKind::Stack)?
6565
};
@@ -381,10 +381,10 @@ pub fn eval_in_interpreter<'mir, 'tcx>(
381381
Ok(mplace) => {
382382
// Since evaluation had no errors, validate the resulting constant.
383383

384-
// Temporarily allow access to the static_root_alloc_id for the purpose of validation.
385-
let static_root_alloc_id = ecx.machine.static_root_alloc_id.take();
384+
// Temporarily allow access to the static_root_ids for the purpose of validation.
385+
let static_root_ids = ecx.machine.static_root_ids.take();
386386
let validation = const_validate_mplace(&ecx, &mplace, cid);
387-
ecx.machine.static_root_alloc_id = static_root_alloc_id;
387+
ecx.machine.static_root_ids = static_root_ids;
388388

389389
let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
390390

compiler/rustc_const_eval/src/const_eval/machine.rs

+16-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rustc_data_structures::fx::FxIndexMap;
88
use rustc_data_structures::fx::IndexEntry;
99
use rustc_hir::def::DefKind;
1010
use rustc_hir::def_id::DefId;
11+
use rustc_hir::def_id::LocalDefId;
1112
use rustc_hir::LangItem;
1213
use rustc_middle::mir;
1314
use rustc_middle::mir::AssertMessage;
@@ -60,7 +61,19 @@ pub struct CompileTimeInterpreter<'mir, 'tcx> {
6061
pub(super) check_alignment: CheckAlignment,
6162

6263
/// Used to prevent reads from a static's base allocation, as that may allow for self-initialization.
63-
pub(crate) static_root_alloc_id: Option<AllocId>,
64+
pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
65+
}
66+
67+
pub trait HasStaticRootDefId {
68+
/// Returns the `DefId` of the static item that is currently being evaluated.
69+
/// Used for interning to be able to handle nested allocations.
70+
fn static_def_id(&self) -> Option<LocalDefId>;
71+
}
72+
73+
impl HasStaticRootDefId for CompileTimeInterpreter<'_, '_> {
74+
fn static_def_id(&self) -> Option<LocalDefId> {
75+
Some(self.static_root_ids?.1)
76+
}
6477
}
6578

6679
#[derive(Copy, Clone)]
@@ -94,7 +107,7 @@ impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
94107
stack: Vec::new(),
95108
can_access_mut_global,
96109
check_alignment,
97-
static_root_alloc_id: None,
110+
static_root_ids: None,
98111
}
99112
}
100113
}
@@ -751,7 +764,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
751764
ecx: &InterpCx<'mir, 'tcx, Self>,
752765
alloc_id: AllocId,
753766
) -> InterpResult<'tcx> {
754-
if Some(alloc_id) == ecx.machine.static_root_alloc_id {
767+
if Some(alloc_id) == ecx.machine.static_root_ids.map(|(id, _)| id) {
755768
Err(ConstEvalErrKind::RecursiveStatic.into())
756769
} else {
757770
Ok(())

compiler/rustc_const_eval/src/interpret/intern.rs

+31-3
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,16 @@
1313
//! but that would require relying on type information, and given how many ways Rust has to lie
1414
//! about type information, we want to avoid doing that.
1515
16+
use hir::def::DefKind;
1617
use rustc_ast::Mutability;
1718
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
1819
use rustc_errors::ErrorGuaranteed;
1920
use rustc_hir as hir;
20-
use rustc_middle::mir::interpret::{CtfeProvenance, InterpResult};
21+
use rustc_middle::mir::interpret::{ConstAllocation, CtfeProvenance, InterpResult};
22+
use rustc_middle::query::TyCtxtAt;
2123
use rustc_middle::ty::layout::TyAndLayout;
24+
use rustc_span::def_id::LocalDefId;
25+
use rustc_span::sym;
2226

2327
use super::{AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy};
2428
use crate::const_eval;
@@ -33,7 +37,7 @@ pub trait CompileTimeMachine<'mir, 'tcx: 'mir, T> = Machine<
3337
FrameExtra = (),
3438
AllocExtra = (),
3539
MemoryMap = FxIndexMap<AllocId, (MemoryKind<T>, Allocation)>,
36-
>;
40+
> + const_eval::HasStaticRootDefId;
3741

3842
/// Intern an allocation. Returns `Err` if the allocation does not exist in the local memory.
3943
///
@@ -67,10 +71,34 @@ fn intern_shallow<'rt, 'mir, 'tcx, T, M: CompileTimeMachine<'mir, 'tcx, T>>(
6771
}
6872
// link the alloc id to the actual allocation
6973
let alloc = ecx.tcx.mk_const_alloc(alloc);
70-
ecx.tcx.set_alloc_id_memory(alloc_id, alloc);
74+
if let Some(static_id) = ecx.machine.static_def_id() {
75+
intern_as_new_static(ecx.tcx, static_id, alloc_id, alloc);
76+
} else {
77+
ecx.tcx.set_alloc_id_memory(alloc_id, alloc);
78+
}
7179
Ok(alloc.0.0.provenance().ptrs().iter().map(|&(_, prov)| prov))
7280
}
7381

82+
/// Creates a new `DefId` and feeds all the right queries to make this `DefId`
83+
/// appear as if it were a user-written `static` (though it has no HIR).
84+
fn intern_as_new_static<'tcx>(
85+
tcx: TyCtxtAt<'tcx>,
86+
static_id: LocalDefId,
87+
alloc_id: AllocId,
88+
alloc: ConstAllocation<'tcx>,
89+
) {
90+
let feed = tcx.create_def(
91+
static_id,
92+
sym::nested,
93+
DefKind::Static { mt: alloc.0.mutability, nested: true },
94+
);
95+
tcx.set_nested_alloc_id_static(alloc_id, feed.def_id());
96+
feed.codegen_fn_attrs(tcx.codegen_fn_attrs(static_id).clone());
97+
feed.eval_static_initializer(Ok(alloc));
98+
feed.generics_of(tcx.generics_of(static_id).clone());
99+
feed.def_ident_span(tcx.def_ident_span(static_id));
100+
feed.explicit_predicates_of(tcx.explicit_predicates_of(static_id));
101+
}
74102
/// How a constant value should be interned.
75103
#[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)]
76104
pub enum InternKind {

compiler/rustc_const_eval/src/interpret/memory.rs

+25-10
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::ptr;
1414

1515
use rustc_ast::Mutability;
1616
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
17+
use rustc_hir::def::DefKind;
1718
use rustc_middle::mir::display_allocation;
1819
use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt};
1920
use rustc_target::abi::{Align, HasDataLayout, Size};
@@ -744,19 +745,33 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
744745
// be held throughout the match.
745746
match self.tcx.try_get_global_alloc(id) {
746747
Some(GlobalAlloc::Static(def_id)) => {
747-
assert!(self.tcx.is_static(def_id));
748748
// Thread-local statics do not have a constant address. They *must* be accessed via
749749
// `ThreadLocalRef`; we can never have a pointer to them as a regular constant value.
750750
assert!(!self.tcx.is_thread_local_static(def_id));
751-
// Use size and align of the type.
752-
let ty = self
753-
.tcx
754-
.type_of(def_id)
755-
.no_bound_vars()
756-
.expect("statics should not have generic parameters");
757-
let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
758-
assert!(layout.is_sized());
759-
(layout.size, layout.align.abi, AllocKind::LiveData)
751+
752+
let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else {
753+
bug!("GlobalAlloc::Static is not a static")
754+
};
755+
756+
let (size, align) = if nested {
757+
// Nested anonymous statics are untyped, so let's get their
758+
// size and alignment from the allocaiton itself. This always
759+
// succeeds, as the query is fed at DefId creation time, so no
760+
// evaluation actually occurs.
761+
let alloc = self.tcx.eval_static_initializer(def_id).unwrap();
762+
(alloc.0.size(), alloc.0.align)
763+
} else {
764+
// Use size and align of the type.
765+
let ty = self
766+
.tcx
767+
.type_of(def_id)
768+
.no_bound_vars()
769+
.expect("statics should not have generic parameters");
770+
let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
771+
assert!(layout.is_sized());
772+
(layout.size, layout.align.abi)
773+
};
774+
(size, align, AllocKind::LiveData)
760775
}
761776
Some(GlobalAlloc::Memory(alloc)) => {
762777
// Need to duplicate the logic here, because the global allocations have

compiler/rustc_const_eval/src/interpret/util.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use crate::const_eval::CompileTimeEvalContext;
22
use crate::interpret::{MemPlaceMeta, MemoryKind};
3+
use rustc_hir::def_id::LocalDefId;
34
use rustc_middle::mir::interpret::{AllocId, Allocation, InterpResult, Pointer};
45
use rustc_middle::ty::layout::TyAndLayout;
56
use rustc_middle::ty::{
67
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
78
};
8-
use rustc_span::def_id::DefId;
99
use std::ops::ControlFlow;
1010

1111
use super::MPlaceTy;
@@ -89,13 +89,13 @@ pub(crate) fn take_static_root_alloc<'mir, 'tcx: 'mir>(
8989

9090
pub(crate) fn create_static_alloc<'mir, 'tcx: 'mir>(
9191
ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
92-
static_def_id: DefId,
92+
static_def_id: LocalDefId,
9393
layout: TyAndLayout<'tcx>,
9494
) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
9595
let alloc = Allocation::try_uninit(layout.size, layout.align.abi)?;
96-
let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id);
97-
assert_eq!(ecx.machine.static_root_alloc_id, None);
98-
ecx.machine.static_root_alloc_id = Some(alloc_id);
96+
let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
97+
assert_eq!(ecx.machine.static_root_ids, None);
98+
ecx.machine.static_root_ids = Some((alloc_id, static_def_id));
9999
assert!(ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none());
100100
Ok(ecx.ptr_with_meta_to_mplace(Pointer::from(alloc_id).into(), MemPlaceMeta::None, layout))
101101
}

compiler/rustc_hir/src/def.rs

+3
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,9 @@ impl DefKind {
250250
| DefKind::AssocTy
251251
| DefKind::TyParam
252252
| DefKind::ExternCrate => DefPathData::TypeNs(name),
253+
// It's not exactly an anon const, but wrt DefPathData, there
254+
// is not difference.
255+
DefKind::Static { nested: true, .. } => DefPathData::AnonConst,
253256
DefKind::Fn
254257
| DefKind::Const
255258
| DefKind::ConstParam

compiler/rustc_metadata/src/rmeta/encoder.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,7 @@ fn should_encode_attrs(def_kind: DefKind) -> bool {
882882
| DefKind::AssocTy
883883
| DefKind::Fn
884884
| DefKind::Const
885-
| DefKind::Static { .. }
885+
| DefKind::Static { nested: false, .. }
886886
| DefKind::AssocFn
887887
| DefKind::AssocConst
888888
| DefKind::Macro(_)
@@ -903,6 +903,7 @@ fn should_encode_attrs(def_kind: DefKind) -> bool {
903903
| DefKind::InlineConst
904904
| DefKind::OpaqueTy
905905
| DefKind::LifetimeParam
906+
| DefKind::Static { nested: true, .. }
906907
| DefKind::GlobalAsm => false,
907908
}
908909
}
@@ -956,7 +957,7 @@ fn should_encode_visibility(def_kind: DefKind) -> bool {
956957
| DefKind::AssocTy
957958
| DefKind::Fn
958959
| DefKind::Const
959-
| DefKind::Static { .. }
960+
| DefKind::Static { nested: false, .. }
960961
| DefKind::Ctor(..)
961962
| DefKind::AssocFn
962963
| DefKind::AssocConst
@@ -969,6 +970,7 @@ fn should_encode_visibility(def_kind: DefKind) -> bool {
969970
| DefKind::LifetimeParam
970971
| DefKind::AnonConst
971972
| DefKind::InlineConst
973+
| DefKind::Static { nested: true, .. }
972974
| DefKind::OpaqueTy
973975
| DefKind::GlobalAsm
974976
| DefKind::Impl { .. }
@@ -1148,7 +1150,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) ->
11481150
| DefKind::Field
11491151
| DefKind::Fn
11501152
| DefKind::Const
1151-
| DefKind::Static { .. }
1153+
| DefKind::Static { nested: false, .. }
11521154
| DefKind::TyAlias
11531155
| DefKind::ForeignTy
11541156
| DefKind::Impl { .. }
@@ -1190,6 +1192,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) ->
11901192
| DefKind::Mod
11911193
| DefKind::ForeignMod
11921194
| DefKind::Macro(..)
1195+
| DefKind::Static { nested: true, .. }
11931196
| DefKind::Use
11941197
| DefKind::LifetimeParam
11951198
| DefKind::GlobalAsm

compiler/rustc_middle/src/mir/interpret/mod.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ use rustc_data_structures::fx::FxHashMap;
130130
use rustc_data_structures::sync::{HashMapExt, Lock};
131131
use rustc_data_structures::tiny_list::TinyList;
132132
use rustc_errors::ErrorGuaranteed;
133-
use rustc_hir::def_id::DefId;
133+
use rustc_hir::def_id::{DefId, LocalDefId};
134134
use rustc_macros::HashStable;
135135
use rustc_middle::ty::print::with_no_trimmed_paths;
136136
use rustc_serialize::{Decodable, Encodable};
@@ -627,6 +627,16 @@ impl<'tcx> TyCtxt<'tcx> {
627627
}
628628
}
629629

630+
/// Freezes an `AllocId` created with `reserve` by pointing it at a static item. Trying to
631+
/// call this function twice, even with the same `DefId` will ICE the compiler.
632+
pub fn set_nested_alloc_id_static(self, id: AllocId, def_id: LocalDefId) {
633+
if let Some(old) =
634+
self.alloc_map.lock().alloc_map.insert(id, GlobalAlloc::Static(def_id.to_def_id()))
635+
{
636+
bug!("tried to set allocation ID {id:?}, but it was already existing as {old:#?}");
637+
}
638+
}
639+
630640
/// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
631641
/// twice for the same `(AllocId, Allocation)` pair.
632642
fn set_alloc_id_same_memory(self, id: AllocId, mem: ConstAllocation<'tcx>) {

0 commit comments

Comments
 (0)