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, HasTypeFlags, 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
.needs_infer() && !psubsts
.types
.has_param_types());
52 let _icx
= push_ctxt("monomorphic_fn");
54 let hash_id
= MonoId
{
56 params
: &psubsts
.types
59 let item_ty
= ccx
.tcx().lookup_item_type(fn_id
).ty
;
61 debug
!("monomorphic_fn about to subst into {:?}", item_ty
);
62 let mono_ty
= apply_param_substs(ccx
.tcx(), psubsts
, &item_ty
);
63 debug
!("mono_ty = {:?} (post-substitution)", mono_ty
);
65 match ccx
.monomorphized().borrow().get(&hash_id
) {
67 debug
!("leaving monomorphic fn {}",
68 ccx
.tcx().item_path_str(fn_id
));
69 return (val
, mono_ty
, false);
74 debug
!("monomorphic_fn(\
83 let map_node
= session
::expect(
85 ccx
.tcx().map
.find(fn_id
.node
),
87 format
!("while monomorphizing {:?}, couldn't find it in \
88 the item map (may have attempted to monomorphize \
89 an item defined in a different crate?)",
93 if let ast_map
::NodeForeignItem(_
) = map_node
{
94 if ccx
.tcx().map
.get_foreign_abi(fn_id
.node
) != abi
::RustIntrinsic
{
95 // Foreign externs don't have to be monomorphized.
96 return (get_item_val(ccx
, fn_id
.node
), mono_ty
, true);
100 ccx
.stats().n_monos
.set(ccx
.stats().n_monos
.get() + 1);
104 let mut monomorphizing
= ccx
.monomorphizing().borrow_mut();
105 depth
= match monomorphizing
.get(&fn_id
) {
106 Some(&d
) => d
, None
=> 0
109 // Random cut-off -- code that needs to instantiate the same function
110 // recursively more than thirty times can probably safely be assumed
111 // to be causing an infinite expansion.
112 if depth
> ccx
.sess().recursion_limit
.get() {
113 ccx
.sess().span_fatal(ccx
.tcx().map
.span(fn_id
.node
),
114 "reached the recursion limit during monomorphization");
117 monomorphizing
.insert(fn_id
, depth
+ 1);
122 let mut state
= SipHasher
::new();
123 hash_id
.hash(&mut state
);
124 mono_ty
.hash(&mut state
);
126 hash
= format
!("h{}", state
.finish());
127 ccx
.tcx().map
.with_path(fn_id
.node
, |path
| {
128 exported_name(path
, &hash
[..])
132 debug
!("monomorphize_fn mangled to {}", s
);
134 // This shouldn't need to option dance.
135 let mut hash_id
= Some(hash_id
);
136 let mut mk_lldecl
= |abi
: abi
::Abi
| {
137 let lldecl
= if abi
!= abi
::Rust
{
138 foreign
::decl_rust_fn_with_foreign_abi(ccx
, mono_ty
, &s
[..])
140 // FIXME(nagisa): perhaps needs a more fine grained selection? See
141 // setup_lldecl below.
142 declare
::define_internal_rust_fn(ccx
, &s
, mono_ty
)
145 ccx
.monomorphized().borrow_mut().insert(hash_id
.take().unwrap(), lldecl
);
148 let setup_lldecl
= |lldecl
, attrs
: &[ast
::Attribute
]| {
149 base
::update_linkage(ccx
, lldecl
, None
, base
::OriginalTranslation
);
150 attributes
::from_fn_attrs(ccx
, attrs
, lldecl
);
152 let is_first
= !ccx
.available_monomorphizations().borrow().contains(&s
);
154 ccx
.available_monomorphizations().borrow_mut().insert(s
.clone());
157 let trans_everywhere
= attr
::requests_inline(attrs
);
158 if trans_everywhere
&& !is_first
{
159 llvm
::SetLinkage(lldecl
, llvm
::AvailableExternallyLinkage
);
162 // If `true`, then `lldecl` should be given a function body.
163 // Otherwise, it should be left as a declaration of an external
164 // function, with no definition in the current compilation unit.
165 trans_everywhere
|| is_first
168 let lldecl
= match map_node
{
169 ast_map
::NodeItem(i
) => {
172 node
: ast
::ItemFn(ref decl
, _
, _
, abi
, _
, ref body
),
175 let d
= mk_lldecl(abi
);
176 let needs_body
= setup_lldecl(d
, &i
.attrs
);
178 if abi
!= abi
::Rust
{
179 foreign
::trans_rust_fn_with_foreign_abi(
180 ccx
, &**decl
, &**body
, &[], d
, psubsts
, fn_id
.node
,
183 trans_fn(ccx
, &**decl
, &**body
, d
, psubsts
, fn_id
.node
, &[]);
190 ccx
.sess().bug("Can't monomorphize this kind of item")
194 ast_map
::NodeVariant(v
) => {
195 let parent
= ccx
.tcx().map
.get_parent(fn_id
.node
);
196 let tvs
= ccx
.tcx().enum_variants(local_def(parent
));
197 let this_tv
= tvs
.iter().find(|tv
| { tv.id.node == fn_id.node}
).unwrap();
198 let d
= mk_lldecl(abi
::Rust
);
199 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
201 ast
::TupleVariantKind(ref args
) => {
202 trans_enum_variant(ccx
,
210 ast
::StructVariantKind(_
) =>
211 ccx
.sess().bug("can't monomorphize struct variants"),
215 ast_map
::NodeImplItem(impl_item
) => {
216 match impl_item
.node
{
217 ast
::MethodImplItem(ref sig
, ref body
) => {
218 let d
= mk_lldecl(abi
::Rust
);
219 let needs_body
= setup_lldecl(d
, &impl_item
.attrs
);
232 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
237 ast_map
::NodeTraitItem(trait_item
) => {
238 match trait_item
.node
{
239 ast
::MethodTraitItem(ref sig
, Some(ref body
)) => {
240 let d
= mk_lldecl(abi
::Rust
);
241 let needs_body
= setup_lldecl(d
, &trait_item
.attrs
);
243 trans_fn(ccx
, &sig
.decl
, body
, d
,
244 psubsts
, trait_item
.id
, &[]);
249 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
254 ast_map
::NodeStructCtor(struct_def
) => {
255 let d
= mk_lldecl(abi
::Rust
);
256 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
257 base
::trans_tuple_struct(ccx
,
259 struct_def
.ctor_id
.expect("ast-mapped tuple struct \
260 didn't have a ctor id"),
266 // Ugh -- but this ensures any new variants won't be forgotten
267 ast_map
::NodeForeignItem(..) |
268 ast_map
::NodeLifetime(..) |
269 ast_map
::NodeTyParam(..) |
270 ast_map
::NodeExpr(..) |
271 ast_map
::NodeStmt(..) |
272 ast_map
::NodeArg(..) |
273 ast_map
::NodeBlock(..) |
274 ast_map
::NodePat(..) |
275 ast_map
::NodeLocal(..) => {
276 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
281 ccx
.monomorphizing().borrow_mut().insert(fn_id
, depth
);
283 debug
!("leaving monomorphic fn {}", ccx
.tcx().item_path_str(fn_id
));
284 (lldecl
, mono_ty
, true)
287 #[derive(PartialEq, Eq, Hash, Debug)]
288 pub struct MonoId
<'tcx
> {
290 pub params
: &'tcx subst
::VecPerParamSpace
<Ty
<'tcx
>>
293 /// Monomorphizes a type from the AST by first applying the in-scope
294 /// substitutions and then normalizing any associated types.
295 pub fn apply_param_substs
<'tcx
,T
>(tcx
: &ty
::ctxt
<'tcx
>,
296 param_substs
: &Substs
<'tcx
>,
299 where T
: TypeFoldable
<'tcx
> + HasTypeFlags
301 let substituted
= value
.subst(tcx
, param_substs
);
302 normalize_associated_type(tcx
, &substituted
)
305 /// Removes associated types, if any. Since this during
306 /// monomorphization, we know that only concrete types are involved,
307 /// and hence we can be sure that all associated types will be
308 /// completely normalized away.
309 pub fn normalize_associated_type
<'tcx
,T
>(tcx
: &ty
::ctxt
<'tcx
>, value
: &T
) -> T
310 where T
: TypeFoldable
<'tcx
> + HasTypeFlags
312 debug
!("normalize_associated_type(t={:?})", value
);
314 let value
= erase_regions(tcx
, value
);
316 if !value
.has_projection_types() {
320 // FIXME(#20304) -- cache
321 let infcx
= infer
::normalizing_infer_ctxt(tcx
, &tcx
.tables
);
322 let mut selcx
= traits
::SelectionContext
::new(&infcx
);
323 let cause
= traits
::ObligationCause
::dummy();
324 let traits
::Normalized { value: result, obligations }
=
325 traits
::normalize(&mut selcx
, cause
, &value
);
327 debug
!("normalize_associated_type: result={:?} obligations={:?}",
331 let mut fulfill_cx
= infcx
.fulfillment_cx
.borrow_mut();
333 for obligation
in obligations
{
334 fulfill_cx
.register_predicate_obligation(&infcx
, obligation
);
336 let result
= drain_fulfillment_cx_or_panic(DUMMY_SP
, &infcx
, &mut fulfill_cx
, &result
);