Skip to content

Commit f713b50

Browse files
committed
change thir to lazily create constants
1 parent 36748cf commit f713b50

File tree

17 files changed

+296
-133
lines changed

17 files changed

+296
-133
lines changed

compiler/rustc_middle/src/query/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,12 +955,17 @@ 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> {
961962
desc { "converting literal to const" }
962963
}
963964

965+
query lit_to_constant(key: LitToConstInput<'tcx>) -> Result<mir::ConstantKind<'tcx>, LitToConstError> {
966+
desc { "converting literal to mir constant"}
967+
}
968+
964969
query check_match(key: DefId) {
965970
desc { |tcx| "match-checking `{}`", tcx.def_path_str(key) }
966971
cache_on_disk_if { key.is_local() }

compiler/rustc_middle/src/thir.rs

Lines changed: 26 additions & 6 deletions
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,26 @@ 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+
ScalarLiteral {
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+
literal: ty::Const<'tcx>,
428+
def_id: DefId,
429+
user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
430+
},
431+
// FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
418432
/// A literal containing the address of a `static`.
419433
///
420434
/// This is only distinguished from `Literal` so that we can register some
@@ -439,6 +453,12 @@ pub enum ExprKind<'tcx> {
439453
},
440454
}
441455

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

compiler/rustc_middle/src/thir/visit.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
9393
visitor.visit_expr(&visitor.thir()[value])
9494
}
9595
}
96-
ConstBlock { value } => visitor.visit_const(value),
96+
ConstBlock { did: _, substs: _ } => {}
9797
Repeat { value, count } => {
9898
visitor.visit_expr(&visitor.thir()[value]);
9999
visitor.visit_const(count);
@@ -122,7 +122,10 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
122122
visitor.visit_expr(&visitor.thir()[source])
123123
}
124124
Closure { closure_id: _, substs: _, upvars: _, movability: _, fake_reads: _ } => {}
125-
Literal { literal, user_ty: _, const_id: _ } => visitor.visit_const(literal),
125+
Literal { lit: _, neg: _ } => {}
126+
ScalarLiteral { lit: _, user_ty: _ } => {}
127+
NamedConst { def_id: _, substs: _, user_ty: _ } => {}
128+
ConstParam { literal: _, def_id: _, user_ty: _ } => {}
126129
StaticRef { alloc_id: _, ty: _, def_id: _ } => {}
127130
InlineAsm { ref operands, template: _, options: _, line_spans: _ } => {
128131
for op in &**operands {
Lines changed: 120 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,153 @@
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+
debug!("expr: {:#?}", expr);
21+
// FIXME: Maybe we should try to evaluate here and only create an `Unevaluated`
22+
// constant in case the evaluation fails. Need some evaluation function that
23+
// allows normalization to fail.
24+
let create_uneval_from_def_id =
25+
|tcx: TyCtxt<'tcx>, def_id: DefId, ty: Ty<'tcx>, substs: SubstsRef<'tcx>| {
26+
let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
27+
tcx.mk_const(ty::ConstS { val: ty::ConstKind::Unevaluated(uneval), ty })
28+
};
29+
1330
let this = self;
31+
let tcx = this.tcx;
1432
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
1533
match *kind {
1634
ExprKind::Scope { region_scope: _, lint_level: _, value } => {
1735
this.as_constant(&this.thir[value])
1836
}
19-
ExprKind::Literal { literal, user_ty, const_id: _ } => {
37+
ExprKind::Literal { lit, neg } => {
38+
let literal = match tcx.at(expr.span).lit_to_constant(LitToConstInput {
39+
lit: &lit.node,
40+
ty,
41+
neg,
42+
}) {
43+
Ok(c) => c,
44+
Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
45+
Err(LitToConstError::TypeError) => {
46+
bug!("encountered type error in `lit_to_constant")
47+
}
48+
};
49+
50+
Constant { span, user_ty: None, literal: literal.into() }
51+
}
52+
ExprKind::ScalarLiteral { lit, user_ty } => {
53+
let user_ty = user_ty.map(|user_ty| {
54+
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
55+
span,
56+
user_ty,
57+
inferred_ty: ty,
58+
})
59+
});
60+
61+
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
62+
63+
Constant { span, user_ty: user_ty, literal }
64+
}
65+
ExprKind::NamedConst { def_id, substs, user_ty } => {
66+
let user_ty = user_ty.map(|user_ty| {
67+
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
68+
span,
69+
user_ty,
70+
inferred_ty: ty,
71+
})
72+
});
73+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
74+
75+
Constant { user_ty, span, literal }
76+
}
77+
ExprKind::ConstParam { literal, def_id: _, user_ty } => {
2078
let user_ty = user_ty.map(|user_ty| {
2179
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
2280
span,
2381
user_ty,
2482
inferred_ty: ty,
2583
})
2684
});
27-
assert_eq!(literal.ty(), ty);
28-
Constant { span, user_ty, literal: literal.into() }
85+
let literal = ConstantKind::Ty(literal);
86+
87+
Constant { user_ty: user_ty, span, literal }
88+
}
89+
ExprKind::ConstBlock { did: def_id, substs } => {
90+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
91+
92+
Constant { user_ty: None, span, literal }
2993
}
3094
ExprKind::StaticRef { alloc_id, ty, .. } => {
31-
let const_val =
32-
ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &this.tcx));
95+
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
3396
let literal = ConstantKind::Val(const_val, ty);
3497

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

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

Lines changed: 3 additions & 0 deletions
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::ScalarLiteral { .. }
571+
| ExprKind::ConstParam { .. }
569572
| ExprKind::ConstBlock { .. }
570573
| ExprKind::StaticRef { .. }
571574
| ExprKind::InlineAsm { .. }

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

Lines changed: 3 additions & 0 deletions
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::ScalarLiteral { .. }
332+
| ExprKind::ConstParam { .. }
330333
| ExprKind::ConstBlock { .. }
331334
| ExprKind::StaticRef { .. }
332335
| ExprKind::Block { .. }

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

Lines changed: 1 addition & 1 deletion
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, .. } => {
7474
local_decl.local_info = Some(Box::new(LocalInfo::ConstRef { def_id }));
7575
}
7676
_ => {}

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

Lines changed: 6 additions & 3 deletions
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::ScalarLiteral { .. }
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

Lines changed: 3 additions & 0 deletions
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::ScalarLiteral { .. }
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

Lines changed: 1 addition & 1 deletion
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/build/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,4 +1078,5 @@ mod matches;
10781078
mod misc;
10791079
mod scope;
10801080

1081+
crate use expr::as_constant;
10811082
pub(crate) use expr::category::Category as ExprCategory;

compiler/rustc_mir_build/src/check_unsafety.rs

Lines changed: 3 additions & 0 deletions
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::ScalarLiteral { .. }
308+
| ExprKind::ConstParam { .. }
306309
| ExprKind::ConstBlock { .. }
307310
| ExprKind::Deref { .. }
308311
| ExprKind::Index { .. }

compiler/rustc_mir_build/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use rustc_middle::ty::query::Providers;
2727
pub fn provide(providers: &mut Providers) {
2828
providers.check_match = thir::pattern::check_match;
2929
providers.lit_to_const = thir::constant::lit_to_const;
30+
providers.lit_to_constant = build::as_constant::lit_to_constant;
3031
providers.mir_built = build::mir_built;
3132
providers.thir_check_unsafety = check_unsafety::thir_check_unsafety;
3233
providers.thir_check_unsafety_for_const_arg = check_unsafety::thir_check_unsafety_for_const_arg;

compiler/rustc_mir_build/src/thir/constant.rs

Lines changed: 7 additions & 1 deletion
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)