Skip to content

Commit 4e437be

Browse files
authored
Rollup merge of #117441 - cjgillot:diag-noassert, r=oli-obk,RalfJung
Do not assert in op_to_const. `op_to_const` is used in `try_destructure_mir_constant_for_diagnostics`, which may encounter invalid constants created by optimizations and debugging. r? ``@oli-obk`` Fixes #117368
2 parents 3087b63 + f512f91 commit 4e437be

12 files changed

+468
-11
lines changed

compiler/rustc_const_eval/src/const_eval/eval_queries.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,16 @@ pub(crate) fn mk_eval_cx<'mir, 'tcx>(
106106
}
107107

108108
/// This function converts an interpreter value into a MIR constant.
109+
///
110+
/// The `for_diagnostics` flag turns the usual rules for returning `ConstValue::Scalar` into a
111+
/// best-effort attempt. This is not okay for use in const-eval sine it breaks invariants rustc
112+
/// relies on, but it is okay for diagnostics which will just give up gracefully when they
113+
/// encounter an `Indirect` they cannot handle.
109114
#[instrument(skip(ecx), level = "debug")]
110115
pub(super) fn op_to_const<'tcx>(
111116
ecx: &CompileTimeEvalContext<'_, 'tcx>,
112117
op: &OpTy<'tcx>,
118+
for_diagnostics: bool,
113119
) -> ConstValue<'tcx> {
114120
// Handle ZST consistently and early.
115121
if op.layout.is_zst() {
@@ -133,7 +139,13 @@ pub(super) fn op_to_const<'tcx>(
133139
_ => false,
134140
};
135141
let immediate = if force_as_immediate {
136-
Right(ecx.read_immediate(op).expect("normalization works on validated constants"))
142+
match ecx.read_immediate(op) {
143+
Ok(imm) => Right(imm),
144+
Err(err) if !for_diagnostics => {
145+
panic!("normalization works on validated constants: {err:?}")
146+
}
147+
_ => op.as_mplace_or_imm(),
148+
}
137149
} else {
138150
op.as_mplace_or_imm()
139151
};
@@ -205,7 +217,7 @@ pub(crate) fn turn_into_const_value<'tcx>(
205217
);
206218

207219
// Turn this into a proper constant.
208-
op_to_const(&ecx, &mplace.into())
220+
op_to_const(&ecx, &mplace.into(), /* for diagnostics */ false)
209221
}
210222

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

compiler/rustc_const_eval/src/const_eval/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ pub(crate) fn eval_to_valtree<'tcx>(
7272
}
7373

7474
#[instrument(skip(tcx), level = "debug")]
75-
pub(crate) fn try_destructure_mir_constant_for_diagnostics<'tcx>(
75+
pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>(
7676
tcx: TyCtxtAt<'tcx>,
7777
val: mir::ConstValue<'tcx>,
7878
ty: Ty<'tcx>,
@@ -99,7 +99,7 @@ pub(crate) fn try_destructure_mir_constant_for_diagnostics<'tcx>(
9999
let fields_iter = (0..field_count)
100100
.map(|i| {
101101
let field_op = ecx.project_field(&down, i).ok()?;
102-
let val = op_to_const(&ecx, &field_op);
102+
let val = op_to_const(&ecx, &field_op, /* for diagnostics */ true);
103103
Some((val, field_op.layout.ty))
104104
})
105105
.collect::<Option<Vec<_>>>()?;

compiler/rustc_const_eval/src/const_eval/valtrees.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ pub fn valtree_to_const_value<'tcx>(
232232
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, CanAccessStatics::No);
233233
let imm = valtree_to_ref(&mut ecx, valtree, *inner_ty);
234234
let imm = ImmTy::from_immediate(imm, tcx.layout_of(param_env_ty).unwrap());
235-
op_to_const(&ecx, &imm.into())
235+
op_to_const(&ecx, &imm.into(), /* for diagnostics */ false)
236236
}
237237
ty::Tuple(_) | ty::Array(_, _) | ty::Adt(..) => {
238238
let layout = tcx.layout_of(param_env_ty).unwrap();
@@ -265,7 +265,7 @@ pub fn valtree_to_const_value<'tcx>(
265265
dump_place(&ecx, &place);
266266
intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &place).unwrap();
267267

268-
op_to_const(&ecx, &place.into())
268+
op_to_const(&ecx, &place.into(), /* for diagnostics */ false)
269269
}
270270
ty::Never
271271
| ty::Error(_)

compiler/rustc_const_eval/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ pub fn provide(providers: &mut Providers) {
5454
let (param_env, raw) = param_env_and_value.into_parts();
5555
const_eval::eval_to_valtree(tcx, param_env, raw)
5656
};
57-
providers.hooks.try_destructure_mir_constant_for_diagnostics =
58-
const_eval::try_destructure_mir_constant_for_diagnostics;
57+
providers.hooks.try_destructure_mir_constant_for_user_output =
58+
const_eval::try_destructure_mir_constant_for_user_output;
5959
providers.valtree_to_const_val = |tcx, (ty, valtree)| {
6060
const_eval::valtree_to_const_value(tcx, ty::ParamEnv::empty().and(ty), valtree)
6161
};

compiler/rustc_middle/src/hooks/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ macro_rules! declare_hooks {
6666
declare_hooks! {
6767
/// Tries to destructure an `mir::Const` ADT or array into its variant index
6868
/// and its field values. This should only be used for pretty printing.
69-
hook try_destructure_mir_constant_for_diagnostics(val: mir::ConstValue<'tcx>, ty: Ty<'tcx>) -> Option<mir::DestructuredConstant<'tcx>>;
69+
hook try_destructure_mir_constant_for_user_output(val: mir::ConstValue<'tcx>, ty: Ty<'tcx>) -> Option<mir::DestructuredConstant<'tcx>>;
7070

7171
/// Getting a &core::panic::Location referring to a span.
7272
hook const_caller_location(file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue<'tcx>;

compiler/rustc_middle/src/mir/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1713,7 +1713,7 @@ fn pretty_print_const_value_tcx<'tcx>(
17131713
(_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
17141714
let ct = tcx.lift(ct).unwrap();
17151715
let ty = tcx.lift(ty).unwrap();
1716-
if let Some(contents) = tcx.try_destructure_mir_constant_for_diagnostics(ct, ty) {
1716+
if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
17171717
let fields: Vec<(ConstValue<'_>, Ty<'_>)> = contents.fields.to_vec();
17181718
match *ty.kind() {
17191719
ty::Array(..) => {

src/tools/clippy/clippy_utils/src/consts.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -710,7 +710,7 @@ fn field_of_struct<'tcx>(
710710
field: &Ident,
711711
) -> Option<mir::Const<'tcx>> {
712712
if let mir::Const::Val(result, ty) = result
713-
&& let Some(dc) = lcx.tcx.try_destructure_mir_constant_for_diagnostics(result, ty)
713+
&& let Some(dc) = lcx.tcx.try_destructure_mir_constant_for_user_output(result, ty)
714714
&& let Some(dc_variant) = dc.variant
715715
&& let Some(variant) = adt_def.variants().get(dc_variant)
716716
&& let Some(field_idx) = variant.fields.iter().position(|el| el.name == field.name)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
- // MIR for `main` before GVN
2+
+ // MIR for `main` after GVN
3+
4+
fn main() -> () {
5+
let mut _0: ();
6+
let _1: std::alloc::Layout;
7+
let mut _2: std::option::Option<std::alloc::Layout>;
8+
let mut _3: *mut u8;
9+
let mut _4: *mut [u8];
10+
let mut _5: std::ptr::NonNull<[u8]>;
11+
let mut _6: std::result::Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError>;
12+
let mut _7: &std::alloc::Global;
13+
let mut _8: std::alloc::Layout;
14+
scope 1 {
15+
debug layout => _1;
16+
let mut _9: &std::alloc::Global;
17+
scope 2 {
18+
debug ptr => _3;
19+
}
20+
scope 5 (inlined <std::alloc::Global as Allocator>::allocate) {
21+
debug self => _9;
22+
debug layout => _1;
23+
}
24+
scope 6 (inlined #[track_caller] Result::<NonNull<[u8]>, std::alloc::AllocError>::unwrap) {
25+
debug self => _6;
26+
let mut _12: isize;
27+
let _13: std::alloc::AllocError;
28+
let mut _14: !;
29+
let _15: &str;
30+
let mut _16: &dyn std::fmt::Debug;
31+
let mut _17: &std::alloc::AllocError;
32+
scope 7 {
33+
debug t => _5;
34+
}
35+
scope 8 {
36+
debug e => const std::alloc::AllocError;
37+
}
38+
}
39+
scope 9 (inlined NonNull::<[u8]>::as_ptr) {
40+
debug self => _5;
41+
let mut _18: *const [u8];
42+
}
43+
}
44+
scope 3 (inlined #[track_caller] Option::<Layout>::unwrap) {
45+
debug self => _2;
46+
let mut _10: isize;
47+
let mut _11: !;
48+
scope 4 {
49+
debug val => _1;
50+
}
51+
}
52+
53+
bb0: {
54+
StorageLive(_2);
55+
- _2 = Option::<Layout>::None;
56+
+ _2 = const Option::<Layout>::None;
57+
StorageLive(_10);
58+
_10 = const 0_isize;
59+
switchInt(const 0_isize) -> [0: bb1, 1: bb3, otherwise: bb2];
60+
}
61+
62+
bb1: {
63+
_11 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind unreachable;
64+
}
65+
66+
bb2: {
67+
unreachable;
68+
}
69+
70+
bb3: {
71+
- _1 = move ((_2 as Some).0: std::alloc::Layout);
72+
+ _1 = const Layout {{ size: Indirect { alloc_id: ALLOC0, offset: Size(4 bytes) }: usize, align: std::ptr::Alignment(Scalar(0x00000000): ptr::alignment::AlignmentEnum32) }};
73+
StorageDead(_10);
74+
StorageDead(_2);
75+
StorageLive(_3);
76+
StorageLive(_4);
77+
StorageLive(_5);
78+
StorageLive(_6);
79+
_9 = const _;
80+
- _6 = std::alloc::Global::alloc_impl(_9, _1, const false) -> [return: bb4, unwind unreachable];
81+
+ _6 = std::alloc::Global::alloc_impl(const {ALLOC1: &std::alloc::Global}, const Layout {{ size: Indirect { alloc_id: ALLOC0, offset: Size(4 bytes) }: usize, align: std::ptr::Alignment(Scalar(0x00000000): ptr::alignment::AlignmentEnum32) }}, const false) -> [return: bb4, unwind unreachable];
82+
}
83+
84+
bb4: {
85+
StorageLive(_12);
86+
StorageLive(_15);
87+
_12 = discriminant(_6);
88+
switchInt(move _12) -> [0: bb6, 1: bb5, otherwise: bb2];
89+
}
90+
91+
bb5: {
92+
_15 = const "called `Result::unwrap()` on an `Err` value";
93+
StorageLive(_16);
94+
StorageLive(_17);
95+
_17 = &_13;
96+
_16 = move _17 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
97+
StorageDead(_17);
98+
_14 = result::unwrap_failed(move _15, move _16) -> unwind unreachable;
99+
}
100+
101+
bb6: {
102+
_5 = move ((_6 as Ok).0: std::ptr::NonNull<[u8]>);
103+
StorageDead(_15);
104+
StorageDead(_12);
105+
StorageDead(_6);
106+
StorageLive(_18);
107+
_18 = (_5.0: *const [u8]);
108+
_4 = move _18 as *mut [u8] (PtrToPtr);
109+
StorageDead(_18);
110+
StorageDead(_5);
111+
_3 = move _4 as *mut u8 (PtrToPtr);
112+
StorageDead(_4);
113+
StorageDead(_3);
114+
return;
115+
}
116+
}
117+
+
118+
+ ALLOC0 (size: 8, align: 4) {
119+
+ 00 00 00 00 __ __ __ __ │ ....░░░░
120+
+ }
121+
+
122+
+ ALLOC1 (size: 0, align: 1) {}
123+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
- // MIR for `main` before GVN
2+
+ // MIR for `main` after GVN
3+
4+
fn main() -> () {
5+
let mut _0: ();
6+
let _1: std::alloc::Layout;
7+
let mut _2: std::option::Option<std::alloc::Layout>;
8+
let mut _3: *mut u8;
9+
let mut _4: *mut [u8];
10+
let mut _5: std::ptr::NonNull<[u8]>;
11+
let mut _6: std::result::Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError>;
12+
let mut _7: &std::alloc::Global;
13+
let mut _8: std::alloc::Layout;
14+
scope 1 {
15+
debug layout => _1;
16+
let mut _9: &std::alloc::Global;
17+
scope 2 {
18+
debug ptr => _3;
19+
}
20+
scope 5 (inlined <std::alloc::Global as Allocator>::allocate) {
21+
debug self => _9;
22+
debug layout => _1;
23+
}
24+
scope 6 (inlined NonNull::<[u8]>::as_ptr) {
25+
debug self => _5;
26+
let mut _12: *const [u8];
27+
}
28+
}
29+
scope 3 (inlined #[track_caller] Option::<Layout>::unwrap) {
30+
debug self => _2;
31+
let mut _10: isize;
32+
let mut _11: !;
33+
scope 4 {
34+
debug val => _1;
35+
}
36+
}
37+
38+
bb0: {
39+
StorageLive(_2);
40+
- _2 = Option::<Layout>::None;
41+
+ _2 = const Option::<Layout>::None;
42+
StorageLive(_10);
43+
_10 = const 0_isize;
44+
switchInt(const 0_isize) -> [0: bb2, 1: bb4, otherwise: bb3];
45+
}
46+
47+
bb1: {
48+
StorageDead(_6);
49+
StorageLive(_12);
50+
_12 = (_5.0: *const [u8]);
51+
_4 = move _12 as *mut [u8] (PtrToPtr);
52+
StorageDead(_12);
53+
StorageDead(_5);
54+
_3 = move _4 as *mut u8 (PtrToPtr);
55+
StorageDead(_4);
56+
StorageDead(_3);
57+
return;
58+
}
59+
60+
bb2: {
61+
_11 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind continue;
62+
}
63+
64+
bb3: {
65+
unreachable;
66+
}
67+
68+
bb4: {
69+
- _1 = move ((_2 as Some).0: std::alloc::Layout);
70+
+ _1 = const Layout {{ size: Indirect { alloc_id: ALLOC0, offset: Size(4 bytes) }: usize, align: std::ptr::Alignment(Scalar(0x00000000): ptr::alignment::AlignmentEnum32) }};
71+
StorageDead(_10);
72+
StorageDead(_2);
73+
StorageLive(_3);
74+
StorageLive(_4);
75+
StorageLive(_5);
76+
StorageLive(_6);
77+
_9 = const _;
78+
- _6 = std::alloc::Global::alloc_impl(_9, _1, const false) -> [return: bb5, unwind continue];
79+
+ _6 = std::alloc::Global::alloc_impl(const {ALLOC1: &std::alloc::Global}, const Layout {{ size: Indirect { alloc_id: ALLOC0, offset: Size(4 bytes) }: usize, align: std::ptr::Alignment(Scalar(0x00000000): ptr::alignment::AlignmentEnum32) }}, const false) -> [return: bb5, unwind continue];
80+
}
81+
82+
bb5: {
83+
_5 = Result::<NonNull<[u8]>, std::alloc::AllocError>::unwrap(move _6) -> [return: bb1, unwind continue];
84+
}
85+
}
86+
+
87+
+ ALLOC0 (size: 8, align: 4) {
88+
+ 00 00 00 00 __ __ __ __ │ ....░░░░
89+
+ }
90+
+
91+
+ ALLOC1 (size: 0, align: 1) {}
92+

0 commit comments

Comments
 (0)