]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Auto merge of #35764 - eddyb:byegone, r=nikomatsakis
[rust.git] / src / librustc_trans / trans_item.rs
1 // Copyright 2016 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 //! Walks the crate looking for items/impl-items/trait-items that have
12 //! either a `rustc_symbol_name` or `rustc_item_path` attribute and
13 //! generates an error giving, respectively, the symbol name or
14 //! item-path. This is used for unit testing the code that generates
15 //! paths etc in all kinds of annoying scenarios.
16
17 use attributes;
18 use base;
19 use consts;
20 use context::{CrateContext, SharedCrateContext};
21 use declare;
22 use glue::DropGlueKind;
23 use llvm;
24 use monomorphize::{self, Instance};
25 use rustc::dep_graph::DepNode;
26 use rustc::hir;
27 use rustc::hir::def_id::DefId;
28 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
29 use rustc::ty::subst::Substs;
30 use rustc_const_eval::fatal_const_eval_err;
31 use std::hash::{Hash, Hasher};
32 use syntax::ast::{self, NodeId};
33 use syntax::attr;
34 use type_of;
35 use glue;
36 use abi::{Abi, FnType};
37 use back::symbol_names;
38
39 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
40 pub enum TransItem<'tcx> {
41     DropGlue(DropGlueKind<'tcx>),
42     Fn(Instance<'tcx>),
43     Static(NodeId)
44 }
45
46 impl<'tcx> Hash for TransItem<'tcx> {
47     fn hash<H: Hasher>(&self, s: &mut H) {
48         match *self {
49             TransItem::DropGlue(t) => {
50                 0u8.hash(s);
51                 t.hash(s);
52             },
53             TransItem::Fn(instance) => {
54                 1u8.hash(s);
55                 instance.def.hash(s);
56                 (instance.substs as *const _ as usize).hash(s);
57             }
58             TransItem::Static(node_id) => {
59                 2u8.hash(s);
60                 node_id.hash(s);
61             }
62         };
63     }
64 }
65
66 impl<'a, 'tcx> TransItem<'tcx> {
67
68     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
69         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
70                   self.to_string(ccx.tcx()),
71                   self.to_raw_string(),
72                   ccx.codegen_unit().name());
73
74         // (*) This code executes in the context of a dep-node for the
75         // entire CGU. In some cases, we introduce dep-nodes for
76         // particular items that we are translating (these nodes will
77         // have read edges coming into the CGU node). These smaller
78         // nodes are not needed for correctness -- we always
79         // invalidate an entire CGU at a time -- but they enable
80         // finer-grained testing, since you can write tests that check
81         // that the incoming edges to a particular fn are from a
82         // particular set.
83
84         match *self {
85             TransItem::Static(node_id) => {
86                 let def_id = ccx.tcx().map.local_def_id(node_id);
87                 let _task = ccx.tcx().dep_graph.in_task(DepNode::TransCrateItem(def_id)); // (*)
88                 let item = ccx.tcx().map.expect_item(node_id);
89                 if let hir::ItemStatic(_, m, _) = item.node {
90                     match consts::trans_static(&ccx, m, item.id, &item.attrs) {
91                         Ok(_) => { /* Cool, everything's alright. */ },
92                         Err(err) => {
93                             // FIXME: shouldn't this be a `span_err`?
94                             fatal_const_eval_err(
95                                 ccx.tcx(), &err, item.span, "static");
96                         }
97                     };
98                 } else {
99                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
100                 }
101             }
102             TransItem::Fn(instance) => {
103                 let _task = ccx.tcx().dep_graph.in_task(
104                     DepNode::TransCrateItem(instance.def)); // (*)
105
106                 base::trans_instance(&ccx, instance);
107             }
108             TransItem::DropGlue(dg) => {
109                 glue::implement_drop_glue(&ccx, dg);
110             }
111         }
112
113         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
114                self.to_string(ccx.tcx()),
115                self.to_raw_string(),
116                ccx.codegen_unit().name());
117     }
118
119     pub fn predefine(&self,
120                      ccx: &CrateContext<'a, 'tcx>,
121                      linkage: llvm::Linkage) {
122         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
123                self.to_string(ccx.tcx()),
124                self.to_raw_string(),
125                ccx.codegen_unit().name());
126
127         let symbol_name = ccx.symbol_map()
128                              .get_or_compute(ccx.shared(), *self);
129
130         debug!("symbol {}", &symbol_name);
131
132         match *self {
133             TransItem::Static(node_id) => {
134                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
135             }
136             TransItem::Fn(instance) => {
137                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
138             }
139             TransItem::DropGlue(dg) => {
140                 TransItem::predefine_drop_glue(ccx, dg, linkage, &symbol_name);
141             }
142         }
143
144         debug!("END PREDEFINING '{} ({})' in cgu {}",
145                self.to_string(ccx.tcx()),
146                self.to_raw_string(),
147                ccx.codegen_unit().name());
148     }
149
150     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
151                         node_id: ast::NodeId,
152                         linkage: llvm::Linkage,
153                         symbol_name: &str) {
154         let def_id = ccx.tcx().map.local_def_id(node_id);
155         let ty = ccx.tcx().lookup_item_type(def_id).ty;
156         let llty = type_of::type_of(ccx, ty);
157
158         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
159             ccx.sess().span_fatal(ccx.tcx().map.span(node_id),
160                 &format!("symbol `{}` is already defined", symbol_name))
161         });
162
163         unsafe { llvm::LLVMSetLinkage(g, linkage) };
164
165         let instance = Instance::mono(ccx.shared(), def_id);
166         ccx.instances().borrow_mut().insert(instance, g);
167         ccx.statics().borrow_mut().insert(g, def_id);
168     }
169
170     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
171                     instance: Instance<'tcx>,
172                     linkage: llvm::Linkage,
173                     symbol_name: &str) {
174         assert!(!instance.substs.types.needs_infer() &&
175                 !instance.substs.types.has_param_types());
176
177         let item_ty = ccx.tcx().lookup_item_type(instance.def).ty;
178         let item_ty = ccx.tcx().erase_regions(&item_ty);
179         let mono_ty = monomorphize::apply_param_substs(ccx.tcx(), instance.substs, &item_ty);
180
181         let attrs = ccx.tcx().get_attrs(instance.def);
182         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
183         unsafe { llvm::LLVMSetLinkage(lldecl, linkage) };
184         base::set_link_section(ccx, lldecl, &attrs);
185         if linkage == llvm::LinkOnceODRLinkage ||
186             linkage == llvm::WeakODRLinkage {
187             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
188         }
189
190         attributes::from_fn_attrs(ccx, &attrs, lldecl);
191
192         ccx.instances().borrow_mut().insert(instance, lldecl);
193     }
194
195     fn predefine_drop_glue(ccx: &CrateContext<'a, 'tcx>,
196                            dg: glue::DropGlueKind<'tcx>,
197                            linkage: llvm::Linkage,
198                            symbol_name: &str) {
199         let tcx = ccx.tcx();
200         assert_eq!(dg.ty(), glue::get_drop_glue_type(tcx, dg.ty()));
201         let t = dg.ty();
202
203         let sig = ty::FnSig {
204             inputs: vec![tcx.mk_mut_ptr(tcx.types.i8)],
205             output: tcx.mk_nil(),
206             variadic: false,
207         };
208
209         // Create a FnType for fn(*mut i8) and substitute the real type in
210         // later - that prevents FnType from splitting fat pointers up.
211         let mut fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
212         fn_ty.args[0].original_ty = type_of::type_of(ccx, t).ptr_to();
213         let llfnty = fn_ty.llvm_type(ccx);
214
215         assert!(declare::get_defined_value(ccx, symbol_name).is_none());
216         let llfn = declare::declare_cfn(ccx, symbol_name, llfnty);
217         unsafe { llvm::LLVMSetLinkage(llfn, linkage) };
218         if linkage == llvm::LinkOnceODRLinkage ||
219            linkage == llvm::WeakODRLinkage {
220             llvm::SetUniqueComdat(ccx.llmod(), llfn);
221         }
222         attributes::set_frame_pointer_elimination(ccx, llfn);
223         ccx.drop_glues().borrow_mut().insert(dg, (llfn, fn_ty));
224     }
225
226     pub fn compute_symbol_name(&self,
227                                scx: &SharedCrateContext<'a, 'tcx>) -> String {
228         match *self {
229             TransItem::Fn(instance) => instance.symbol_name(scx),
230             TransItem::Static(node_id) => {
231                 let def_id = scx.tcx().map.local_def_id(node_id);
232                 Instance::mono(scx, def_id).symbol_name(scx)
233             }
234             TransItem::DropGlue(dg) => {
235                 let prefix = match dg {
236                     DropGlueKind::Ty(_) => "drop",
237                     DropGlueKind::TyContents(_) => "drop_contents",
238                 };
239                 symbol_names::exported_name_from_type_and_prefix(scx, dg.ty(), prefix)
240             }
241         }
242     }
243
244     pub fn requests_inline(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
245         match *self {
246             TransItem::Fn(ref instance) => {
247                 !instance.substs.types.is_empty() || {
248                     let attributes = tcx.get_attrs(instance.def);
249                     attr::requests_inline(&attributes[..])
250                 }
251             }
252             TransItem::DropGlue(..) => true,
253             TransItem::Static(..)   => false,
254         }
255     }
256
257     pub fn is_from_extern_crate(&self) -> bool {
258         match *self {
259             TransItem::Fn(ref instance) => !instance.def.is_local(),
260             TransItem::DropGlue(..) |
261             TransItem::Static(..)   => false,
262         }
263     }
264
265     pub fn is_instantiated_only_on_demand(&self) -> bool {
266         match *self {
267             TransItem::Fn(ref instance) => !instance.def.is_local() ||
268                                            !instance.substs.types.is_empty(),
269             TransItem::DropGlue(..) => true,
270             TransItem::Static(..)   => false,
271         }
272     }
273
274     pub fn is_generic_fn(&self) -> bool {
275         match *self {
276             TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
277             TransItem::DropGlue(..) |
278             TransItem::Static(..)   => false,
279         }
280     }
281
282     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
283         let def_id = match *self {
284             TransItem::Fn(ref instance) => instance.def,
285             TransItem::Static(node_id) => tcx.map.local_def_id(node_id),
286             TransItem::DropGlue(..) => return None,
287         };
288
289         let attributes = tcx.get_attrs(def_id);
290         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
291             if let Some(linkage) = base::llvm_linkage_by_name(&name) {
292                 Some(linkage)
293             } else {
294                 let span = tcx.map.span_if_local(def_id);
295                 if let Some(span) = span {
296                     tcx.sess.span_fatal(span, "invalid linkage specified")
297                 } else {
298                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
299                 }
300             }
301         } else {
302             None
303         }
304     }
305
306     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
307         let hir_map = &tcx.map;
308
309         return match *self {
310             TransItem::DropGlue(dg) => {
311                 let mut s = String::with_capacity(32);
312                 match dg {
313                     DropGlueKind::Ty(_) => s.push_str("drop-glue "),
314                     DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
315                 };
316                 push_unique_type_name(tcx, dg.ty(), &mut s);
317                 s
318             }
319             TransItem::Fn(instance) => {
320                 to_string_internal(tcx, "fn ", instance)
321             },
322             TransItem::Static(node_id) => {
323                 let def_id = hir_map.local_def_id(node_id);
324                 let instance = Instance::new(def_id, Substs::empty(tcx));
325                 to_string_internal(tcx, "static ", instance)
326             },
327         };
328
329         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
330                                         prefix: &str,
331                                         instance: Instance<'tcx>)
332                                         -> String {
333             let mut result = String::with_capacity(32);
334             result.push_str(prefix);
335             push_instance_as_string(tcx, instance, &mut result);
336             result
337         }
338     }
339
340     pub fn to_raw_string(&self) -> String {
341         match *self {
342             TransItem::DropGlue(dg) => {
343                 let prefix = match dg {
344                     DropGlueKind::Ty(_) => "Ty",
345                     DropGlueKind::TyContents(_) => "TyContents",
346                 };
347                 format!("DropGlue({}: {})", prefix, dg.ty() as *const _ as usize)
348             }
349             TransItem::Fn(instance) => {
350                 format!("Fn({:?}, {})",
351                          instance.def,
352                          instance.substs as *const _ as usize)
353             }
354             TransItem::Static(id) => {
355                 format!("Static({:?})", id)
356             }
357         }
358     }
359 }
360
361
362 //=-----------------------------------------------------------------------------
363 // TransItem String Keys
364 //=-----------------------------------------------------------------------------
365
366 // The code below allows for producing a unique string key for a trans item.
367 // These keys are used by the handwritten auto-tests, so they need to be
368 // predictable and human-readable.
369 //
370 // Note: A lot of this could looks very similar to what's already in the
371 //       ppaux module. It would be good to refactor things so we only have one
372 //       parameterizable implementation for printing types.
373
374 /// Same as `unique_type_name()` but with the result pushed onto the given
375 /// `output` parameter.
376 pub fn push_unique_type_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
377                                        t: ty::Ty<'tcx>,
378                                        output: &mut String) {
379     match t.sty {
380         ty::TyBool              => output.push_str("bool"),
381         ty::TyChar              => output.push_str("char"),
382         ty::TyStr               => output.push_str("str"),
383         ty::TyNever             => output.push_str("!"),
384         ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
385         ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
386         ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
387         ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
388         ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
389         ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
390         ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
391         ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
392         ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
393         ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
394         ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
395         ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
396         ty::TyStruct(adt_def, substs) |
397         ty::TyEnum(adt_def, substs) => {
398             push_item_name(tcx, adt_def.did, output);
399             push_type_params(tcx, &substs.types, &[], output);
400         },
401         ty::TyTuple(component_types) => {
402             output.push('(');
403             for &component_type in component_types {
404                 push_unique_type_name(tcx, component_type, output);
405                 output.push_str(", ");
406             }
407             if !component_types.is_empty() {
408                 output.pop();
409                 output.pop();
410             }
411             output.push(')');
412         },
413         ty::TyBox(inner_type) => {
414             output.push_str("Box<");
415             push_unique_type_name(tcx, inner_type, output);
416             output.push('>');
417         },
418         ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
419             output.push('*');
420             match mutbl {
421                 hir::MutImmutable => output.push_str("const "),
422                 hir::MutMutable => output.push_str("mut "),
423             }
424
425             push_unique_type_name(tcx, inner_type, output);
426         },
427         ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
428             output.push('&');
429             if mutbl == hir::MutMutable {
430                 output.push_str("mut ");
431             }
432
433             push_unique_type_name(tcx, inner_type, output);
434         },
435         ty::TyArray(inner_type, len) => {
436             output.push('[');
437             push_unique_type_name(tcx, inner_type, output);
438             output.push_str(&format!("; {}", len));
439             output.push(']');
440         },
441         ty::TySlice(inner_type) => {
442             output.push('[');
443             push_unique_type_name(tcx, inner_type, output);
444             output.push(']');
445         },
446         ty::TyTrait(ref trait_data) => {
447             push_item_name(tcx, trait_data.principal.def_id(), output);
448             push_type_params(tcx,
449                              &trait_data.principal.skip_binder().substs.types,
450                              &trait_data.projection_bounds,
451                              output);
452         },
453         ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
454         ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
455             if unsafety == hir::Unsafety::Unsafe {
456                 output.push_str("unsafe ");
457             }
458
459             if abi != ::abi::Abi::Rust {
460                 output.push_str("extern \"");
461                 output.push_str(abi.name());
462                 output.push_str("\" ");
463             }
464
465             output.push_str("fn(");
466
467             let sig = tcx.erase_late_bound_regions(sig);
468             if !sig.inputs.is_empty() {
469                 for &parameter_type in &sig.inputs {
470                     push_unique_type_name(tcx, parameter_type, output);
471                     output.push_str(", ");
472                 }
473                 output.pop();
474                 output.pop();
475             }
476
477             if sig.variadic {
478                 if !sig.inputs.is_empty() {
479                     output.push_str(", ...");
480                 } else {
481                     output.push_str("...");
482                 }
483             }
484
485             output.push(')');
486
487             if !sig.output.is_nil() {
488                 output.push_str(" -> ");
489                 push_unique_type_name(tcx, sig.output, output);
490             }
491         },
492         ty::TyClosure(def_id, ref closure_substs) => {
493             push_item_name(tcx, def_id, output);
494             output.push_str("{");
495             output.push_str(&format!("{}:{}", def_id.krate, def_id.index.as_usize()));
496             output.push_str("}");
497             push_type_params(tcx, &closure_substs.func_substs.types, &[], output);
498         }
499         ty::TyError |
500         ty::TyInfer(_) |
501         ty::TyProjection(..) |
502         ty::TyParam(_) |
503         ty::TyAnon(..) => {
504             bug!("debuginfo: Trying to create type name for \
505                   unexpected type: {:?}", t);
506         }
507     }
508 }
509
510 fn push_item_name(tcx: TyCtxt,
511                   def_id: DefId,
512                   output: &mut String) {
513     let def_path = tcx.def_path(def_id);
514
515     // some_crate::
516     output.push_str(&tcx.crate_name(def_path.krate));
517     output.push_str("::");
518
519     // foo::bar::ItemName::
520     for part in tcx.def_path(def_id).data {
521         output.push_str(&format!("{}[{}]::",
522                         part.data.as_interned_str(),
523                         part.disambiguator));
524     }
525
526     // remove final "::"
527     output.pop();
528     output.pop();
529 }
530
531 fn push_type_params<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
532                               types: &[Ty<'tcx>],
533                               projections: &[ty::PolyExistentialProjection<'tcx>],
534                               output: &mut String) {
535     if types.is_empty() && projections.is_empty() {
536         return;
537     }
538
539     output.push('<');
540
541     for &type_parameter in types {
542         push_unique_type_name(tcx, type_parameter, output);
543         output.push_str(", ");
544     }
545
546     for projection in projections {
547         let projection = projection.skip_binder();
548         let name = &projection.item_name.as_str();
549         output.push_str(name);
550         output.push_str("=");
551         push_unique_type_name(tcx, projection.ty, output);
552         output.push_str(", ");
553     }
554
555     output.pop();
556     output.pop();
557
558     output.push('>');
559 }
560
561 fn push_instance_as_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
562                                      instance: Instance<'tcx>,
563                                      output: &mut String) {
564     push_item_name(tcx, instance.def, output);
565     push_type_params(tcx, &instance.substs.types, &[], output);
566 }
567
568 pub fn def_id_to_string(tcx: TyCtxt, def_id: DefId) -> String {
569     let mut output = String::new();
570     push_item_name(tcx, def_id, &mut output);
571     output
572 }
573
574 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
575                                 ty: ty::Ty<'tcx>)
576                                 -> String {
577     let mut output = String::new();
578     push_unique_type_name(tcx, ty, &mut output);
579     output
580 }