Skip to content

Commit 3704c43

Browse files
committed
Auto merge of #68118 - skinny121:eager_lit_eval, r=<try>
perf: Eagerly convert literals to consts Previousely even literal constants were being converted to an `Unevaluted` constant for evaluation later. This seems unecessary as no more information is needed to be able to convert the literal to a mir constant. Hopefully this will also minimise the performance impact of #67717, as far less constant evaluations are needed.
2 parents 543b7d9 + 5a20dba commit 3704c43

File tree

18 files changed

+146
-86
lines changed

18 files changed

+146
-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

+22-27
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ 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

1211
use rustc::mir::interpret::{get_slice_bytes, sign_extend, ConstValue, ErrorHandled};
12+
use rustc::mir::interpret::{LitToConstError, LitToConstInput};
1313
use rustc::mir::UserTypeProjection;
1414
use rustc::mir::{BorrowKind, Field, Mutability};
1515
use rustc::ty::layout::VariantIdx;
@@ -829,35 +829,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
829829
/// which would overflow if we tried to evaluate `128_i8` and then negate
830830
/// afterwards.
831831
fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
832-
match expr.kind {
833-
hir::ExprKind::Lit(ref lit) => {
834-
let ty = self.tables.expr_ty(expr);
835-
match lit_to_const(&lit.node, self.tcx, ty, false) {
836-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
837-
Err(LitToConstError::UnparseableFloat) => {
838-
self.errors.push(PatternError::FloatBug);
839-
PatKind::Wild
840-
}
841-
Err(LitToConstError::Reported) => PatKind::Wild,
832+
if let hir::ExprKind::Path(ref qpath) = expr.kind {
833+
*self.lower_path(qpath, expr.hir_id, expr.span).kind
834+
} else {
835+
let (lit, neg) = match expr.kind {
836+
hir::ExprKind::Lit(ref lit) => (lit, false),
837+
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
838+
let lit = match expr.kind {
839+
hir::ExprKind::Lit(ref lit) => lit,
840+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
841+
};
842+
(lit, true)
842843
}
843-
}
844-
hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
845-
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
846-
let ty = self.tables.expr_ty(expr);
847-
let lit = match expr.kind {
848-
hir::ExprKind::Lit(ref lit) => lit,
849-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
850-
};
851-
match lit_to_const(&lit.node, self.tcx, ty, true) {
852-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
853-
Err(LitToConstError::UnparseableFloat) => {
854-
self.errors.push(PatternError::FloatBug);
855-
PatKind::Wild
856-
}
857-
Err(LitToConstError::Reported) => PatKind::Wild,
844+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
845+
};
846+
847+
let lit_input = LitToConstInput { lit: &lit.node, ty: self.tables.expr_ty(expr), neg };
848+
match self.tcx.at(expr.span).lit_to_const(lit_input) {
849+
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
850+
Err(LitToConstError::UnparseableFloat) => {
851+
self.errors.push(PatternError::FloatBug);
852+
PatKind::Wild
858853
}
854+
Err(LitToConstError::Reported) => PatKind::Wild,
859855
}
860-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
861856
}
862857
}
863858
}

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`.
@@ -37,6 +38,7 @@ use std::collections::BTreeSet;
3738
use std::iter;
3839
use std::slice;
3940

41+
use rustc::mir::interpret::LitToConstInput;
4042
use rustc_error_codes::*;
4143

4244
#[derive(Debug)]
@@ -2699,13 +2701,28 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
26992701
let tcx = self.tcx();
27002702
let def_id = tcx.hir().local_def_id(ast_const.hir_id);
27012703

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

2707-
let expr = &tcx.hir().body(ast_const.body).value;
2708-
if let Some(def_id) = self.const_param_def_id(expr) {
2717+
if let Some(lit_input) = lit_input {
2718+
// If an error occurred, ignore that it's a literal and leave reporting the error up to
2719+
// mir.
2720+
if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
2721+
return c;
2722+
}
2723+
}
2724+
2725+
let kind = if let Some(def_id) = self.const_param_def_id(expr) {
27092726
// Find the name and index of the const parameter by indexing the generics of the
27102727
// parent item and construct a `ParamConst`.
27112728
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
@@ -2714,10 +2731,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
27142731
let generics = tcx.generics_of(item_def_id);
27152732
let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
27162733
let name = tcx.hir().name(hir_id);
2717-
const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2718-
}
2719-
2720-
tcx.mk_const(const_)
2734+
ty::ConstKind::Param(ty::ParamConst::new(index, name))
2735+
} else {
2736+
ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id))
2737+
};
2738+
tcx.mk_const(ty::Const { val: kind, ty })
27212739
}
27222740

27232741
pub fn impl_trait_ty_to_ty(

src/libsyntax/ast.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1441,8 +1441,8 @@ pub struct MacroDef {
14411441
pub legacy: bool,
14421442
}
14431443

1444-
// Clippy uses Hash and PartialEq
1445-
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1444+
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
1445+
#[derive(HashStable_Generic)]
14461446
pub enum StrStyle {
14471447
/// A regular string, like `"foo"`.
14481448
Cooked,
@@ -1491,9 +1491,9 @@ impl StrLit {
14911491
}
14921492
}
14931493

1494-
// Clippy uses Hash and PartialEq
14951494
/// Type of the integer literal based on provided suffix.
1496-
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1495+
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1496+
#[derive(HashStable_Generic)]
14971497
pub enum LitIntType {
14981498
/// e.g. `42_i32`.
14991499
Signed(IntTy),
@@ -1504,7 +1504,8 @@ pub enum LitIntType {
15041504
}
15051505

15061506
/// Type of the float literal based on provided suffix.
1507-
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1507+
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1508+
#[derive(HashStable_Generic)]
15081509
pub enum LitFloatType {
15091510
/// A float literal with a suffix (`1f32` or `1E10f32`).
15101511
Suffixed(FloatTy),
@@ -1515,8 +1516,7 @@ pub enum LitFloatType {
15151516
/// Literal kind.
15161517
///
15171518
/// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1518-
// Clippy uses Hash and PartialEq
1519-
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1519+
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
15201520
pub enum LitKind {
15211521
/// A string literal (`"foo"`).
15221522
Str(Symbol, StrStyle),

0 commit comments

Comments
 (0)