1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use back
::link
::exported_name
;
17 use middle
::subst
::{Subst, Substs}
;
19 use middle
::ty_fold
::{TypeFolder, TypeFoldable}
;
21 use trans
::attributes
;
22 use trans
::base
::{trans_enum_variant, push_ctxt, get_item_val}
;
23 use trans
::base
::trans_fn
;
28 use middle
::ty
::{self, HasProjectionTypes, Ty}
;
32 use syntax
::ast_util
::local_def
;
34 use syntax
::codemap
::DUMMY_SP
;
35 use std
::hash
::{Hasher, Hash, SipHasher}
;
37 pub fn monomorphic_fn
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
39 psubsts
: &'tcx subst
::Substs
<'tcx
>,
40 ref_id
: Option
<ast
::NodeId
>)
41 -> (ValueRef
, Ty
<'tcx
>, bool
) {
42 debug
!("monomorphic_fn(\
50 assert
!(psubsts
.types
.all(|t
| {
51 !ty
::type_needs_infer(*t
) && !ty
::type_has_params(*t
)
54 let _icx
= push_ctxt("monomorphic_fn");
56 let hash_id
= MonoId
{
58 params
: &psubsts
.types
61 let item_ty
= ty
::lookup_item_type(ccx
.tcx(), fn_id
).ty
;
63 debug
!("monomorphic_fn about to subst into {:?}", item_ty
);
64 let mono_ty
= item_ty
.subst(ccx
.tcx(), psubsts
);
66 match ccx
.monomorphized().borrow().get(&hash_id
) {
68 debug
!("leaving monomorphic fn {}",
69 ty
::item_path_str(ccx
.tcx(), fn_id
));
70 return (val
, mono_ty
, false);
75 debug
!("monomorphic_fn(\
84 let map_node
= session
::expect(
86 ccx
.tcx().map
.find(fn_id
.node
),
88 format
!("while monomorphizing {:?}, couldn't find it in \
89 the item map (may have attempted to monomorphize \
90 an item defined in a different crate?)",
94 if let ast_map
::NodeForeignItem(_
) = map_node
{
95 if ccx
.tcx().map
.get_foreign_abi(fn_id
.node
) != abi
::RustIntrinsic
{
96 // Foreign externs don't have to be monomorphized.
97 return (get_item_val(ccx
, fn_id
.node
), mono_ty
, true);
101 debug
!("mono_ty = {:?} (post-substitution)", mono_ty
);
103 let mono_ty
= normalize_associated_type(ccx
.tcx(), &mono_ty
);
104 debug
!("mono_ty = {:?} (post-normalization)", mono_ty
);
106 ccx
.stats().n_monos
.set(ccx
.stats().n_monos
.get() + 1);
110 let mut monomorphizing
= ccx
.monomorphizing().borrow_mut();
111 depth
= match monomorphizing
.get(&fn_id
) {
112 Some(&d
) => d
, None
=> 0
115 // Random cut-off -- code that needs to instantiate the same function
116 // recursively more than thirty times can probably safely be assumed
117 // to be causing an infinite expansion.
118 if depth
> ccx
.sess().recursion_limit
.get() {
119 ccx
.sess().span_fatal(ccx
.tcx().map
.span(fn_id
.node
),
120 "reached the recursion limit during monomorphization");
123 monomorphizing
.insert(fn_id
, depth
+ 1);
128 let mut state
= SipHasher
::new();
129 hash_id
.hash(&mut state
);
130 mono_ty
.hash(&mut state
);
132 hash
= format
!("h{}", state
.finish());
133 ccx
.tcx().map
.with_path(fn_id
.node
, |path
| {
134 exported_name(path
, &hash
[..])
138 debug
!("monomorphize_fn mangled to {}", s
);
140 // This shouldn't need to option dance.
141 let mut hash_id
= Some(hash_id
);
142 let mut mk_lldecl
= |abi
: abi
::Abi
| {
143 let lldecl
= if abi
!= abi
::Rust
{
144 foreign
::decl_rust_fn_with_foreign_abi(ccx
, mono_ty
, &s
[..])
146 // FIXME(nagisa): perhaps needs a more fine grained selection? See setup_lldecl below.
147 declare
::define_internal_rust_fn(ccx
, &s
[..], mono_ty
).unwrap_or_else(||{
148 ccx
.sess().bug(&format
!("symbol `{}` already defined", s
));
152 ccx
.monomorphized().borrow_mut().insert(hash_id
.take().unwrap(), lldecl
);
155 let setup_lldecl
= |lldecl
, attrs
: &[ast
::Attribute
]| {
156 base
::update_linkage(ccx
, lldecl
, None
, base
::OriginalTranslation
);
157 attributes
::from_fn_attrs(ccx
, attrs
, lldecl
);
159 let is_first
= !ccx
.available_monomorphizations().borrow().contains(&s
);
161 ccx
.available_monomorphizations().borrow_mut().insert(s
.clone());
164 let trans_everywhere
= attr
::requests_inline(attrs
);
165 if trans_everywhere
&& !is_first
{
166 llvm
::SetLinkage(lldecl
, llvm
::AvailableExternallyLinkage
);
169 // If `true`, then `lldecl` should be given a function body.
170 // Otherwise, it should be left as a declaration of an external
171 // function, with no definition in the current compilation unit.
172 trans_everywhere
|| is_first
175 let lldecl
= match map_node
{
176 ast_map
::NodeItem(i
) => {
179 node
: ast
::ItemFn(ref decl
, _
, _
, abi
, _
, ref body
),
182 let d
= mk_lldecl(abi
);
183 let needs_body
= setup_lldecl(d
, &i
.attrs
);
185 if abi
!= abi
::Rust
{
186 foreign
::trans_rust_fn_with_foreign_abi(
187 ccx
, &**decl
, &**body
, &[], d
, psubsts
, fn_id
.node
,
190 trans_fn(ccx
, &**decl
, &**body
, d
, psubsts
, fn_id
.node
, &[]);
197 ccx
.sess().bug("Can't monomorphize this kind of item")
201 ast_map
::NodeVariant(v
) => {
202 let parent
= ccx
.tcx().map
.get_parent(fn_id
.node
);
203 let tvs
= ty
::enum_variants(ccx
.tcx(), local_def(parent
));
204 let this_tv
= tvs
.iter().find(|tv
| { tv.id.node == fn_id.node}
).unwrap();
205 let d
= mk_lldecl(abi
::Rust
);
206 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
208 ast
::TupleVariantKind(ref args
) => {
209 trans_enum_variant(ccx
,
217 ast
::StructVariantKind(_
) =>
218 ccx
.sess().bug("can't monomorphize struct variants"),
222 ast_map
::NodeImplItem(impl_item
) => {
223 match impl_item
.node
{
224 ast
::MethodImplItem(ref sig
, ref body
) => {
225 let d
= mk_lldecl(abi
::Rust
);
226 let needs_body
= setup_lldecl(d
, &impl_item
.attrs
);
239 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
244 ast_map
::NodeTraitItem(trait_item
) => {
245 match trait_item
.node
{
246 ast
::MethodTraitItem(ref sig
, Some(ref body
)) => {
247 let d
= mk_lldecl(abi
::Rust
);
248 let needs_body
= setup_lldecl(d
, &trait_item
.attrs
);
250 trans_fn(ccx
, &sig
.decl
, body
, d
,
251 psubsts
, trait_item
.id
, &[]);
256 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
261 ast_map
::NodeStructCtor(struct_def
) => {
262 let d
= mk_lldecl(abi
::Rust
);
263 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
264 base
::trans_tuple_struct(ccx
,
266 struct_def
.ctor_id
.expect("ast-mapped tuple struct \
267 didn't have a ctor id"),
273 // Ugh -- but this ensures any new variants won't be forgotten
274 ast_map
::NodeForeignItem(..) |
275 ast_map
::NodeLifetime(..) |
276 ast_map
::NodeExpr(..) |
277 ast_map
::NodeStmt(..) |
278 ast_map
::NodeArg(..) |
279 ast_map
::NodeBlock(..) |
280 ast_map
::NodePat(..) |
281 ast_map
::NodeLocal(..) => {
282 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
287 ccx
.monomorphizing().borrow_mut().insert(fn_id
, depth
);
289 debug
!("leaving monomorphic fn {}", ty
::item_path_str(ccx
.tcx(), fn_id
));
290 (lldecl
, mono_ty
, true)
293 #[derive(PartialEq, Eq, Hash, Debug)]
294 pub struct MonoId
<'tcx
> {
296 pub params
: &'tcx subst
::VecPerParamSpace
<Ty
<'tcx
>>
299 /// Monomorphizes a type from the AST by first applying the in-scope
300 /// substitutions and then normalizing any associated types.
301 pub fn apply_param_substs
<'tcx
,T
>(tcx
: &ty
::ctxt
<'tcx
>,
302 param_substs
: &Substs
<'tcx
>,
305 where T
: TypeFoldable
<'tcx
> + HasProjectionTypes
307 let substituted
= value
.subst(tcx
, param_substs
);
308 normalize_associated_type(tcx
, &substituted
)
311 /// Removes associated types, if any. Since this during
312 /// monomorphization, we know that only concrete types are involved,
313 /// and hence we can be sure that all associated types will be
314 /// completely normalized away.
315 pub fn normalize_associated_type
<'tcx
,T
>(tcx
: &ty
::ctxt
<'tcx
>, value
: &T
) -> T
316 where T
: TypeFoldable
<'tcx
> + HasProjectionTypes
318 debug
!("normalize_associated_type(t={:?})", value
);
320 let value
= erase_regions(tcx
, value
);
322 if !value
.has_projection_types() {
326 // FIXME(#20304) -- cache
328 let infcx
= infer
::new_infer_ctxt(tcx
);
329 let typer
= NormalizingClosureTyper
::new(tcx
);
330 let mut selcx
= traits
::SelectionContext
::new(&infcx
, &typer
);
331 let cause
= traits
::ObligationCause
::dummy();
332 let traits
::Normalized { value: result, obligations }
=
333 traits
::normalize(&mut selcx
, cause
, &value
);
335 debug
!("normalize_associated_type: result={:?} obligations={:?}",
339 let mut fulfill_cx
= traits
::FulfillmentContext
::new(true);
340 for obligation
in obligations
{
341 fulfill_cx
.register_predicate_obligation(&infcx
, obligation
);
343 let result
= drain_fulfillment_cx_or_panic(DUMMY_SP
, &infcx
, &mut fulfill_cx
, &result
);