Skip to content

Commit

Permalink
librustc: Introduce a "quick reject" mechanism to quickly throw out
Browse files Browse the repository at this point in the history
method candidates and prevent method lookup from being invoked at all
for overloaded operators.

40%-50% improvement in typechecking time.
  • Loading branch information
pcwalton committed Oct 13, 2014
1 parent 86509d8 commit 1a1ce83
Show file tree
Hide file tree
Showing 5 changed files with 425 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/librustc/driver/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ pub struct Options {
/// An optional name to use as the crate for std during std injection,
/// written `extern crate std = "name"`. Default to "std". Used by
/// out-of-tree drivers.
pub alt_std_name: Option<String>
pub alt_std_name: Option<String>,
}

/// Some reasonable defaults
Expand Down Expand Up @@ -841,7 +841,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
color: color,
externs: externs,
crate_name: crate_name,
alt_std_name: None
alt_std_name: None,
}
}

Expand Down
190 changes: 190 additions & 0 deletions src/librustc/middle/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,11 @@ pub struct ctxt<'tcx> {

/// Caches the representation hints for struct definitions.
pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,

pub overloaded_operator_filter:
RefCell<HashMap<SimplifiedType,OverloadedOperatorFilter>>,

pub smart_pointers: RefCell<DefIdSet>,
}

pub enum tbox_flag {
Expand Down Expand Up @@ -1537,6 +1542,8 @@ pub fn mk_ctxt<'tcx>(s: Session,
trait_associated_types: RefCell::new(DefIdMap::new()),
selection_cache: traits::SelectionCache::new(),
repr_hint_cache: RefCell::new(DefIdMap::new()),
overloaded_operator_filter: RefCell::new(HashMap::new()),
smart_pointers: RefCell::new(DefIdSet::new()),
}
}

Expand Down Expand Up @@ -5598,3 +5605,186 @@ pub fn with_freevars<T>(tcx: &ty::ctxt, fid: ast::NodeId, f: |&[Freevar]| -> T)
Some(d) => f(d.as_slice())
}
}

pub enum AllowDerefableFlag<'a> {
AllowDerefable,
DisallowDerefable(&'a ParameterEnvironment),
}

#[deriving(Clone, PartialEq, Eq, Hash)]
pub enum SimplifiedType {
NilSimplifiedType,
BoolSimplifiedType,
CharSimplifiedType,
IntSimplifiedType(ast::IntTy),
UintSimplifiedType(ast::UintTy),
FloatSimplifiedType(ast::FloatTy),
EnumSimplifiedType(DefId),
StrSimplifiedType,
VecSimplifiedType,
PtrSimplifiedType,
TupleSimplifiedType(uint),
TraitSimplifiedType(DefId),
StructSimplifiedType(DefId),
UnboxedClosureSimplifiedType(DefId),
FunctionSimplifiedType(uint),
ParameterSimplifiedType,
}

impl SimplifiedType {
pub fn from_type(tcx: &ctxt,
ty: ty::t,
can_simplify_params: bool,
allow_derefable: AllowDerefableFlag)
-> Option<SimplifiedType> {
let simplified_type = match get(ty).sty {
ty_nil => Some(NilSimplifiedType),
ty_bool => Some(BoolSimplifiedType),
ty_char => Some(CharSimplifiedType),
ty_int(int_type) => Some(IntSimplifiedType(int_type)),
ty_uint(uint_type) => Some(UintSimplifiedType(uint_type)),
ty_float(float_type) => Some(FloatSimplifiedType(float_type)),
ty_enum(def_id, _) => Some(EnumSimplifiedType(def_id)),
ty_str => Some(StrSimplifiedType),
ty_trait(ref trait_info) => {
Some(TraitSimplifiedType(trait_info.def_id))
}
ty_struct(def_id, _) => {
Some(StructSimplifiedType(def_id))
}
ty_unboxed_closure(def_id, _) => {
Some(UnboxedClosureSimplifiedType(def_id))
}
ty_vec(..) => Some(VecSimplifiedType),
ty_ptr(_) => Some(PtrSimplifiedType),
ty_rptr(_, ref mt) => {
SimplifiedType::from_type(tcx,
mt.ty,
can_simplify_params,
allow_derefable)
}
ty_uniq(ref ty) => {
SimplifiedType::from_type(tcx,
*ty,
can_simplify_params,
allow_derefable)
}
ty_tup(ref tys) => Some(TupleSimplifiedType(tys.len())),
ty_closure(ref f) => {
Some(FunctionSimplifiedType(f.sig.inputs.len()))
}
ty_bare_fn(ref f) => {
Some(FunctionSimplifiedType(f.sig.inputs.len()))
}
ty_param(_) if can_simplify_params => {
Some(ParameterSimplifiedType)
}
ty_bot | ty_param(_) | ty_open(_) | ty_infer(_) | ty_err => None,
};

let simplified_type = match simplified_type {
None => return None,
Some(simplified_type) => simplified_type,
};

match allow_derefable {
AllowDerefable => {}
DisallowDerefable(param_env) => {
match tcx.overloaded_operator_filter
.borrow()
.find(&simplified_type) {
Some(ref flags) if flags.contains(
DEREF_OVERLOADED_OPERATOR_FILTER) => {
return None
}
Some(_) | None => {}
}

match get(ty).sty {
ty_param(ref param_ty) => {
let bounds = &param_env.bounds
.get(param_ty.space,
param_ty.idx)
.trait_bounds;
for bound in bounds.iter() {
let bad = Some(bound.def_id) ==
tcx.lang_items.deref_trait() ||
Some(bound.def_id) ==
tcx.lang_items.deref_mut_trait();
debug!("for param {} bound {} deref {} bad {}",
param_ty.repr(tcx),
bound.repr(tcx),
tcx.lang_items.deref_trait(),
bad);
if bad {
return None
}
}
}
_ => {}
}
}
}

Some(simplified_type)
}
}

pub enum MethodLookupKey {
SimplifiedTypeLookupKey(SimplifiedType),
SmartPointerLookupKey(ast::DefId, SimplifiedType),
}

impl MethodLookupKey {
pub fn from_type(tcx: &ctxt, ty: ty::t, param_env: &ParameterEnvironment)
-> Option<MethodLookupKey> {
match get(ty).sty {
ty_struct(def_id, ref substs) => {
if tcx.smart_pointers.borrow().contains(&def_id) {
let simplified_referent = SimplifiedType::from_type(
tcx,
*substs.types.get(subst::TypeSpace, 0),
true,
DisallowDerefable(param_env));
match simplified_referent {
None => return None,
Some(simplified_referent) => {
return Some(SmartPointerLookupKey(
def_id,
simplified_referent))
}
}
}
}
_ => {}
}

match SimplifiedType::from_type(tcx,
ty,
true,
DisallowDerefable(param_env)) {
None => None,
Some(simplified_type) => {
Some(SimplifiedTypeLookupKey(simplified_type))
}
}
}

pub fn might_match(&self, other: &SimplifiedType) -> bool {
match *self {
SimplifiedTypeLookupKey(ref this) => *this == *other,
SmartPointerLookupKey(def_id, ref this) => {
*this == *other || StructSimplifiedType(def_id) == *other
}
}
}
}

bitflags! {
flags OverloadedOperatorFilter: u8 {
const INDEX_OVERLOADED_OPERATOR_FILTER = 0x01,
const DEREF_OVERLOADED_OPERATOR_FILTER = 0x02,
const CALL_OVERLOADED_OPERATOR_FILTER = 0x04
}
}

65 changes: 60 additions & 5 deletions src/librustc/middle/typeck/check/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,15 @@ pub fn lookup<'a, 'tcx>(
lcx.push_inherent_candidates(self_ty);
debug!("searching extension candidates");
lcx.push_bound_candidates(self_ty, None);
lcx.push_extension_candidates(expr.id);

let method_lookup_key = MethodLookupKey::from_type(fcx.tcx(),
self_ty,
&fcx.inh.param_env);
if method_lookup_key.is_none() {
debug!("couldn't simplify {}", lcx.ty_to_string(self_ty));
}
lcx.push_extension_candidates(expr.id, &method_lookup_key);

lcx.search(self_ty)
}

Expand Down Expand Up @@ -197,7 +205,14 @@ pub fn lookup_in_trait<'a, 'tcx>(
self_ty.repr(fcx.tcx()), self_expr.map(|e| e.repr(fcx.tcx())));

lcx.push_bound_candidates(self_ty, Some(trait_did));
lcx.push_extension_candidate(trait_did);

let method_lookup_key = MethodLookupKey::from_type(fcx.tcx(),
self_ty,
&fcx.inh.param_env);
if method_lookup_key.is_none() {
debug!("couldn't simplify {}", lcx.ty_to_string(self_ty));
}
lcx.push_extension_candidate(trait_did, &method_lookup_key);
lcx.search(self_ty)
}

Expand Down Expand Up @@ -484,7 +499,9 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
});
}

fn push_extension_candidate(&mut self, trait_did: DefId) {
fn push_extension_candidate(&mut self,
trait_did: DefId,
method_lookup_key: &Option<MethodLookupKey>) {
ty::populate_implementations_for_trait_if_necessary(self.tcx(), trait_did);

// Look for explicit implementations.
Expand All @@ -494,12 +511,16 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
let items = impl_items.get(impl_did);
self.push_candidates_from_impl(*impl_did,
items.as_slice(),
method_lookup_key,
true);
}
}
}

fn push_extension_candidates(&mut self, expr_id: ast::NodeId) {
fn push_extension_candidates(
&mut self,
expr_id: ast::NodeId,
method_lookup_key: &Option<MethodLookupKey>) {
// If the method being called is associated with a trait, then
// find all the impls of that trait. Each of those are
// candidates.
Expand All @@ -512,7 +533,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
} else {
"(external)".to_string()
});
self.push_extension_candidate(*trait_did);
self.push_extension_candidate(*trait_did, method_lookup_key);
}
}
}
Expand Down Expand Up @@ -775,6 +796,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
let items = impl_items.get(impl_did);
self.push_candidates_from_impl(*impl_did,
items.as_slice(),
&None,
false);
}
}
Expand All @@ -783,6 +805,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
fn push_candidates_from_impl(&mut self,
impl_did: DefId,
impl_items: &[ImplOrTraitItemId],
method_lookup_key: &Option<MethodLookupKey>,
is_extension: bool) {
let did = if self.report_statics == ReportStaticMethods {
// we only want to report each base trait once
Expand All @@ -798,6 +821,38 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> {
return; // already visited
}

// See if we can quickly reject...
match *method_lookup_key {
Some(ref method_lookup_key) => {
let impl_type = ty::lookup_item_type(self.tcx(), impl_did);
let simplified_impl_type =
SimplifiedType::from_type(self.tcx(),
impl_type.ty,
false,
ty::AllowDerefable);
match simplified_impl_type {
Some(ref simplified_impl_type) => {
if !method_lookup_key.might_match(
simplified_impl_type) {
debug!("quick reject succeeded");
return
}
debug!("quick reject failed: could possibly unify");
}
None => {
debug!("quick reject failed: impl type {} was \
unsimplifiable",
self.ty_to_string(impl_type.ty));
}
}
}
None => {
if is_extension {
debug!("quick reject failed: callee is unsimplifiable");
}
}
}

debug!("push_candidates_from_impl: {} {}",
token::get_name(self.m_name),
impl_items.iter()
Expand Down
Loading

0 comments on commit 1a1ce83

Please sign in to comment.