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, create_DIArray, is_node_local_to_unit};
18 use self::namespace::mangled_name_of_instance;
19 use self::type_names::compute_debuginfo_type_name;
20 use self::metadata::{type_metadata, file_metadata, TypeMap};
21 use self::source_loc::InternalDebugLocation::{self, UnknownLocation};
24 use llvm::{ModuleRef, ContextRef, ValueRef};
25 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray, DIFlags};
26 use rustc::hir::def_id::{DefId, CrateNum};
27 use rustc::ty::subst::Substs;
30 use common::CodegenCx;
32 use monomorphize::Instance;
33 use rustc::ty::{self, ParamEnv, Ty};
35 use rustc::session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
36 use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet};
39 use std::cell::{Cell, RefCell};
40 use std::ffi::CString;
43 use syntax_pos::{self, Span, Pos};
45 use syntax::symbol::{Symbol, InternedString};
46 use rustc::ty::layout::{self, LayoutOf};
56 pub use self::create_scope_map::{create_mir_scopes, MirDebugScope};
57 pub use self::source_loc::start_emitting_source_locations;
58 pub use self::metadata::create_global_var_metadata;
59 pub use self::metadata::create_vtable_metadata;
60 pub use self::metadata::extend_scope_to_file;
61 pub use self::source_loc::set_source_location;
63 #[allow(non_upper_case_globals)]
64 const DW_TAG_auto_variable: c_uint = 0x100;
65 #[allow(non_upper_case_globals)]
66 const DW_TAG_arg_variable: c_uint = 0x101;
68 /// A context object for maintaining all state needed by the debuginfo module.
69 pub struct CrateDebugContext<'tcx> {
70 llcontext: ContextRef,
72 builder: DIBuilderRef,
73 created_files: RefCell<FxHashMap<(Symbol, Symbol), DIFile>>,
74 created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), DIType>>,
76 type_map: RefCell<TypeMap<'tcx>>,
77 namespace_map: RefCell<DefIdMap<DIScope>>,
79 // This collection is used to assert that composite types (structs, enums,
80 // ...) have their members only set once:
81 composite_types_completed: RefCell<FxHashSet<DIType>>,
84 impl<'tcx> CrateDebugContext<'tcx> {
85 pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
86 debug!("CrateDebugContext::new");
87 let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
88 // DIBuilder inherits context from the module, so we'd better use the same one
89 let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
94 created_files: RefCell::new(FxHashMap()),
95 created_enum_disr_types: RefCell::new(FxHashMap()),
96 type_map: RefCell::new(TypeMap::new()),
97 namespace_map: RefCell::new(DefIdMap()),
98 composite_types_completed: RefCell::new(FxHashSet()),
103 pub enum FunctionDebugContext {
104 RegularContext(FunctionDebugContextData),
106 FunctionWithoutDebugInfo,
109 impl FunctionDebugContext {
110 pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData {
112 FunctionDebugContext::RegularContext(ref data) => data,
113 FunctionDebugContext::DebugInfoDisabled => {
114 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
116 FunctionDebugContext::FunctionWithoutDebugInfo => {
117 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
122 fn debuginfo_disabled_message() -> &'static str {
123 "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
126 fn should_be_ignored_message() -> &'static str {
127 "debuginfo: Error trying to access FunctionDebugContext for function that should be \
128 ignored by debug info!"
132 pub struct FunctionDebugContextData {
133 fn_metadata: DISubprogram,
134 source_locations_enabled: Cell<bool>,
135 pub defining_crate: CrateNum,
138 pub enum VariableAccess<'a> {
139 // The llptr given is an alloca containing the variable's value
140 DirectVariable { alloca: ValueRef },
141 // The llptr given is an alloca containing the start of some pointer chain
142 // leading to the variable's content.
143 IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
146 pub enum VariableKind {
147 ArgumentVariable(usize /*index*/),
152 /// Create any deferred debug metadata nodes
153 pub fn finalize(cx: &CodegenCx) {
154 if cx.dbg_cx.is_none() {
160 if gdb::needs_gdb_debug_scripts_section(cx) {
161 // Add a .debug_gdb_scripts section to this compile-unit. This will
162 // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
163 // which activates the Rust pretty printers for binary this section is
165 gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
169 llvm::LLVMRustDIBuilderFinalize(DIB(cx));
170 llvm::LLVMRustDIBuilderDispose(DIB(cx));
171 // Debuginfo generation in LLVM by default uses a higher
172 // version of dwarf than macOS currently understands. We can
173 // instruct LLVM to emit an older version of dwarf, however,
174 // for macOS to understand. For more info see #11352
175 // This can be overridden using --llvm-opts -dwarf-version,N.
176 // Android has the same issue (#22398)
177 if cx.sess().target.target.options.is_like_osx ||
178 cx.sess().target.target.options.is_like_android {
179 llvm::LLVMRustAddModuleFlag(cx.llmod,
180 "Dwarf Version\0".as_ptr() as *const _,
184 // Indicate that we want CodeView debug information on MSVC
185 if cx.sess().target.target.options.is_like_msvc {
186 llvm::LLVMRustAddModuleFlag(cx.llmod,
187 "CodeView\0".as_ptr() as *const _,
191 // Prevent bitcode readers from deleting the debug info.
192 let ptr = "Debug Info Version\0".as_ptr();
193 llvm::LLVMRustAddModuleFlag(cx.llmod, ptr as *const _,
194 llvm::LLVMRustDebugMetadataVersion());
198 /// Creates the function-specific debug context.
200 /// Returns the FunctionDebugContext for the function which holds state needed
201 /// for debug info creation. The function may also return another variant of the
202 /// FunctionDebugContext enum which indicates why no debuginfo should be created
203 /// for the function.
204 pub fn create_function_debug_context<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
205 instance: Instance<'tcx>,
206 sig: ty::FnSig<'tcx>,
208 mir: &mir::Mir) -> FunctionDebugContext {
209 if cx.sess().opts.debuginfo == NoDebugInfo {
210 return FunctionDebugContext::DebugInfoDisabled;
213 for attr in instance.def.attrs(cx.tcx).iter() {
214 if attr.check_name("no_debug") {
215 return FunctionDebugContext::FunctionWithoutDebugInfo;
219 let containing_scope = get_containing_scope(cx, instance);
222 // This can be the case for functions inlined from another crate
223 if span == syntax_pos::DUMMY_SP {
224 // FIXME(simulacrum): Probably can't happen; remove.
225 return FunctionDebugContext::FunctionWithoutDebugInfo;
228 let def_id = instance.def_id();
229 let loc = span_start(cx, span);
230 let file_metadata = file_metadata(cx, &loc.file.name, def_id.krate);
232 let function_type_metadata = unsafe {
233 let fn_signature = get_function_signature(cx, sig);
234 llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
237 // Find the enclosing function, in case this is a closure.
238 let def_key = cx.tcx.def_key(def_id);
239 let mut name = def_key.disambiguated_data.data.to_string();
241 let enclosing_fn_def_id = cx.tcx.closure_base_def_id(def_id);
243 // Get_template_parameters() will append a `<...>` clause to the function
244 // name if necessary.
245 let generics = cx.tcx.generics_of(enclosing_fn_def_id);
246 let substs = instance.substs.truncate_to(cx.tcx, generics);
247 let template_parameters = get_template_parameters(cx,
253 // Get the linkage_name, which is just the symbol name
254 let linkage_name = mangled_name_of_instance(cx, instance);
256 let scope_line = span_start(cx, span).line;
257 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
259 let function_name = CString::new(name).unwrap();
260 let linkage_name = CString::new(linkage_name.to_string()).unwrap();
262 let mut flags = DIFlags::FlagPrototyped;
264 let local_id = cx.tcx.hir.as_local_node_id(def_id);
265 match *cx.sess().entry_fn.borrow() {
266 Some((id, _, _)) => {
267 if local_id == Some(id) {
268 flags = flags | DIFlags::FlagMainSubprogram;
273 if sig.output().is_never() {
274 flags = flags | DIFlags::FlagNoReturn;
277 let fn_metadata = unsafe {
278 llvm::LLVMRustDIBuilderCreateFunction(
281 function_name.as_ptr(),
282 linkage_name.as_ptr(),
285 function_type_metadata,
288 scope_line as c_uint,
290 cx.sess().opts.optimize != config::OptLevel::No,
296 // Initialize fn debug context (including scope map and namespace map)
297 let fn_debug_context = FunctionDebugContextData {
299 source_locations_enabled: Cell::new(false),
300 defining_crate: def_id.krate,
303 return FunctionDebugContext::RegularContext(fn_debug_context);
305 fn get_function_signature<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
306 sig: ty::FnSig<'tcx>) -> DIArray {
307 if cx.sess().opts.debuginfo == LimitedDebugInfo {
308 return create_DIArray(DIB(cx), &[]);
311 let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
313 // Return type -- llvm::DIBuilder wants this at index 0
314 signature.push(match sig.output().sty {
315 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
316 _ => type_metadata(cx, sig.output(), syntax_pos::DUMMY_SP)
319 let inputs = if sig.abi == Abi::RustCall {
320 &sig.inputs()[..sig.inputs().len() - 1]
326 if cx.sess().target.target.options.is_like_msvc {
328 // There is a bug in MSDIA that leads to a crash when it encounters
329 // a fixed-size array of `u8` or something zero-sized in a
330 // function-type (see #40477).
331 // As a workaround, we replace those fixed-size arrays with a
332 // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
333 // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
334 // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
335 // This transformed type is wrong, but these function types are
336 // already inaccurate due to ABI adjustments (see #42800).
337 signature.extend(inputs.iter().map(|&t| {
338 let t = match t.sty {
340 if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() => {
341 cx.tcx.mk_imm_ptr(ct)
345 type_metadata(cx, t, syntax_pos::DUMMY_SP)
348 signature.extend(inputs.iter().map(|t| {
349 type_metadata(cx, t, syntax_pos::DUMMY_SP)
353 if sig.abi == Abi::RustCall && !sig.inputs().is_empty() {
354 if let ty::TyTuple(args) = sig.inputs()[sig.inputs().len() - 1].sty {
355 for &argument_type in args {
356 signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
361 return create_DIArray(DIB(cx), &signature[..]);
364 fn get_template_parameters<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
365 generics: &ty::Generics,
366 substs: &Substs<'tcx>,
367 file_metadata: DIFile,
368 name_to_append_suffix_to: &mut String)
371 if substs.types().next().is_none() {
372 return create_DIArray(DIB(cx), &[]);
375 name_to_append_suffix_to.push('<');
376 for (i, actual_type) in substs.types().enumerate() {
378 name_to_append_suffix_to.push_str(",");
381 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
382 // Add actual type name to <...> clause of function name
383 let actual_type_name = compute_debuginfo_type_name(cx,
386 name_to_append_suffix_to.push_str(&actual_type_name[..]);
388 name_to_append_suffix_to.push('>');
390 // Again, only create type information if full debuginfo is enabled
391 let template_params: Vec<_> = if cx.sess().opts.debuginfo == FullDebugInfo {
392 let names = get_type_parameter_names(cx, generics);
393 substs.types().zip(names).map(|(ty, name)| {
394 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
395 let actual_type_metadata = type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
396 let name = CString::new(name.as_bytes()).unwrap();
398 llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
402 actual_type_metadata,
412 return create_DIArray(DIB(cx), &template_params[..]);
415 fn get_type_parameter_names(cx: &CodegenCx, generics: &ty::Generics) -> Vec<InternedString> {
416 let mut names = generics.parent.map_or(vec![], |def_id| {
417 get_type_parameter_names(cx, cx.tcx.generics_of(def_id))
419 names.extend(generics.types.iter().map(|param| param.name));
423 fn get_containing_scope<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
424 instance: Instance<'tcx>)
426 // First, let's see if this is a method within an inherent impl. Because
427 // if yes, we want to make the result subroutine DIE a child of the
428 // subroutine's self-type.
429 let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
430 // If the method does *not* belong to a trait, proceed
431 if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
432 let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
434 ty::ParamEnv::reveal_all(),
435 &cx.tcx.type_of(impl_def_id),
438 // Only "class" methods are generally understood by LLVM,
439 // so avoid methods on other types (e.g. `<*mut T>::null`).
440 match impl_self_ty.sty {
441 ty::TyAdt(def, ..) if !def.is_box() => {
442 Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
447 // For trait method impls we still use the "parallel namespace"
453 self_type.unwrap_or_else(|| {
454 namespace::item_namespace(cx, DefId {
455 krate: instance.def_id().krate,
457 .def_key(instance.def_id())
459 .expect("get_containing_scope: missing parent?")
465 pub fn declare_local<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
466 dbg_context: &FunctionDebugContext,
467 variable_name: ast::Name,
468 variable_type: Ty<'tcx>,
469 scope_metadata: DIScope,
470 variable_access: VariableAccess,
471 variable_kind: VariableKind,
475 let file = span_start(cx, span).file;
476 let file_metadata = file_metadata(cx,
478 dbg_context.get_ref(span).defining_crate);
480 let loc = span_start(cx, span);
481 let type_metadata = type_metadata(cx, variable_type, span);
483 let (argument_index, dwarf_tag) = match variable_kind {
484 ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
486 CapturedVariable => (0, DW_TAG_auto_variable)
488 let align = cx.align_of(variable_type);
490 let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
491 match (variable_access, &[][..]) {
492 (DirectVariable { alloca }, address_operations) |
493 (IndirectVariable {alloca, address_operations}, _) => {
494 let metadata = unsafe {
495 llvm::LLVMRustDIBuilderCreateVariable(
503 cx.sess().opts.optimize != config::OptLevel::No,
509 source_loc::set_debug_location(bx,
510 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
512 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bx.llbuilder);
513 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
517 address_operations.as_ptr(),
518 address_operations.len() as c_uint,
522 llvm::LLVMSetInstDebugLocation(bx.llbuilder, instr);
527 match variable_kind {
528 ArgumentVariable(_) | CapturedVariable => {
529 assert!(!dbg_context.get_ref(span).source_locations_enabled.get());
530 source_loc::set_debug_location(bx, UnknownLocation);
532 _ => { /* nothing to do */ }