Skip to content

Commit e620d0f

Browse files
committed
Auto merge of #69262 - Dylan-DPC:rollup-m6dt9cn, r=Dylan-DPC
Rollup of 5 pull requests Successful merges: - #69181 (Change const eval to just return the value ) - #69192 (Add more regression tests) - #69200 (Fix printing of `Yield` terminator) - #69205 (Allow whitespaces in revision flags) - #69233 (Clean up E0310 explanation) Failed merges: r? @ghost
2 parents b0d5813 + 210b181 commit e620d0f

File tree

37 files changed

+358
-137
lines changed

37 files changed

+358
-137
lines changed

src/librustc/mir/interpret/error.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use super::{CheckInAllocMsg, Pointer, RawConst, ScalarMaybeUndef};
22

33
use crate::hir::map::definitions::DefPathData;
44
use crate::mir;
5+
use crate::mir::interpret::ConstValue;
56
use crate::ty::layout::{Align, LayoutError, Size};
67
use crate::ty::query::TyCtxtAt;
78
use crate::ty::{self, layout, Ty};
@@ -40,7 +41,7 @@ CloneTypeFoldableImpls! {
4041
}
4142

4243
pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
43-
pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
44+
pub type ConstEvalResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
4445

4546
#[derive(Debug)]
4647
pub struct ConstEvalErr<'tcx> {

src/librustc/mir/interpret/value.rs

+37-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::fmt;
77

88
use crate::ty::{
99
layout::{HasDataLayout, Size},
10-
Ty,
10+
ParamEnv, Ty, TyCtxt,
1111
};
1212

1313
use super::{sign_extend, truncate, AllocId, Allocation, InterpResult, Pointer, PointerArithmetic};
@@ -66,6 +66,32 @@ impl<'tcx> ConstValue<'tcx> {
6666
ConstValue::Scalar(val) => Some(val),
6767
}
6868
}
69+
70+
pub fn try_to_bits(&self, size: Size) -> Option<u128> {
71+
self.try_to_scalar()?.to_bits(size).ok()
72+
}
73+
74+
pub fn try_to_bits_for_ty(
75+
&self,
76+
tcx: TyCtxt<'tcx>,
77+
param_env: ParamEnv<'tcx>,
78+
ty: Ty<'tcx>,
79+
) -> Option<u128> {
80+
let size = tcx.layout_of(param_env.with_reveal_all().and(ty)).ok()?.size;
81+
self.try_to_bits(size)
82+
}
83+
84+
pub fn from_bool(b: bool) -> Self {
85+
ConstValue::Scalar(Scalar::from_bool(b))
86+
}
87+
88+
pub fn from_u64(i: u64) -> Self {
89+
ConstValue::Scalar(Scalar::from_u64(i))
90+
}
91+
92+
pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
93+
ConstValue::Scalar(Scalar::from_machine_usize(i, cx))
94+
}
6995
}
7096

7197
/// A `Scalar` represents an immediate, primitive value existing outside of a
@@ -287,6 +313,11 @@ impl<'tcx, Tag> Scalar<Tag> {
287313
Scalar::Raw { data: i as u128, size: 8 }
288314
}
289315

316+
#[inline]
317+
pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
318+
Self::from_uint(i, cx.data_layout().pointer_size)
319+
}
320+
290321
#[inline]
291322
pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
292323
let i = i.into();
@@ -306,6 +337,11 @@ impl<'tcx, Tag> Scalar<Tag> {
306337
.unwrap_or_else(|| bug!("Signed value {:#x} does not fit in {} bits", i, size.bits()))
307338
}
308339

340+
#[inline]
341+
pub fn from_machine_isize(i: i64, cx: &impl HasDataLayout) -> Self {
342+
Self::from_int(i, cx.data_layout().pointer_size)
343+
}
344+
309345
#[inline]
310346
pub fn from_f32(f: Single) -> Self {
311347
// We trust apfloat to give us properly truncated data.

src/librustc/mir/mod.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -1468,21 +1468,21 @@ impl<'tcx> TerminatorKind<'tcx> {
14681468
/// successors, which may be rendered differently between the text and the graphviz format.
14691469
pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
14701470
use self::TerminatorKind::*;
1471-
match *self {
1471+
match self {
14721472
Goto { .. } => write!(fmt, "goto"),
1473-
SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1473+
SwitchInt { discr, .. } => write!(fmt, "switchInt({:?})", discr),
14741474
Return => write!(fmt, "return"),
14751475
GeneratorDrop => write!(fmt, "generator_drop"),
14761476
Resume => write!(fmt, "resume"),
14771477
Abort => write!(fmt, "abort"),
1478-
Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1478+
Yield { value, resume_arg, .. } => write!(fmt, "{:?} = yield({:?})", resume_arg, value),
14791479
Unreachable => write!(fmt, "unreachable"),
1480-
Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1481-
DropAndReplace { ref location, ref value, .. } => {
1480+
Drop { location, .. } => write!(fmt, "drop({:?})", location),
1481+
DropAndReplace { location, value, .. } => {
14821482
write!(fmt, "replace({:?} <- {:?})", location, value)
14831483
}
1484-
Call { ref func, ref args, ref destination, .. } => {
1485-
if let Some((ref destination, _)) = *destination {
1484+
Call { func, args, destination, .. } => {
1485+
if let Some((destination, _)) = destination {
14861486
write!(fmt, "{:?} = ", destination)?;
14871487
}
14881488
write!(fmt, "{:?}(", func)?;
@@ -1494,7 +1494,7 @@ impl<'tcx> TerminatorKind<'tcx> {
14941494
}
14951495
write!(fmt, ")")
14961496
}
1497-
Assert { ref cond, expected, ref msg, .. } => {
1497+
Assert { cond, expected, msg, .. } => {
14981498
write!(fmt, "assert(")?;
14991499
if !expected {
15001500
write!(fmt, "!")?;

src/librustc/query/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ rustc_queries! {
519519
/// Extracts a field of a (variant of a) const.
520520
query const_field(
521521
key: ty::ParamEnvAnd<'tcx, (&'tcx ty::Const<'tcx>, mir::Field)>
522-
) -> &'tcx ty::Const<'tcx> {
522+
) -> ConstValue<'tcx> {
523523
no_force
524524
desc { "extract field of const" }
525525
}
@@ -533,7 +533,7 @@ rustc_queries! {
533533
desc { "destructure constant" }
534534
}
535535

536-
query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> &'tcx ty::Const<'tcx> {
536+
query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> ConstValue<'tcx> {
537537
no_force
538538
desc { "get a &core::panic::Location referring to a span" }
539539
}

src/librustc/ty/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2388,10 +2388,10 @@ impl<'tcx> AdtDef {
23882388
let repr_type = self.repr.discr_type();
23892389
match tcx.const_eval_poly(expr_did) {
23902390
Ok(val) => {
2391-
// FIXME: Find the right type and use it instead of `val.ty` here
2392-
if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2391+
let ty = repr_type.to_ty(tcx);
2392+
if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
23932393
trace!("discriminants: {} ({:?})", b, repr_type);
2394-
Some(Discr { val: b, ty: val.ty })
2394+
Some(Discr { val: b, ty })
23952395
} else {
23962396
info!("invalid enum discriminant: {:#?}", val);
23972397
crate::mir::interpret::struct_error(

src/librustc/ty/query/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::middle::resolve_lifetime::{ObjectLifetimeDefault, Region, ResolveLife
1414
use crate::middle::stability::{self, DeprecationEntry};
1515
use crate::mir;
1616
use crate::mir::interpret::GlobalId;
17-
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult};
17+
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult, ConstValue};
1818
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1919
use crate::mir::mono::CodegenUnit;
2020
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};

src/librustc/ty/sty.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -2417,9 +2417,14 @@ pub struct Const<'tcx> {
24172417
static_assert_size!(Const<'_>, 48);
24182418

24192419
impl<'tcx> Const<'tcx> {
2420+
#[inline]
2421+
pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2422+
tcx.mk_const(Self { val: ConstKind::Value(val), ty })
2423+
}
2424+
24202425
#[inline]
24212426
pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2422-
tcx.mk_const(Self { val: ConstKind::Value(ConstValue::Scalar(val)), ty })
2427+
Self::from_value(tcx, ConstValue::Scalar(val), ty)
24232428
}
24242429

24252430
#[inline]
@@ -2473,7 +2478,9 @@ impl<'tcx> Const<'tcx> {
24732478

24742479
// try to resolve e.g. associated constants to their definition on an impl, and then
24752480
// evaluate the const.
2476-
tcx.const_eval_resolve(param_env, did, substs, promoted, None).ok()
2481+
tcx.const_eval_resolve(param_env, did, substs, promoted, None)
2482+
.ok()
2483+
.map(|val| Const::from_value(tcx, val, self.ty))
24772484
};
24782485

24792486
match self.val {

src/librustc_codegen_llvm/consts.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,9 @@ pub fn codegen_static_initializer(
7878
cx: &CodegenCx<'ll, 'tcx>,
7979
def_id: DefId,
8080
) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
81-
let static_ = cx.tcx.const_eval_poly(def_id)?;
82-
83-
let alloc = match static_.val {
84-
ty::ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc,
85-
_ => bug!("static const eval returned {:#?}", static_),
81+
let alloc = match cx.tcx.const_eval_poly(def_id)? {
82+
ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
83+
val => bug!("static const eval returned {:#?}", val),
8684
};
8785
Ok((const_alloc_to_llvm(cx, alloc), alloc))
8886
}

src/librustc_codegen_llvm/intrinsic.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
193193
.tcx
194194
.const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
195195
.unwrap();
196-
OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
196+
OperandRef::from_const(self, ty_name, ret_ty).immediate_or_packed_pair(self)
197197
}
198198
"init" => {
199199
let ty = substs.type_at(0);

src/librustc_codegen_ssa/mir/block.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -991,7 +991,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
991991
caller.line as u32,
992992
caller.col_display as u32 + 1,
993993
));
994-
OperandRef::from_const(bx, const_loc)
994+
OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
995995
})
996996
}
997997

src/librustc_codegen_ssa/mir/constant.rs

+20-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::mir::operand::OperandRef;
22
use crate::traits::*;
33
use rustc::mir;
4-
use rustc::mir::interpret::ErrorHandled;
4+
use rustc::mir::interpret::{ConstValue, ErrorHandled};
55
use rustc::ty::layout::{self, HasTyCtxt};
66
use rustc::ty::{self, Ty};
77
use rustc_index::vec::Idx;
@@ -30,15 +30,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
3030
}
3131
_ => {
3232
let val = self.eval_mir_constant(constant)?;
33-
Ok(OperandRef::from_const(bx, val))
33+
let ty = self.monomorphize(&constant.literal.ty);
34+
Ok(OperandRef::from_const(bx, val.clone(), ty))
3435
}
3536
}
3637
}
3738

3839
pub fn eval_mir_constant(
3940
&mut self,
4041
constant: &mir::Constant<'tcx>,
41-
) -> Result<&'tcx ty::Const<'tcx>, ErrorHandled> {
42+
) -> Result<ConstValue<'tcx>, ErrorHandled> {
4243
match constant.literal.val {
4344
ty::ConstKind::Unevaluated(def_id, substs, promoted) => {
4445
let substs = self.monomorphize(&substs);
@@ -55,7 +56,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
5556
err
5657
})
5758
}
58-
_ => Ok(self.monomorphize(&constant.literal)),
59+
ty::ConstKind::Value(value) => Ok(value),
60+
_ => {
61+
let const_ = self.monomorphize(&constant.literal);
62+
if let ty::ConstKind::Value(value) = const_.val {
63+
Ok(value)
64+
} else {
65+
span_bug!(constant.span, "encountered bad ConstKind in codegen: {:?}", const_);
66+
}
67+
}
5968
}
6069
}
6170

@@ -65,21 +74,22 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
6574
bx: &Bx,
6675
span: Span,
6776
ty: Ty<'tcx>,
68-
constant: Result<&'tcx ty::Const<'tcx>, ErrorHandled>,
77+
constant: Result<ConstValue<'tcx>, ErrorHandled>,
6978
) -> (Bx::Value, Ty<'tcx>) {
7079
constant
71-
.map(|c| {
72-
let field_ty = c.ty.builtin_index().unwrap();
73-
let fields = match c.ty.kind {
80+
.map(|val| {
81+
let field_ty = ty.builtin_index().unwrap();
82+
let fields = match ty.kind {
7483
ty::Array(_, n) => n.eval_usize(bx.tcx(), ty::ParamEnv::reveal_all()),
75-
_ => bug!("invalid simd shuffle type: {}", c.ty),
84+
_ => bug!("invalid simd shuffle type: {}", ty),
7685
};
86+
let c = ty::Const::from_value(bx.tcx(), val, ty);
7787
let values: Vec<_> = (0..fields)
7888
.map(|field| {
7989
let field = bx.tcx().const_field(
8090
ty::ParamEnv::reveal_all().and((&c, mir::Field::new(field as usize))),
8191
);
82-
if let Some(prim) = field.val.try_to_scalar() {
92+
if let Some(prim) = field.try_to_scalar() {
8393
let layout = bx.layout_of(field_ty);
8494
let scalar = match layout.abi {
8595
layout::Abi::Scalar(ref x) => x,

src/librustc_codegen_ssa/mir/operand.rs

+5-9
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use crate::MemFlags;
88

99
use rustc::mir;
1010
use rustc::mir::interpret::{ConstValue, ErrorHandled, Pointer, Scalar};
11-
use rustc::ty;
1211
use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
12+
use rustc::ty::Ty;
1313

1414
use std::fmt;
1515

@@ -66,20 +66,16 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
6666

6767
pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
6868
bx: &mut Bx,
69-
val: &'tcx ty::Const<'tcx>,
69+
val: ConstValue<'tcx>,
70+
ty: Ty<'tcx>,
7071
) -> Self {
71-
let layout = bx.layout_of(val.ty);
72+
let layout = bx.layout_of(ty);
7273

7374
if layout.is_zst() {
7475
return OperandRef::new_zst(bx, layout);
7576
}
7677

77-
let val_val = match val.val {
78-
ty::ConstKind::Value(val_val) => val_val,
79-
_ => bug!("encountered bad ConstKind in codegen"),
80-
};
81-
82-
let val = match val_val {
78+
let val = match val {
8379
ConstValue::Scalar(x) => {
8480
let scalar = match layout.abi {
8581
layout::Abi::Scalar(ref x) => x,

src/librustc_error_codes/error_codes/E0310.md

+9-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
Types in type definitions have lifetimes associated with them that represent
2-
how long the data stored within them is guaranteed to be live. This lifetime
3-
must be as long as the data needs to be alive, and missing the constraint that
4-
denotes this will cause this error.
1+
A parameter type is missing a lifetime constraint or has a lifetime that
2+
does not live long enough.
3+
4+
Erroneous code example:
55

66
```compile_fail,E0310
77
// This won't compile because T is not constrained to the static lifetime
@@ -11,6 +11,11 @@ struct Foo<T> {
1111
}
1212
```
1313

14+
Type parameters in type definitions have lifetimes associated with them that
15+
represent how long the data stored within them is guaranteed to live. This
16+
lifetime must be as long as the data needs to be alive, and missing the
17+
constraint that denotes this will cause this error.
18+
1419
This will compile, because it has the constraint on the type parameter:
1520

1621
```

src/librustc_mir/const_eval.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pub(crate) fn const_field<'tcx>(
2626
variant: Option<VariantIdx>,
2727
field: mir::Field,
2828
value: &'tcx ty::Const<'tcx>,
29-
) -> &'tcx ty::Const<'tcx> {
29+
) -> ConstValue<'tcx> {
3030
trace!("const_field: {:?}, {:?}", field, value);
3131
let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
3232
// get the operand again
@@ -46,19 +46,13 @@ pub(crate) fn const_field<'tcx>(
4646
pub(crate) fn const_caller_location<'tcx>(
4747
tcx: TyCtxt<'tcx>,
4848
(file, line, col): (Symbol, u32, u32),
49-
) -> &'tcx ty::Const<'tcx> {
49+
) -> ConstValue<'tcx> {
5050
trace!("const_caller_location: {}:{}:{}", file, line, col);
5151
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
5252

53-
let loc_ty = tcx.caller_location_ty();
5453
let loc_place = ecx.alloc_caller_location(file, line, col);
5554
intern_const_alloc_recursive(&mut ecx, InternKind::Constant, loc_place, false).unwrap();
56-
let loc_const = ty::Const {
57-
ty: loc_ty,
58-
val: ty::ConstKind::Value(ConstValue::Scalar(loc_place.ptr.into())),
59-
};
60-
61-
tcx.mk_const(loc_const)
55+
ConstValue::Scalar(loc_place.ptr.into())
6256
}
6357

6458
// this function uses `unwrap` copiously, because an already validated constant
@@ -84,7 +78,8 @@ pub(crate) fn destructure_const<'tcx>(
8478
let down = ecx.operand_downcast(op, variant).unwrap();
8579
let fields_iter = (0..field_count).map(|i| {
8680
let field_op = ecx.operand_field(down, i).unwrap();
87-
op_to_const(&ecx, field_op)
81+
let val = op_to_const(&ecx, field_op);
82+
ty::Const::from_value(tcx, val, field_op.layout.ty)
8883
});
8984
let fields = tcx.arena.alloc_from_iter(fields_iter);
9085

0 commit comments

Comments
 (0)