]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/monomorphize.rs
71aacfdfe58acc90a91872e37a732572cec0884c
[rust.git] / src / librustc_trans / monomorphize.rs
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.
4 //
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.
10
11 use llvm::ValueRef;
12 use llvm;
13 use rustc::hir::def_id::DefId;
14 use rustc::infer::TransNormalize;
15 use rustc::ty::subst;
16 use rustc::ty::subst::{Subst, Substs};
17 use rustc::ty::{self, Ty, TypeFoldable, TyCtxt};
18 use attributes;
19 use base::{push_ctxt};
20 use base;
21 use common::*;
22 use declare;
23 use Disr;
24 use rustc::hir::map as hir_map;
25 use rustc::util::ppaux;
26
27 use rustc::hir;
28
29 use errors;
30
31 use std::fmt;
32 use trans_item::TransItem;
33
34 pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
35                                 fn_id: DefId,
36                                 psubsts: &'tcx subst::Substs<'tcx>)
37                                 -> (ValueRef, Ty<'tcx>) {
38     debug!("monomorphic_fn(fn_id={:?}, real_substs={:?})", fn_id, psubsts);
39     assert!(!psubsts.types.needs_infer() && !psubsts.types.has_param_types());
40
41     let _icx = push_ctxt("monomorphic_fn");
42
43     let instance = Instance::new(fn_id, psubsts);
44
45     let item_ty = ccx.tcx().lookup_item_type(fn_id).ty;
46
47     debug!("monomorphic_fn about to subst into {:?}", item_ty);
48     let mono_ty = apply_param_substs(ccx.tcx(), psubsts, &item_ty);
49     debug!("mono_ty = {:?} (post-substitution)", mono_ty);
50
51     if let Some(&val) = ccx.instances().borrow().get(&instance) {
52         debug!("leaving monomorphic fn {:?}", instance);
53         return (val, mono_ty);
54     } else {
55         assert!(!ccx.codegen_unit().items.contains_key(&TransItem::Fn(instance)));
56     }
57
58     debug!("monomorphic_fn({:?})", instance);
59
60     ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
61
62     let depth;
63     {
64         let mut monomorphizing = ccx.monomorphizing().borrow_mut();
65         depth = match monomorphizing.get(&fn_id) {
66             Some(&d) => d, None => 0
67         };
68
69         debug!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id, depth+1);
70
71         // Random cut-off -- code that needs to instantiate the same function
72         // recursively more than thirty times can probably safely be assumed
73         // to be causing an infinite expansion.
74         if depth > ccx.sess().recursion_limit.get() {
75             let error = format!("reached the recursion limit while instantiating `{}`",
76                                 instance);
77             if let Some(id) = ccx.tcx().map.as_local_node_id(fn_id) {
78                 ccx.sess().span_fatal(ccx.tcx().map.span(id), &error);
79             } else {
80                 ccx.sess().fatal(&error);
81             }
82         }
83
84         monomorphizing.insert(fn_id, depth + 1);
85     }
86
87     let symbol = ccx.symbol_map().get_or_compute(ccx.shared(),
88                                                  TransItem::Fn(instance));
89
90     debug!("monomorphize_fn mangled to {}", &symbol);
91     assert!(declare::get_defined_value(ccx, &symbol).is_none());
92
93     // FIXME(nagisa): perhaps needs a more fine grained selection?
94     let lldecl = declare::define_internal_fn(ccx, &symbol, mono_ty);
95     // FIXME(eddyb) Doubt all extern fn should allow unwinding.
96     attributes::unwind(lldecl, true);
97
98     ccx.instances().borrow_mut().insert(instance, lldecl);
99
100     // we can only monomorphize things in this crate (or inlined into it)
101     let fn_node_id = ccx.tcx().map.as_local_node_id(fn_id).unwrap();
102     let map_node = errors::expect(
103         ccx.sess().diagnostic(),
104         ccx.tcx().map.find(fn_node_id),
105         || {
106             format!("while instantiating `{}`, couldn't find it in \
107                      the item map (may have attempted to monomorphize \
108                      an item defined in a different crate?)",
109                     instance)
110         });
111     match map_node {
112         hir_map::NodeItem(&hir::Item {
113             ref attrs,
114             node: hir::ItemFn(..), ..
115         }) |
116         hir_map::NodeImplItem(&hir::ImplItem {
117             ref attrs, node: hir::ImplItemKind::Method(
118                 hir::MethodSig { .. }, _), ..
119         }) |
120         hir_map::NodeTraitItem(&hir::TraitItem {
121             ref attrs, node: hir::MethodTraitItem(
122                 hir::MethodSig { .. }, Some(_)), ..
123         }) => {
124             let trans_item = TransItem::Fn(instance);
125
126             if ccx.shared().translation_items().borrow().contains_key(&trans_item) {
127                 attributes::from_fn_attrs(ccx, attrs, lldecl);
128                 llvm::SetLinkage(lldecl, llvm::ExternalLinkage);
129             } else {
130                 // FIXME: #34151
131                 // Normally, getting here would indicate a bug in trans::collector,
132                 // since it seems to have missed a translation item. When we are
133                 // translating with non-MIR based trans, however, the results of
134                 // the collector are not entirely reliable since it bases its
135                 // analysis on MIR. Thus, we'll instantiate the missing function
136                 // privately in this codegen unit, so that things keep working.
137                 ccx.stats().n_fallback_instantiations.set(ccx.stats()
138                                                              .n_fallback_instantiations
139                                                              .get() + 1);
140                 trans_item.predefine(ccx, llvm::PrivateLinkage);
141                 trans_item.define(ccx);
142             }
143         }
144
145         hir_map::NodeVariant(_) | hir_map::NodeStructCtor(_) => {
146             let disr = match map_node {
147                 hir_map::NodeVariant(_) => {
148                     Disr::from(inlined_variant_def(ccx, fn_node_id).disr_val)
149                 }
150                 hir_map::NodeStructCtor(_) => Disr(0),
151                 _ => bug!()
152             };
153             attributes::inline(lldecl, attributes::InlineAttr::Hint);
154             attributes::set_frame_pointer_elimination(ccx, lldecl);
155             base::trans_ctor_shim(ccx, fn_node_id, disr, psubsts, lldecl);
156         }
157
158         _ => bug!("can't monomorphize a {:?}", map_node)
159     };
160
161     ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
162
163     debug!("leaving monomorphic fn {}", ccx.tcx().item_path_str(fn_id));
164     (lldecl, mono_ty)
165 }
166
167 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
168 pub struct Instance<'tcx> {
169     pub def: DefId,
170     pub substs: &'tcx Substs<'tcx>,
171 }
172
173 impl<'tcx> fmt::Display for Instance<'tcx> {
174     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175         ppaux::parameterized(f, &self.substs, self.def, ppaux::Ns::Value, &[], |_| None)
176     }
177 }
178
179 impl<'tcx> Instance<'tcx> {
180     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
181                -> Instance<'tcx> {
182         assert!(substs.regions.iter().all(|&r| r == ty::ReErased));
183         Instance { def: def_id, substs: substs }
184     }
185     pub fn mono<'a>(scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId) -> Instance<'tcx> {
186         Instance::new(def_id, scx.empty_substs_for_def_id(def_id))
187     }
188 }
189
190 /// Monomorphizes a type from the AST by first applying the in-scope
191 /// substitutions and then normalizing any associated types.
192 pub fn apply_param_substs<'a, 'tcx, T>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
193                                        param_substs: &Substs<'tcx>,
194                                        value: &T)
195                                        -> T
196     where T: TransNormalize<'tcx>
197 {
198     let substituted = value.subst(tcx, param_substs);
199     tcx.normalize_associated_type(&substituted)
200 }
201
202
203 /// Returns the normalized type of a struct field
204 pub fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
205                           param_substs: &Substs<'tcx>,
206                           f: ty::FieldDef<'tcx>)
207                           -> Ty<'tcx>
208 {
209     tcx.normalize_associated_type(&f.ty(tcx, param_substs))
210 }