Skip to content

Commit 9f5f777

Browse files
committed
perf: eagerly convert literals to consts, this avoids creating loads on unevaluated consts
which requires a lot of unnecessary work to evaluate them further down the line.
1 parent caa231d commit 9f5f777

File tree

17 files changed

+174
-86
lines changed

17 files changed

+174
-86
lines changed

src/librustc/dep_graph/dep_node.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
use crate::hir::map::DefPathHash;
5353
use crate::ich::{Fingerprint, StableHashingContext};
5454
use crate::mir;
55-
use crate::mir::interpret::GlobalId;
55+
use crate::mir::interpret::{GlobalId, LitToConstInput};
5656
use crate::traits;
5757
use crate::traits::query::{
5858
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,

src/librustc/mir/interpret/mod.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ use crate::mir;
119119
use crate::ty::codec::TyDecoder;
120120
use crate::ty::layout::{self, Size};
121121
use crate::ty::subst::GenericArgKind;
122-
use crate::ty::{self, Instance, TyCtxt};
122+
use crate::ty::{self, Instance, Ty, TyCtxt};
123123
use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};
124124
use rustc_data_structures::fx::FxHashMap;
125125
use rustc_data_structures::sync::{HashMapExt, Lock};
@@ -131,6 +131,7 @@ use std::fmt;
131131
use std::io;
132132
use std::num::NonZeroU32;
133133
use std::sync::atomic::{AtomicU32, Ordering};
134+
use syntax::ast::LitKind;
134135

135136
/// Uniquely identifies one of the following:
136137
/// - A constant
@@ -147,6 +148,24 @@ pub struct GlobalId<'tcx> {
147148
pub promoted: Option<mir::Promoted>,
148149
}
149150

151+
/// Input argument for `tcx.lit_to_const`
152+
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable)]
153+
pub struct LitToConstInput<'tcx> {
154+
/// The absolute value of the resultant constant
155+
pub lit: &'tcx LitKind,
156+
/// The type of the constant
157+
pub ty: Ty<'tcx>,
158+
/// If the constant is negative
159+
pub neg: bool,
160+
}
161+
162+
/// Error type for `tcx.lit_to_const`
163+
#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable)]
164+
pub enum LitToConstError {
165+
UnparseableFloat,
166+
Reported,
167+
}
168+
150169
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
151170
pub struct AllocId(pub u64);
152171

src/librustc/query/mod.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::dep_graph::{DepKind, DepNode, RecoverKey, SerializedDepNodeIndex};
22
use crate::mir;
3-
use crate::mir::interpret::GlobalId;
3+
use crate::mir::interpret::{GlobalId, LitToConstInput};
44
use crate::traits;
55
use crate::traits::query::{
66
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
@@ -509,6 +509,13 @@ rustc_queries! {
509509
no_force
510510
desc { "get a &core::panic::Location referring to a span" }
511511
}
512+
513+
query lit_to_const(
514+
key: LitToConstInput<'tcx>
515+
) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
516+
no_force
517+
desc { "converting literal to const" }
518+
}
512519
}
513520

514521
TypeChecking {

src/librustc/ty/query/keys.rs

+10
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ impl<'tcx> Key for mir::interpret::GlobalId<'tcx> {
5252
}
5353
}
5454

55+
impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> {
56+
fn query_crate(&self) -> CrateNum {
57+
LOCAL_CRATE
58+
}
59+
60+
fn default_span(&self, _tcx: TyCtxt<'_>) -> Span {
61+
DUMMY_SP
62+
}
63+
}
64+
5565
impl Key for CrateNum {
5666
fn query_crate(&self) -> CrateNum {
5767
*self

src/librustc/ty/query/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use crate::middle::stability::{self, DeprecationEntry};
1515
use crate::mir;
1616
use crate::mir::interpret::GlobalId;
1717
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult};
18+
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1819
use crate::mir::mono::CodegenUnit;
1920
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
2021
use crate::session::CrateDisambiguator;

src/librustc_mir/hair/constant.rs

+33-24
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
1-
use rustc::mir::interpret::{ConstValue, Scalar};
2-
use rustc::ty::{self, layout::Size, ParamEnv, Ty, TyCtxt};
1+
use rustc::mir::interpret::{
2+
truncate, Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
3+
};
4+
use rustc::ty::{self, layout::Size, ParamEnv, TyCtxt};
35
use rustc_span::symbol::Symbol;
46
use syntax::ast;
57

6-
#[derive(PartialEq)]
7-
crate enum LitToConstError {
8-
UnparseableFloat,
9-
Reported,
10-
}
11-
128
crate fn lit_to_const<'tcx>(
13-
lit: &'tcx ast::LitKind,
149
tcx: TyCtxt<'tcx>,
15-
ty: Ty<'tcx>,
16-
neg: bool,
10+
lit_input: LitToConstInput<'tcx>,
1711
) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
18-
use syntax::ast::*;
12+
let LitToConstInput { lit, ty, neg } = lit_input;
1913

2014
let trunc = |n| {
2115
let param_ty = ParamEnv::reveal_all().and(ty);
@@ -26,35 +20,50 @@ crate fn lit_to_const<'tcx>(
2620
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
2721
};
2822

29-
use rustc::mir::interpret::*;
3023
let lit = match *lit {
31-
LitKind::Str(ref s, _) => {
24+
ast::LitKind::Str(ref s, _) => {
3225
let s = s.as_str();
3326
let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes());
3427
let allocation = tcx.intern_const_alloc(allocation);
3528
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
3629
}
37-
LitKind::ByteStr(ref data) => {
38-
let id = tcx.allocate_bytes(data);
39-
ConstValue::Scalar(Scalar::Ptr(id.into()))
30+
ast::LitKind::ByteStr(ref data) => {
31+
if let ty::Ref(_, ref_ty, _) = ty.kind {
32+
match ref_ty.kind {
33+
ty::Slice(_) => {
34+
let allocation = Allocation::from_byte_aligned_bytes(data as &Vec<u8>);
35+
let allocation = tcx.intern_const_alloc(allocation);
36+
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
37+
}
38+
ty::Array(_, _) => {
39+
let id = tcx.allocate_bytes(data);
40+
ConstValue::Scalar(Scalar::Ptr(id.into()))
41+
}
42+
_ => {
43+
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
44+
}
45+
}
46+
} else {
47+
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
48+
}
4049
}
41-
LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
42-
LitKind::Int(n, _) if neg => {
50+
ast::LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
51+
ast::LitKind::Int(n, _) if neg => {
4352
let n = n as i128;
4453
let n = n.overflowing_neg().0;
4554
trunc(n as u128)?
4655
}
47-
LitKind::Int(n, _) => trunc(n)?,
48-
LitKind::Float(n, _) => {
56+
ast::LitKind::Int(n, _) => trunc(n)?,
57+
ast::LitKind::Float(n, _) => {
4958
let fty = match ty.kind {
5059
ty::Float(fty) => fty,
5160
_ => bug!(),
5261
};
5362
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
5463
}
55-
LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
56-
LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
57-
LitKind::Err(_) => unreachable!(),
64+
ast::LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
65+
ast::LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
66+
ast::LitKind::Err(_) => return Err(LitToConstError::Reported),
5867
};
5968
Ok(tcx.mk_const(ty::Const { val: ty::ConstKind::Value(lit), ty }))
6069
}

src/librustc_mir/hair/cx/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
use crate::hair::util::UserAnnotatedTyHelpers;
66
use crate::hair::*;
77

8-
use crate::hair::constant::{lit_to_const, LitToConstError};
98
use rustc::infer::InferCtxt;
109
use rustc::middle::region;
10+
use rustc::mir::interpret::{LitToConstError, LitToConstInput};
1111
use rustc::ty::layout::VariantIdx;
1212
use rustc::ty::subst::Subst;
1313
use rustc::ty::subst::{GenericArg, InternalSubsts};
@@ -136,7 +136,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> {
136136
) -> &'tcx ty::Const<'tcx> {
137137
trace!("const_eval_literal: {:#?}, {:?}, {:?}, {:?}", lit, ty, sp, neg);
138138

139-
match lit_to_const(lit, self.tcx, ty, neg) {
139+
match self.tcx.at(sp).lit_to_const(LitToConstInput { lit, ty, neg }) {
140140
Ok(c) => c,
141141
Err(LitToConstError::UnparseableFloat) => {
142142
// FIXME(#31407) this is only necessary because float parsing is buggy

src/librustc_mir/hair/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use rustc_hir as hir;
1616
use rustc_hir::def_id::DefId;
1717
use rustc_span::Span;
1818

19-
mod constant;
19+
pub(crate) mod constant;
2020
pub mod cx;
2121

2222
pub mod pattern;

src/librustc_mir/hair/pattern/mod.rs

+24-28
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@ mod const_to_pat;
66

77
pub(crate) use self::check_match::check_match;
88

9-
use crate::hair::constant::*;
109
use crate::hair::util::UserAnnotatedTyHelpers;
1110

12-
use rustc::mir::interpret::{get_slice_bytes, sign_extend, ConstValue, ErrorHandled};
11+
use rustc::mir::interpret::{
12+
get_slice_bytes, sign_extend, ConstValue, ErrorHandled, LitToConstError, LitToConstInput,
13+
};
1314
use rustc::mir::UserTypeProjection;
1415
use rustc::mir::{BorrowKind, Field, Mutability};
1516
use rustc::ty::layout::VariantIdx;
@@ -803,35 +804,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
803804
/// which would overflow if we tried to evaluate `128_i8` and then negate
804805
/// afterwards.
805806
fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
806-
match expr.kind {
807-
hir::ExprKind::Lit(ref lit) => {
808-
let ty = self.tables.expr_ty(expr);
809-
match lit_to_const(&lit.node, self.tcx, ty, false) {
810-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
811-
Err(LitToConstError::UnparseableFloat) => {
812-
self.errors.push(PatternError::FloatBug);
813-
PatKind::Wild
814-
}
815-
Err(LitToConstError::Reported) => PatKind::Wild,
807+
if let hir::ExprKind::Path(ref qpath) = expr.kind {
808+
*self.lower_path(qpath, expr.hir_id, expr.span).kind
809+
} else {
810+
let (lit, neg) = match expr.kind {
811+
hir::ExprKind::Lit(ref lit) => (lit, false),
812+
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
813+
let lit = match expr.kind {
814+
hir::ExprKind::Lit(ref lit) => lit,
815+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
816+
};
817+
(lit, true)
816818
}
817-
}
818-
hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
819-
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
820-
let ty = self.tables.expr_ty(expr);
821-
let lit = match expr.kind {
822-
hir::ExprKind::Lit(ref lit) => lit,
823-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
824-
};
825-
match lit_to_const(&lit.node, self.tcx, ty, true) {
826-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
827-
Err(LitToConstError::UnparseableFloat) => {
828-
self.errors.push(PatternError::FloatBug);
829-
PatKind::Wild
830-
}
831-
Err(LitToConstError::Reported) => PatKind::Wild,
819+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
820+
};
821+
822+
let lit_input = LitToConstInput { lit: &lit.node, ty: self.tables.expr_ty(expr), neg };
823+
match self.tcx.at(expr.span).lit_to_const(lit_input) {
824+
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
825+
Err(LitToConstError::UnparseableFloat) => {
826+
self.errors.push(PatternError::FloatBug);
827+
PatKind::Wild
832828
}
829+
Err(LitToConstError::Reported) => PatKind::Wild,
833830
}
834-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
835831
}
836832
}
837833
}

src/librustc_mir/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,5 @@ pub fn provide(providers: &mut Providers<'_>) {
6464
let (param_env, (value, field)) = param_env_and_value.into_parts();
6565
const_eval::const_field(tcx, param_env, None, field, value)
6666
};
67+
providers.lit_to_const = hair::constant::lit_to_const;
6768
}

src/librustc_typeck/astconv.rs

+27-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// ignore-tidy-filelength FIXME(#67418) Split up this file
12
//! Conversion from AST representation of types to the `ty.rs` representation.
23
//! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
34
//! instance of `AstConv`.
@@ -38,6 +39,7 @@ use std::collections::BTreeSet;
3839
use std::iter;
3940
use std::slice;
4041

42+
use rustc::mir::interpret::LitToConstInput;
4143
use rustc_error_codes::*;
4244

4345
#[derive(Debug)]
@@ -2696,13 +2698,28 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
26962698
let tcx = self.tcx();
26972699
let def_id = tcx.hir().local_def_id(ast_const.hir_id);
26982700

2699-
let mut const_ = ty::Const {
2700-
val: ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id)),
2701-
ty,
2701+
let expr = &tcx.hir().body(ast_const.body).value;
2702+
2703+
let lit_input = match expr.kind {
2704+
hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2705+
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => match expr.kind {
2706+
hir::ExprKind::Lit(ref lit) => {
2707+
Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2708+
}
2709+
_ => None,
2710+
},
2711+
_ => None,
27022712
};
27032713

2704-
let expr = &tcx.hir().body(ast_const.body).value;
2705-
if let Some(def_id) = self.const_param_def_id(expr) {
2714+
if let Some(lit_input) = lit_input {
2715+
// If an error occurred, ignore that it's a literal and leave reporting the error up to
2716+
// mir
2717+
if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
2718+
return c;
2719+
}
2720+
}
2721+
2722+
let kind = if let Some(def_id) = self.const_param_def_id(expr) {
27062723
// Find the name and index of the const parameter by indexing the generics of the
27072724
// parent item and construct a `ParamConst`.
27082725
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
@@ -2711,10 +2728,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
27112728
let generics = tcx.generics_of(item_def_id);
27122729
let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
27132730
let name = tcx.hir().name(hir_id);
2714-
const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2715-
}
2716-
2717-
tcx.mk_const(const_)
2731+
ty::ConstKind::Param(ty::ParamConst::new(index, name))
2732+
} else {
2733+
ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id))
2734+
};
2735+
tcx.mk_const(ty::Const { val: kind, ty })
27182736
}
27192737

27202738
pub fn impl_trait_ty_to_ty(

0 commit comments

Comments
 (0)