Skip to content

Commit 0f8908d

Browse files
committed
cleanup op_to_const a bit; rename ConstValue::ByRef → Indirect
1 parent 551f481 commit 0f8908d

File tree

14 files changed

+40
-47
lines changed

14 files changed

+40
-47
lines changed

compiler/rustc_codegen_cranelift/src/constant.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ pub(crate) fn codegen_const_value<'tcx>(
116116
}
117117

118118
match const_val {
119-
ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
119+
ConstValue::ZeroSized => unreachable!(), // we already handled ZST above
120120
ConstValue::Scalar(x) => match x {
121121
Scalar::Int(int) => {
122122
if fx.clif_type(layout.ty).is_some() {
@@ -200,7 +200,7 @@ pub(crate) fn codegen_const_value<'tcx>(
200200
CValue::by_val(val, layout)
201201
}
202202
},
203-
ConstValue::ByRef { alloc_id, offset } => {
203+
ConstValue::Indirect { alloc_id, offset } => {
204204
let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
205205
// FIXME: avoid creating multiple allocations for the same AllocId?
206206
CValue::by_ref(

compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
172172
.expect("simd_shuffle idx not const");
173173

174174
let idx_bytes = match idx_const {
175-
ConstValue::ByRef { alloc_id, offset } => {
175+
ConstValue::Indirect { alloc_id, offset } => {
176176
let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
177177
let size = Size::from_bytes(
178178
4 * ret_lane_count, /* size_of([u32; ret_lane_count]) */

compiler/rustc_codegen_ssa/src/mir/operand.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
116116
let b_llval = bx.const_usize((end - start) as u64);
117117
OperandValue::Pair(a_llval, b_llval)
118118
}
119-
ConstValue::ByRef { alloc_id, offset } => {
119+
ConstValue::Indirect { alloc_id, offset } => {
120120
let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
121121
// FIXME: should we attempt to avoid building the same AllocId multiple times?
122122
return Self::from_const_alloc(bx, layout, alloc, offset);

compiler/rustc_const_eval/src/const_eval/eval_queries.rs

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,13 @@ pub(super) fn op_to_const<'tcx>(
112112
ecx: &CompileTimeEvalContext<'_, 'tcx>,
113113
op: &OpTy<'tcx>,
114114
) -> ConstValue<'tcx> {
115+
// Handle ZST consistently and early.
116+
if op.layout.is_zst() {
117+
return ConstValue::ZeroSized;
118+
}
119+
115120
// We do not have value optimizations for everything.
116121
// Only scalars and slices, since they are very common.
117-
// Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
118-
// from scalar unions that are initialized with one of their zero sized variants. We could
119-
// instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
120-
// the usual cases of extracting e.g. a `usize`, without there being a real use case for the
121-
// `Undef` situation.
122122
let try_as_immediate = match op.layout.abi {
123123
Abi::Scalar(abi::Scalar::Initialized { .. }) => true,
124124
Abi::ScalarPair(..) => match op.layout.ty.kind() {
@@ -134,7 +134,7 @@ pub(super) fn op_to_const<'tcx>(
134134
let immediate = if try_as_immediate {
135135
Right(ecx.read_immediate(op).expect("normalization works on validated constants"))
136136
} else {
137-
// It is guaranteed that any non-slice scalar pair is actually ByRef here.
137+
// It is guaranteed that any non-slice scalar pair is actually `Indirect` here.
138138
// When we come back from raw const eval, we are always by-ref. The only way our op here is
139139
// by-val is if we are in destructure_mir_constant, i.e., if this is (a field of) something that we
140140
// "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
@@ -144,28 +144,15 @@ pub(super) fn op_to_const<'tcx>(
144144

145145
debug!(?immediate);
146146

147-
// We know `offset` is relative to the allocation, so we can use `into_parts`.
148-
let to_const_value = |mplace: &MPlaceTy<'_>| {
149-
debug!("to_const_value(mplace: {:?})", mplace);
150-
match mplace.ptr().into_parts() {
151-
(Some(alloc_id), offset) => ConstValue::ByRef { alloc_id, offset },
152-
(None, offset) => {
153-
assert!(mplace.layout.is_zst());
154-
assert_eq!(
155-
offset.bytes() % mplace.layout.align.abi.bytes(),
156-
0,
157-
"this MPlaceTy must come from a validated constant, thus we can assume the \
158-
alignment is correct",
159-
);
160-
ConstValue::ZeroSized
161-
}
162-
}
163-
};
164147
match immediate {
165-
Left(ref mplace) => to_const_value(mplace),
148+
Left(ref mplace) => {
149+
// We know `offset` is relative to the allocation, so we can use `into_parts`.
150+
let (alloc_id, offset) = mplace.ptr().into_parts();
151+
let alloc_id = alloc_id.expect("cannot have `fake` place fot non-ZST type");
152+
ConstValue::Indirect { alloc_id, offset }
153+
}
166154
// see comment on `let try_as_immediate` above
167155
Right(imm) => match *imm {
168-
_ if imm.layout.is_zst() => ConstValue::ZeroSized,
169156
Immediate::Scalar(x) => ConstValue::Scalar(x),
170157
Immediate::ScalarPair(a, b) => {
171158
debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
@@ -186,7 +173,7 @@ pub(super) fn op_to_const<'tcx>(
186173
let len: usize = len.try_into().unwrap();
187174
ConstValue::Slice { data, start, end: start + len }
188175
}
189-
Immediate::Uninit => to_const_value(&op.assert_mem_place()),
176+
Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty),
190177
},
191178
}
192179
}

compiler/rustc_const_eval/src/interpret/operand.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -756,7 +756,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
756756
};
757757
let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
758758
let op = match val_val {
759-
ConstValue::ByRef { alloc_id, offset } => {
759+
ConstValue::Indirect { alloc_id, offset } => {
760760
// We rely on mutability being set correctly in that allocation to prevent writes
761761
// where none should happen.
762762
let ptr = self.global_base_pointer(Pointer::new(alloc_id, offset))?;

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,21 @@ pub struct ConstAlloc<'tcx> {
3030
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash)]
3131
#[derive(HashStable, Lift)]
3232
pub enum ConstValue<'tcx> {
33-
/// Used only for types with `layout::abi::Scalar` ABI.
33+
/// Used for types with `layout::abi::Scalar` ABI.
3434
///
3535
/// Not using the enum `Value` to encode that this must not be `Uninit`.
3636
Scalar(Scalar),
3737

38-
/// Only used for ZSTs.
38+
/// Only for ZSTs.
3939
ZeroSized,
4040

41-
/// Used only for `&[u8]` and `&str`
41+
/// Used for `&[u8]` and `&str`.
42+
///
43+
/// This is worth the optimization since Rust has literals of that type.
4244
Slice { data: ConstAllocation<'tcx>, start: usize, end: usize },
4345

44-
/// A value not represented/representable by `Scalar` or `Slice`
45-
ByRef {
46+
/// A value not representable by the other variants; needs to be stored in-memory.
47+
Indirect {
4648
/// The backing memory of the value. May contain more memory than needed for just the value
4749
/// if this points into some other larger ConstValue.
4850
///
@@ -62,7 +64,7 @@ impl<'tcx> ConstValue<'tcx> {
6264
#[inline]
6365
pub fn try_to_scalar(&self) -> Option<Scalar<AllocId>> {
6466
match *self {
65-
ConstValue::ByRef { .. } | ConstValue::Slice { .. } | ConstValue::ZeroSized => None,
67+
ConstValue::Indirect { .. } | ConstValue::Slice { .. } | ConstValue::ZeroSized => None,
6668
ConstValue::Scalar(val) => Some(val),
6769
}
6870
}

compiler/rustc_middle/src/mir/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2914,7 +2914,7 @@ fn pretty_print_const_value<'tcx>(
29142914
_ => {}
29152915
}
29162916
}
2917-
(ConstValue::ByRef { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
2917+
(ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
29182918
let n = n.try_to_target_usize(tcx).unwrap();
29192919
let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
29202920
// cast is ok because we already checked for pointer size (32 or 64 bit) above

compiler/rustc_middle/src/mir/pretty.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
460460
ConstValue::ZeroSized => "<ZST>".to_string(),
461461
ConstValue::Scalar(s) => format!("Scalar({s:?})"),
462462
ConstValue::Slice { .. } => "Slice(..)".to_string(),
463-
ConstValue::ByRef { .. } => "ByRef(..)".to_string(),
463+
ConstValue::Indirect { .. } => "ByRef(..)".to_string(),
464464
};
465465

466466
let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree {
@@ -709,7 +709,11 @@ pub fn write_allocations<'tcx>(
709709
// `u8`/`str` slices, shouldn't contain pointers that we want to print.
710710
Either::Right(std::iter::empty())
711711
}
712-
ConstValue::ByRef { alloc_id, .. } => Either::Left(std::iter::once(alloc_id)),
712+
ConstValue::Indirect { alloc_id, .. } => {
713+
// FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
714+
// Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
715+
Either::Left(std::iter::once(alloc_id))
716+
}
713717
}
714718
}
715719
struct CollectAllocIds(BTreeSet<AllocId>);

compiler/rustc_mir_transform/src/const_prop.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx>
143143
#[inline(always)]
144144
fn enforce_alignment(_ecx: &InterpCx<'mir, 'tcx, Self>) -> CheckAlignment {
145145
// We do not check for alignment to avoid having to carry an `Align`
146-
// in `ConstValue::ByRef`.
146+
// in `ConstValue::Indirect`.
147147
CheckAlignment::No
148148
}
149149

@@ -552,7 +552,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
552552
.ok()?;
553553

554554
Some(ConstantKind::Val(
555-
ConstValue::ByRef { alloc_id, offset: Size::ZERO },
555+
ConstValue::Indirect { alloc_id, offset: Size::ZERO },
556556
value.layout.ty,
557557
))
558558
}

compiler/rustc_mir_transform/src/large_enums.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ impl EnumSizeOpt {
153153
span,
154154
user_ty: None,
155155
literal: ConstantKind::Val(
156-
interpret::ConstValue::ByRef { alloc_id, offset: Size::ZERO },
156+
interpret::ConstValue::Indirect { alloc_id, offset: Size::ZERO },
157157
tmp_ty,
158158
),
159159
};

compiler/rustc_monomorphize/src/collector.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1470,7 +1470,7 @@ fn collect_const_value<'tcx>(
14701470
) {
14711471
match value {
14721472
ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => collect_alloc(tcx, ptr.provenance, output),
1473-
ConstValue::ByRef { alloc_id, .. } => collect_alloc(tcx, alloc_id, output),
1473+
ConstValue::Indirect { alloc_id, .. } => collect_alloc(tcx, alloc_id, output),
14741474
ConstValue::Slice { data, start: _, end: _ } => {
14751475
for &id in data.inner().provenance().ptrs().values() {
14761476
collect_alloc(tcx, id, output);

compiler/rustc_smir/src/rustc_smir/alloc.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ pub fn new_allocation<'tcx>(
7272
.unwrap();
7373
allocation.stable(tables)
7474
}
75-
ConstValue::ByRef { alloc_id, offset } => {
75+
ConstValue::Indirect { alloc_id, offset } => {
7676
let alloc = tables.tcx.global_alloc(alloc_id).unwrap_memory();
7777
let ty_size = tables
7878
.tcx

src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Ve
232232
cx.tcx.type_of(def_id).instantiate_identity(),
233233
),
234234
Res::Def(DefKind::Const, def_id) => match cx.tcx.const_eval_poly(def_id).ok()? {
235-
ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => {
235+
ConstValue::Indirect { alloc, offset } if offset.bytes() == 0 => {
236236
read_mir_alloc_def_path(cx, alloc.inner(), cx.tcx.type_of(def_id).instantiate_identity())
237237
},
238238
_ => None,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ pub fn miri_to_const<'tcx>(lcx: &LateContext<'tcx>, result: mir::ConstantKind<'t
684684
},
685685
_ => None,
686686
},
687-
mir::ConstantKind::Val(ConstValue::ByRef { alloc_id, offset: _ }, _) => {
687+
mir::ConstantKind::Val(ConstValue::Indirect { alloc_id, offset: _ }, _) => {
688688
let alloc = lcx.tcx.global_alloc(alloc_id).unwrap_memory();
689689
match result.ty().kind() {
690690
ty::Adt(adt_def, _) if adt_def.is_struct() => Some(Constant::Adt(result)),

0 commit comments

Comments
 (0)