Skip to content

Commit 8d8135f

Browse files
committed
Auto merge of rust-lang#94876 - b-naber:thir-abstract-const-changes, r=lcnr
Change Thir to lazily create constants To allow `AbstractConst`s to work with the previous thir changes we made and those we want to make, i.e. to avoid problems due to `ValTree` and `ConstValue` conversions, we instead switch to a thir representation for constants that allows us to lazily create constants. r? `@oli-obk`
2 parents d2df372 + 19041d9 commit 8d8135f

File tree

17 files changed

+346
-155
lines changed

17 files changed

+346
-155
lines changed

compiler/rustc_middle/src/query/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,7 @@ rustc_queries! {
955955
desc { "get a &core::panic::Location referring to a span" }
956956
}
957957

958+
// FIXME get rid of this with valtrees
958959
query lit_to_const(
959960
key: LitToConstInput<'tcx>
960961
) -> Result<ty::Const<'tcx>, LitToConstError> {

compiler/rustc_middle/src/thir.rs

+25-6
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,8 @@ pub enum ExprKind<'tcx> {
369369
},
370370
/// An inline `const` block, e.g. `const {}`.
371371
ConstBlock {
372-
value: Const<'tcx>,
372+
did: DefId,
373+
substs: SubstsRef<'tcx>,
373374
},
374375
/// An array literal constructed from one repeated element, e.g. `[1; 5]`.
375376
Repeat {
@@ -408,13 +409,25 @@ pub enum ExprKind<'tcx> {
408409
},
409410
/// A literal.
410411
Literal {
411-
literal: Const<'tcx>,
412+
lit: &'tcx hir::Lit,
413+
neg: bool,
414+
},
415+
/// For literals that don't correspond to anything in the HIR
416+
NonHirLiteral {
417+
lit: ty::ScalarInt,
418+
user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
419+
},
420+
/// Associated constants and named constants
421+
NamedConst {
422+
def_id: DefId,
423+
substs: SubstsRef<'tcx>,
412424
user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
413-
/// The `DefId` of the `const` item this literal
414-
/// was produced from, if this is not a user-written
415-
/// literal value.
416-
const_id: Option<DefId>,
417425
},
426+
ConstParam {
427+
param: ty::ParamConst,
428+
def_id: DefId,
429+
},
430+
// FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
418431
/// A literal containing the address of a `static`.
419432
///
420433
/// This is only distinguished from `Literal` so that we can register some
@@ -439,6 +452,12 @@ pub enum ExprKind<'tcx> {
439452
},
440453
}
441454

455+
impl<'tcx> ExprKind<'tcx> {
456+
pub fn zero_sized_literal(user_ty: Option<Canonical<'tcx, UserType<'tcx>>>) -> Self {
457+
ExprKind::NonHirLiteral { lit: ty::ScalarInt::ZST, user_ty }
458+
}
459+
}
460+
442461
/// Represents the association of a field identifier and an expression.
443462
///
444463
/// This is used in struct constructors.

compiler/rustc_middle/src/thir/visit.rs

+8-12
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use super::{
22
Arm, Block, Expr, ExprKind, Guard, InlineAsmOperand, Pat, PatKind, Stmt, StmtKind, Thir,
33
};
4-
use rustc_middle::ty::Const;
54

65
pub trait Visitor<'a, 'tcx: 'a>: Sized {
76
fn thir(&self) -> &'a Thir<'tcx>;
@@ -25,8 +24,6 @@ pub trait Visitor<'a, 'tcx: 'a>: Sized {
2524
fn visit_pat(&mut self, pat: &Pat<'tcx>) {
2625
walk_pat(self, pat);
2726
}
28-
29-
fn visit_const(&mut self, _cnst: Const<'tcx>) {}
3027
}
3128

3229
pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Expr<'tcx>) {
@@ -93,10 +90,9 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
9390
visitor.visit_expr(&visitor.thir()[value])
9491
}
9592
}
96-
ConstBlock { value } => visitor.visit_const(value),
97-
Repeat { value, count } => {
93+
ConstBlock { did: _, substs: _ } => {}
94+
Repeat { value, count: _ } => {
9895
visitor.visit_expr(&visitor.thir()[value]);
99-
visitor.visit_const(count);
10096
}
10197
Array { ref fields } | Tuple { ref fields } => {
10298
for &field in &**fields {
@@ -122,7 +118,10 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
122118
visitor.visit_expr(&visitor.thir()[source])
123119
}
124120
Closure { closure_id: _, substs: _, upvars: _, movability: _, fake_reads: _ } => {}
125-
Literal { literal, user_ty: _, const_id: _ } => visitor.visit_const(literal),
121+
Literal { lit: _, neg: _ } => {}
122+
NonHirLiteral { lit: _, user_ty: _ } => {}
123+
NamedConst { def_id: _, substs: _, user_ty: _ } => {}
124+
ConstParam { param: _, def_id: _ } => {}
126125
StaticRef { alloc_id: _, ty: _, def_id: _ } => {}
127126
InlineAsm { ref operands, template: _, options: _, line_spans: _ } => {
128127
for op in &**operands {
@@ -209,11 +208,8 @@ pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<'
209208
visitor.visit_pat(&subpattern.pattern);
210209
}
211210
}
212-
Constant { value } => visitor.visit_const(*value),
213-
Range(range) => {
214-
visitor.visit_const(range.lo);
215-
visitor.visit_const(range.hi);
216-
}
211+
Constant { value: _ } => {}
212+
Range(_) => {}
217213
Slice { prefix, slice, suffix } | Array { prefix, slice, suffix } => {
218214
for subpattern in prefix {
219215
visitor.visit_pat(&subpattern);
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,141 @@
11
//! See docs in build/expr/mod.rs
22
33
use crate::build::Builder;
4-
use rustc_middle::mir::interpret::{ConstValue, Scalar};
4+
use crate::thir::constant::parse_float;
5+
use rustc_ast::ast;
6+
use rustc_hir::def_id::DefId;
7+
use rustc_middle::mir::interpret::{
8+
Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
9+
};
510
use rustc_middle::mir::*;
611
use rustc_middle::thir::*;
7-
use rustc_middle::ty::CanonicalUserTypeAnnotation;
12+
use rustc_middle::ty::subst::SubstsRef;
13+
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
14+
use rustc_target::abi::Size;
815

916
impl<'a, 'tcx> Builder<'a, 'tcx> {
1017
/// Compile `expr`, yielding a compile-time constant. Assumes that
1118
/// `expr` is a valid compile-time constant!
1219
crate fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
20+
let create_uneval_from_def_id =
21+
|tcx: TyCtxt<'tcx>, def_id: DefId, ty: Ty<'tcx>, substs: SubstsRef<'tcx>| {
22+
let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
23+
tcx.mk_const(ty::ConstS { val: ty::ConstKind::Unevaluated(uneval), ty })
24+
};
25+
1326
let this = self;
27+
let tcx = this.tcx;
1428
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
1529
match *kind {
1630
ExprKind::Scope { region_scope: _, lint_level: _, value } => {
1731
this.as_constant(&this.thir[value])
1832
}
19-
ExprKind::Literal { literal, user_ty, const_id: _ } => {
33+
ExprKind::Literal { lit, neg } => {
34+
let literal =
35+
match lit_to_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
36+
Ok(c) => c,
37+
Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
38+
Err(LitToConstError::TypeError) => {
39+
bug!("encountered type error in `lit_to_constant")
40+
}
41+
};
42+
43+
Constant { span, user_ty: None, literal: literal.into() }
44+
}
45+
ExprKind::NonHirLiteral { lit, user_ty } => {
2046
let user_ty = user_ty.map(|user_ty| {
2147
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
2248
span,
2349
user_ty,
2450
inferred_ty: ty,
2551
})
2652
});
27-
assert_eq!(literal.ty(), ty);
28-
Constant { span, user_ty, literal: literal.into() }
53+
54+
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
55+
56+
Constant { span, user_ty: user_ty, literal }
57+
}
58+
ExprKind::NamedConst { def_id, substs, user_ty } => {
59+
let user_ty = user_ty.map(|user_ty| {
60+
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
61+
span,
62+
user_ty,
63+
inferred_ty: ty,
64+
})
65+
});
66+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
67+
68+
Constant { user_ty, span, literal }
69+
}
70+
ExprKind::ConstParam { param, def_id: _ } => {
71+
let const_param =
72+
tcx.mk_const(ty::ConstS { val: ty::ConstKind::Param(param), ty: expr.ty });
73+
let literal = ConstantKind::Ty(const_param);
74+
75+
Constant { user_ty: None, span, literal }
76+
}
77+
ExprKind::ConstBlock { did: def_id, substs } => {
78+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
79+
80+
Constant { user_ty: None, span, literal }
2981
}
3082
ExprKind::StaticRef { alloc_id, ty, .. } => {
31-
let const_val =
32-
ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &this.tcx));
83+
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
3384
let literal = ConstantKind::Val(const_val, ty);
3485

3586
Constant { span, user_ty: None, literal }
3687
}
37-
ExprKind::ConstBlock { value } => {
38-
Constant { span: span, user_ty: None, literal: value.into() }
39-
}
4088
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
4189
}
4290
}
4391
}
92+
93+
crate fn lit_to_constant<'tcx>(
94+
tcx: TyCtxt<'tcx>,
95+
lit_input: LitToConstInput<'tcx>,
96+
) -> Result<ConstantKind<'tcx>, LitToConstError> {
97+
let LitToConstInput { lit, ty, neg } = lit_input;
98+
let trunc = |n| {
99+
let param_ty = ty::ParamEnv::reveal_all().and(ty);
100+
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
101+
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
102+
let result = width.truncate(n);
103+
trace!("trunc result: {}", result);
104+
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
105+
};
106+
107+
let value = match (lit, &ty.kind()) {
108+
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
109+
let s = s.as_str();
110+
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
111+
let allocation = tcx.intern_const_alloc(allocation);
112+
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
113+
}
114+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
115+
if matches!(inner_ty.kind(), ty::Slice(_)) =>
116+
{
117+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
118+
let allocation = tcx.intern_const_alloc(allocation);
119+
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
120+
}
121+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
122+
let id = tcx.allocate_bytes(data);
123+
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
124+
}
125+
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
126+
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
127+
}
128+
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
129+
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
130+
}
131+
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
132+
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
133+
}
134+
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
135+
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
136+
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
137+
_ => return Err(LitToConstError::TypeError),
138+
};
139+
140+
Ok(ConstantKind::Val(value, ty))
141+
}

compiler/rustc_mir_build/src/build/expr/as_place.rs

+3
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
566566
| ExprKind::Continue { .. }
567567
| ExprKind::Return { .. }
568568
| ExprKind::Literal { .. }
569+
| ExprKind::NamedConst { .. }
570+
| ExprKind::NonHirLiteral { .. }
571+
| ExprKind::ConstParam { .. }
569572
| ExprKind::ConstBlock { .. }
570573
| ExprKind::StaticRef { .. }
571574
| ExprKind::InlineAsm { .. }

compiler/rustc_mir_build/src/build/expr/as_rvalue.rs

+3
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
327327
}
328328
ExprKind::Yield { .. }
329329
| ExprKind::Literal { .. }
330+
| ExprKind::NamedConst { .. }
331+
| ExprKind::NonHirLiteral { .. }
332+
| ExprKind::ConstParam { .. }
330333
| ExprKind::ConstBlock { .. }
331334
| ExprKind::StaticRef { .. }
332335
| ExprKind::Block { .. }

compiler/rustc_mir_build/src/build/expr/as_temp.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
7070
local_decl.local_info =
7171
Some(Box::new(LocalInfo::StaticRef { def_id, is_thread_local: true }));
7272
}
73-
ExprKind::Literal { const_id: Some(def_id), .. } => {
73+
ExprKind::NamedConst { def_id, .. } | ExprKind::ConstParam { def_id, .. } => {
7474
local_decl.local_info = Some(Box::new(LocalInfo::ConstRef { def_id }));
7575
}
7676
_ => {}

compiler/rustc_mir_build/src/build/expr/category.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,12 @@ impl Category {
6969
| ExprKind::AssignOp { .. }
7070
| ExprKind::ThreadLocalRef(_) => Some(Category::Rvalue(RvalueFunc::AsRvalue)),
7171

72-
ExprKind::ConstBlock { .. } | ExprKind::Literal { .. } | ExprKind::StaticRef { .. } => {
73-
Some(Category::Constant)
74-
}
72+
ExprKind::ConstBlock { .. }
73+
| ExprKind::Literal { .. }
74+
| ExprKind::NonHirLiteral { .. }
75+
| ExprKind::ConstParam { .. }
76+
| ExprKind::StaticRef { .. }
77+
| ExprKind::NamedConst { .. } => Some(Category::Constant),
7578

7679
ExprKind::Loop { .. }
7780
| ExprKind::Block { .. }

compiler/rustc_mir_build/src/build/expr/into.rs

+3
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
533533
| ExprKind::Closure { .. }
534534
| ExprKind::ConstBlock { .. }
535535
| ExprKind::Literal { .. }
536+
| ExprKind::NamedConst { .. }
537+
| ExprKind::NonHirLiteral { .. }
538+
| ExprKind::ConstParam { .. }
536539
| ExprKind::ThreadLocalRef(_)
537540
| ExprKind::StaticRef { .. } => {
538541
debug_assert!(match Category::of(&expr.kind).unwrap() {

compiler/rustc_mir_build/src/build/expr/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
//! basically the point where the "by value" operations are bridged
6161
//! over to the "by reference" mode (`as_place`).
6262
63-
mod as_constant;
63+
crate mod as_constant;
6464
mod as_operand;
6565
pub mod as_place;
6666
mod as_rvalue;

compiler/rustc_mir_build/src/check_unsafety.rs

+3
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
303303
| ExprKind::Block { .. }
304304
| ExprKind::Borrow { .. }
305305
| ExprKind::Literal { .. }
306+
| ExprKind::NamedConst { .. }
307+
| ExprKind::NonHirLiteral { .. }
308+
| ExprKind::ConstParam { .. }
306309
| ExprKind::ConstBlock { .. }
307310
| ExprKind::Deref { .. }
308311
| ExprKind::Index { .. }

compiler/rustc_mir_build/src/thir/constant.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_middle::ty::{self, ParamEnv, TyCtxt};
77
use rustc_span::symbol::Symbol;
88
use rustc_target::abi::Size;
99

10+
// FIXME Once valtrees are available, get rid of this function and the query
1011
crate fn lit_to_const<'tcx>(
1112
tcx: TyCtxt<'tcx>,
1213
lit_input: LitToConstInput<'tcx>,
@@ -57,7 +58,12 @@ crate fn lit_to_const<'tcx>(
5758
Ok(ty::Const::from_value(tcx, lit, ty))
5859
}
5960

60-
fn parse_float<'tcx>(num: Symbol, fty: ty::FloatTy, neg: bool) -> Option<ConstValue<'tcx>> {
61+
// FIXME move this to rustc_mir_build::build
62+
pub(crate) fn parse_float<'tcx>(
63+
num: Symbol,
64+
fty: ty::FloatTy,
65+
neg: bool,
66+
) -> Option<ConstValue<'tcx>> {
6167
let num = num.as_str();
6268
use rustc_apfloat::ieee::{Double, Single};
6369
let scalar = match fty {

0 commit comments

Comments
 (0)