1 // Copyright 2012-2015 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 // See doc.rs for documentation.
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
17 use self::utils::{DIB, span_start, assert_type_for_node_id, contains_nodebug_attribute,
18 create_DIArray, is_node_local_to_unit};
19 use self::namespace::{namespace_for_item, NamespaceTreeNode};
20 use self::type_names::compute_debuginfo_type_name;
21 use self::metadata::{type_metadata, diverging_type_metadata};
22 use self::metadata::{file_metadata, scope_metadata, TypeMap, compile_unit_metadata};
23 use self::source_loc::InternalDebugLocation;
26 use llvm::{ModuleRef, ContextRef, ValueRef};
27 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray,
28 DIDescriptor, FlagPrototyped};
29 use middle::def_id::DefId;
30 use middle::infer::normalize_associated_type;
31 use middle::subst::{self, Substs};
34 use rustc_front::attr::IntType;
36 use trans::common::{NodeIdAndSpan, CrateContext, FunctionContext, Block};
38 use trans::{monomorphize, type_of};
39 use middle::ty::{self, Ty};
40 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
41 use util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
42 use rustc::front::map as hir_map;
45 use std::cell::{Cell, RefCell};
46 use std::ffi::CString;
50 use syntax::codemap::{Span, Pos};
51 use syntax::{abi, ast, codemap};
52 use syntax::parse::token::{self, special_idents};
62 pub use self::source_loc::set_source_location;
63 pub use self::source_loc::clear_source_location;
64 pub use self::source_loc::start_emitting_source_locations;
65 pub use self::source_loc::get_cleanup_debug_loc_for_ast_node;
66 pub use self::source_loc::with_source_location_override;
67 pub use self::metadata::create_match_binding_metadata;
68 pub use self::metadata::create_argument_metadata;
69 pub use self::metadata::create_captured_var_metadata;
70 pub use self::metadata::create_global_var_metadata;
71 pub use self::metadata::create_local_var_metadata;
73 #[allow(non_upper_case_globals)]
74 const DW_TAG_auto_variable: c_uint = 0x100;
75 #[allow(non_upper_case_globals)]
76 const DW_TAG_arg_variable: c_uint = 0x101;
78 /// A context object for maintaining all state needed by the debuginfo module.
79 pub struct CrateDebugContext<'tcx> {
80 llcontext: ContextRef,
81 builder: DIBuilderRef,
82 current_debug_location: Cell<InternalDebugLocation>,
83 created_files: RefCell<FnvHashMap<String, DIFile>>,
84 created_enum_disr_types: RefCell<FnvHashMap<(DefId, IntType), DIType>>,
86 type_map: RefCell<TypeMap<'tcx>>,
87 namespace_map: RefCell<FnvHashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
89 // This collection is used to assert that composite types (structs, enums,
90 // ...) have their members only set once:
91 composite_types_completed: RefCell<FnvHashSet<DIType>>,
94 impl<'tcx> CrateDebugContext<'tcx> {
95 pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
96 debug!("CrateDebugContext::new");
97 let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
98 // DIBuilder inherits context from the module, so we'd better use the same one
99 let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
100 return CrateDebugContext {
101 llcontext: llcontext,
103 current_debug_location: Cell::new(InternalDebugLocation::UnknownLocation),
104 created_files: RefCell::new(FnvHashMap()),
105 created_enum_disr_types: RefCell::new(FnvHashMap()),
106 type_map: RefCell::new(TypeMap::new()),
107 namespace_map: RefCell::new(FnvHashMap()),
108 composite_types_completed: RefCell::new(FnvHashSet()),
113 pub enum FunctionDebugContext {
114 RegularContext(Box<FunctionDebugContextData>),
116 FunctionWithoutDebugInfo,
119 impl FunctionDebugContext {
120 fn get_ref<'a>(&'a self,
123 -> &'a FunctionDebugContextData {
125 FunctionDebugContext::RegularContext(box ref data) => data,
126 FunctionDebugContext::DebugInfoDisabled => {
127 cx.sess().span_bug(span,
128 FunctionDebugContext::debuginfo_disabled_message());
130 FunctionDebugContext::FunctionWithoutDebugInfo => {
131 cx.sess().span_bug(span,
132 FunctionDebugContext::should_be_ignored_message());
137 fn debuginfo_disabled_message() -> &'static str {
138 "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
141 fn should_be_ignored_message() -> &'static str {
142 "debuginfo: Error trying to access FunctionDebugContext for function that should be \
143 ignored by debug info!"
147 struct FunctionDebugContextData {
148 scope_map: RefCell<NodeMap<DIScope>>,
149 fn_metadata: DISubprogram,
150 argument_counter: Cell<usize>,
151 source_locations_enabled: Cell<bool>,
152 source_location_override: Cell<bool>,
155 pub enum VariableAccess<'a> {
156 // The llptr given is an alloca containing the variable's value
157 DirectVariable { alloca: ValueRef },
158 // The llptr given is an alloca containing the start of some pointer chain
159 // leading to the variable's content.
160 IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
163 pub enum VariableKind {
164 ArgumentVariable(usize /*index*/),
169 /// Create any deferred debug metadata nodes
170 pub fn finalize(cx: &CrateContext) {
171 if cx.dbg_cx().is_none() {
176 let _ = compile_unit_metadata(cx);
178 if gdb::needs_gdb_debug_scripts_section(cx) {
179 // Add a .debug_gdb_scripts section to this compile-unit. This will
180 // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
181 // which activates the Rust pretty printers for binary this section is
183 gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
187 llvm::LLVMDIBuilderFinalize(DIB(cx));
188 llvm::LLVMDIBuilderDispose(DIB(cx));
189 // Debuginfo generation in LLVM by default uses a higher
190 // version of dwarf than OS X currently understands. We can
191 // instruct LLVM to emit an older version of dwarf, however,
192 // for OS X to understand. For more info see #11352
193 // This can be overridden using --llvm-opts -dwarf-version,N.
194 // Android has the same issue (#22398)
195 if cx.sess().target.target.options.is_like_osx ||
196 cx.sess().target.target.options.is_like_android {
197 llvm::LLVMRustAddModuleFlag(cx.llmod(),
198 "Dwarf Version\0".as_ptr() as *const _,
202 // Prevent bitcode readers from deleting the debug info.
203 let ptr = "Debug Info Version\0".as_ptr();
204 llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
205 llvm::LLVMRustDebugMetadataVersion());
209 /// Creates the function-specific debug context.
211 /// Returns the FunctionDebugContext for the function which holds state needed
212 /// for debug info creation. The function may also return another variant of the
213 /// FunctionDebugContext enum which indicates why no debuginfo should be created
214 /// for the function.
215 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
216 fn_ast_id: ast::NodeId,
217 param_substs: &Substs<'tcx>,
218 llfn: ValueRef) -> FunctionDebugContext {
219 if cx.sess().opts.debuginfo == NoDebugInfo {
220 return FunctionDebugContext::DebugInfoDisabled;
223 // Clear the debug location so we don't assign them in the function prelude.
224 // Do this here already, in case we do an early exit from this function.
225 source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
227 if fn_ast_id == ast::DUMMY_NODE_ID {
228 // This is a function not linked to any source location, so don't
229 // generate debuginfo for it.
230 return FunctionDebugContext::FunctionWithoutDebugInfo;
233 let empty_generics = rustc_front::util::empty_generics();
235 let fnitem = cx.tcx().map.get(fn_ast_id);
237 let (name, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
238 hir_map::NodeItem(ref item) => {
239 if contains_nodebug_attribute(&item.attrs) {
240 return FunctionDebugContext::FunctionWithoutDebugInfo;
244 hir::ItemFn(ref fn_decl, _, _, _, ref generics, ref top_level_block) => {
245 (item.ident.name, fn_decl, generics, top_level_block, item.span, true)
248 cx.sess().span_bug(item.span,
249 "create_function_debug_context: item bound to non-function");
253 hir_map::NodeImplItem(impl_item) => {
254 match impl_item.node {
255 hir::MethodImplItem(ref sig, ref body) => {
256 if contains_nodebug_attribute(&impl_item.attrs) {
257 return FunctionDebugContext::FunctionWithoutDebugInfo;
260 (impl_item.ident.name,
268 cx.sess().span_bug(impl_item.span,
269 "create_function_debug_context() \
270 called on non-method impl item?!")
274 hir_map::NodeExpr(ref expr) => {
276 hir::ExprClosure(_, ref fn_decl, ref top_level_block) => {
277 let name = format!("fn{}", token::gensym("fn"));
278 let name = token::intern(&name[..]);
280 // This is not quite right. It should actually inherit
281 // the generics of the enclosing function.
285 // Don't try to lookup the item path:
288 _ => cx.sess().span_bug(expr.span,
289 "create_function_debug_context: expected an expr_fn_block here")
292 hir_map::NodeTraitItem(trait_item) => {
293 match trait_item.node {
294 hir::MethodTraitItem(ref sig, Some(ref body)) => {
295 if contains_nodebug_attribute(&trait_item.attrs) {
296 return FunctionDebugContext::FunctionWithoutDebugInfo;
299 (trait_item.ident.name,
308 .bug(&format!("create_function_debug_context: \
309 unexpected sort of node: {:?}",
314 hir_map::NodeForeignItem(..) |
315 hir_map::NodeVariant(..) |
316 hir_map::NodeStructCtor(..) => {
317 return FunctionDebugContext::FunctionWithoutDebugInfo;
319 _ => cx.sess().bug(&format!("create_function_debug_context: \
320 unexpected sort of node: {:?}",
324 // This can be the case for functions inlined from another crate
325 if span == codemap::DUMMY_SP {
326 return FunctionDebugContext::FunctionWithoutDebugInfo;
329 let loc = span_start(cx, span);
330 let file_metadata = file_metadata(cx, &loc.file.name);
332 let function_type_metadata = unsafe {
333 let fn_signature = get_function_signature(cx,
337 llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
340 // Get_template_parameters() will append a `<...>` clause to the function
341 // name if necessary.
342 let mut function_name = name.to_string();
343 let template_parameters = get_template_parameters(cx,
349 // There is no hir_map::Path for hir::ExprClosure-type functions. For now,
350 // just don't put them into a namespace. In the future this could be improved
351 // somehow (storing a path in the hir_map, or construct a path using the
352 // enclosing function).
353 let (linkage_name, containing_scope) = if has_path {
354 let namespace_node = namespace_for_item(cx, DefId::local(fn_ast_id));
355 let linkage_name = namespace_node.mangled_name_of_contained_item(
357 let containing_scope = namespace_node.scope;
358 (linkage_name, containing_scope)
360 (function_name.clone(), file_metadata)
363 // Clang sets this parameter to the opening brace of the function's block,
364 // so let's do this too.
365 let scope_line = span_start(cx, top_level_block.span).line;
367 let is_local_to_unit = is_node_local_to_unit(cx, fn_ast_id);
369 let function_name = CString::new(function_name).unwrap();
370 let linkage_name = CString::new(linkage_name).unwrap();
371 let fn_metadata = unsafe {
372 llvm::LLVMDIBuilderCreateFunction(
375 function_name.as_ptr(),
376 linkage_name.as_ptr(),
379 function_type_metadata,
382 scope_line as c_uint,
383 FlagPrototyped as c_uint,
384 cx.sess().opts.optimize != config::No,
390 let scope_map = create_scope_map::create_scope_map(cx,
396 // Initialize fn debug context (including scope map and namespace map)
397 let fn_debug_context = box FunctionDebugContextData {
398 scope_map: RefCell::new(scope_map),
399 fn_metadata: fn_metadata,
400 argument_counter: Cell::new(1),
401 source_locations_enabled: Cell::new(false),
402 source_location_override: Cell::new(false),
407 return FunctionDebugContext::RegularContext(fn_debug_context);
409 fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
410 fn_ast_id: ast::NodeId,
411 param_substs: &Substs<'tcx>,
412 error_reporting_span: Span) -> DIArray {
413 if cx.sess().opts.debuginfo == LimitedDebugInfo {
414 return create_DIArray(DIB(cx), &[]);
417 // Return type -- llvm::DIBuilder wants this at index 0
418 assert_type_for_node_id(cx, fn_ast_id, error_reporting_span);
419 let fn_type = cx.tcx().node_id_to_type(fn_ast_id);
421 let (sig, abi) = match fn_type.sty {
422 ty::TyBareFn(_, ref barefnty) => {
423 (cx.tcx().erase_late_bound_regions(&barefnty.sig), barefnty.abi)
425 ty::TyClosure(def_id, ref substs) => {
426 let closure_type = cx.tcx().closure_type(def_id, substs);
427 (cx.tcx().erase_late_bound_regions(&closure_type.sig), closure_type.abi)
430 _ => cx.sess().bug("get_function_metdata: Expected a function type!")
432 let sig = monomorphize::apply_param_substs(cx.tcx(), param_substs, &sig);
434 let mut signature = Vec::with_capacity(sig.inputs.len() + 1);
436 // Return type -- llvm::DIBuilder wants this at index 0
437 signature.push(match sig.output {
438 ty::FnConverging(ret_ty) => match ret_ty.sty {
439 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
440 _ => type_metadata(cx, ret_ty, codemap::DUMMY_SP)
442 ty::FnDiverging => diverging_type_metadata(cx)
445 let inputs = &if abi == abi::RustCall {
446 type_of::untuple_arguments(cx, &sig.inputs)
452 for &argument_type in inputs {
453 signature.push(type_metadata(cx, argument_type, codemap::DUMMY_SP));
456 return create_DIArray(DIB(cx), &signature[..]);
459 fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
460 generics: &hir::Generics,
461 param_substs: &Substs<'tcx>,
462 file_metadata: DIFile,
463 name_to_append_suffix_to: &mut String)
466 let self_type = param_substs.self_ty();
467 let self_type = normalize_associated_type(cx.tcx(), &self_type);
469 // Only true for static default methods:
470 let has_self_type = self_type.is_some();
472 if !generics.is_type_parameterized() && !has_self_type {
473 return create_DIArray(DIB(cx), &[]);
476 name_to_append_suffix_to.push('<');
478 // The list to be filled with template parameters:
479 let mut template_params: Vec<DIDescriptor> =
480 Vec::with_capacity(generics.ty_params.len() + 1);
484 let actual_self_type = self_type.unwrap();
485 // Add self type name to <...> clause of function name
486 let actual_self_type_name = compute_debuginfo_type_name(
491 name_to_append_suffix_to.push_str(&actual_self_type_name[..]);
493 if generics.is_type_parameterized() {
494 name_to_append_suffix_to.push_str(",");
497 // Only create type information if full debuginfo is enabled
498 if cx.sess().opts.debuginfo == FullDebugInfo {
499 let actual_self_type_metadata = type_metadata(cx,
503 let name = special_idents::type_self.name.as_str();
505 let name = CString::new(name.as_bytes()).unwrap();
506 let param_metadata = unsafe {
507 llvm::LLVMDIBuilderCreateTemplateTypeParameter(
511 actual_self_type_metadata,
517 template_params.push(param_metadata);
521 // Handle other generic parameters
522 let actual_types = param_substs.types.get_slice(subst::FnSpace);
523 for (index, &hir::TyParam{ ident, .. }) in generics.ty_params.iter().enumerate() {
524 let actual_type = actual_types[index];
525 // Add actual type name to <...> clause of function name
526 let actual_type_name = compute_debuginfo_type_name(cx,
529 name_to_append_suffix_to.push_str(&actual_type_name[..]);
531 if index != generics.ty_params.len() - 1 {
532 name_to_append_suffix_to.push_str(",");
535 // Again, only create type information if full debuginfo is enabled
536 if cx.sess().opts.debuginfo == FullDebugInfo {
537 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
538 let name = CString::new(ident.name.as_str().as_bytes()).unwrap();
539 let param_metadata = unsafe {
540 llvm::LLVMDIBuilderCreateTemplateTypeParameter(
544 actual_type_metadata,
549 template_params.push(param_metadata);
553 name_to_append_suffix_to.push('>');
555 return create_DIArray(DIB(cx), &template_params[..]);
559 fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
560 variable_name: ast::Name,
561 variable_type: Ty<'tcx>,
562 scope_metadata: DIScope,
563 variable_access: VariableAccess,
564 variable_kind: VariableKind,
566 let cx: &CrateContext = bcx.ccx();
568 let filename = span_start(cx, span).file.name.clone();
569 let file_metadata = file_metadata(cx, &filename[..]);
571 let loc = span_start(cx, span);
572 let type_metadata = type_metadata(cx, variable_type, span);
574 let (argument_index, dwarf_tag) = match variable_kind {
575 ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
577 CapturedVariable => (0, DW_TAG_auto_variable)
580 let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
581 match (variable_access, &[][..]) {
582 (DirectVariable { alloca }, address_operations) |
583 (IndirectVariable {alloca, address_operations}, _) => {
584 let metadata = unsafe {
585 llvm::LLVMDIBuilderCreateVariable(
593 cx.sess().opts.optimize != config::No,
595 address_operations.as_ptr(),
596 address_operations.len() as c_uint,
599 source_loc::set_debug_location(cx, InternalDebugLocation::new(scope_metadata,
601 loc.col.to_usize()));
603 let debug_loc = llvm::LLVMGetCurrentDebugLocation(cx.raw_builder());
604 let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
608 address_operations.as_ptr(),
609 address_operations.len() as c_uint,
613 llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
618 match variable_kind {
619 ArgumentVariable(_) | CapturedVariable => {
623 .source_locations_enabled
625 source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
627 _ => { /* nothing to do */ }
631 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
633 At(ast::NodeId, Span),
638 pub fn apply(&self, fcx: &FunctionContext) {
640 DebugLoc::At(node_id, span) => {
641 source_loc::set_source_location(fcx, node_id, span);
644 source_loc::clear_source_location(fcx);
650 pub trait ToDebugLoc {
651 fn debug_loc(&self) -> DebugLoc;
654 impl ToDebugLoc for hir::Expr {
655 fn debug_loc(&self) -> DebugLoc {
656 DebugLoc::At(self.id, self.span)
660 impl ToDebugLoc for NodeIdAndSpan {
661 fn debug_loc(&self) -> DebugLoc {
662 DebugLoc::At(self.id, self.span)
666 impl ToDebugLoc for Option<NodeIdAndSpan> {
667 fn debug_loc(&self) -> DebugLoc {
669 Some(NodeIdAndSpan { id, span }) => DebugLoc::At(id, span),
670 None => DebugLoc::None