]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/mod.rs
Auto merge of #49558 - Zoxc:sync-misc, r=michaelwoerister
[rust.git] / src / librustc_trans / debuginfo / mod.rs
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.
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 // See doc.rs for documentation.
12 mod doc;
13
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
16
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};
22
23 use llvm;
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;
28
29 use abi::Abi;
30 use common::CodegenCx;
31 use builder::Builder;
32 use monomorphize::Instance;
33 use rustc::ty::{self, ParamEnv, Ty};
34 use rustc::mir;
35 use rustc::session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
36 use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet};
37
38 use libc::c_uint;
39 use std::cell::{Cell, RefCell};
40 use std::ffi::CString;
41 use std::ptr;
42
43 use syntax_pos::{self, Span, Pos};
44 use syntax::ast;
45 use syntax::symbol::{Symbol, InternedString};
46 use rustc::ty::layout::{self, LayoutOf};
47
48 pub mod gdb;
49 mod utils;
50 mod namespace;
51 mod type_names;
52 pub mod metadata;
53 mod create_scope_map;
54 mod source_loc;
55
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;
62
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;
67
68 /// A context object for maintaining all state needed by the debuginfo module.
69 pub struct CrateDebugContext<'tcx> {
70     llcontext: ContextRef,
71     llmod: ModuleRef,
72     builder: DIBuilderRef,
73     created_files: RefCell<FxHashMap<(Symbol, Symbol), DIFile>>,
74     created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), DIType>>,
75
76     type_map: RefCell<TypeMap<'tcx>>,
77     namespace_map: RefCell<DefIdMap<DIScope>>,
78
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>>,
82 }
83
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) };
90         CrateDebugContext {
91             llcontext,
92             llmod,
93             builder,
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()),
99         }
100     }
101 }
102
103 pub enum FunctionDebugContext {
104     RegularContext(FunctionDebugContextData),
105     DebugInfoDisabled,
106     FunctionWithoutDebugInfo,
107 }
108
109 impl FunctionDebugContext {
110     pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData {
111         match *self {
112             FunctionDebugContext::RegularContext(ref data) => data,
113             FunctionDebugContext::DebugInfoDisabled => {
114                 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
115             }
116             FunctionDebugContext::FunctionWithoutDebugInfo => {
117                 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
118             }
119         }
120     }
121
122     fn debuginfo_disabled_message() -> &'static str {
123         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
124     }
125
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!"
129     }
130 }
131
132 pub struct FunctionDebugContextData {
133     fn_metadata: DISubprogram,
134     source_locations_enabled: Cell<bool>,
135     pub defining_crate: CrateNum,
136 }
137
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] }
144 }
145
146 pub enum VariableKind {
147     ArgumentVariable(usize /*index*/),
148     LocalVariable,
149     CapturedVariable,
150 }
151
152 /// Create any deferred debug metadata nodes
153 pub fn finalize(cx: &CodegenCx) {
154     if cx.dbg_cx.is_none() {
155         return;
156     }
157
158     debug!("finalize");
159
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
164         // contained in.
165         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
166     }
167
168     unsafe {
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 _,
181                                         2)
182         }
183
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 _,
188                                         1)
189         }
190
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());
195     };
196 }
197
198 /// Creates the function-specific debug context.
199 ///
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>,
207                                                llfn: ValueRef,
208                                                mir: &mir::Mir) -> FunctionDebugContext {
209     if cx.sess().opts.debuginfo == NoDebugInfo {
210         return FunctionDebugContext::DebugInfoDisabled;
211     }
212
213     for attr in instance.def.attrs(cx.tcx).iter() {
214         if attr.check_name("no_debug") {
215             return FunctionDebugContext::FunctionWithoutDebugInfo;
216         }
217     }
218
219     let containing_scope = get_containing_scope(cx, instance);
220     let span = mir.span;
221
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;
226     }
227
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);
231
232     let function_type_metadata = unsafe {
233         let fn_signature = get_function_signature(cx, sig);
234         llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
235     };
236
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();
240
241     let enclosing_fn_def_id = cx.tcx.closure_base_def_id(def_id);
242
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,
248                                                       &generics,
249                                                       substs,
250                                                       file_metadata,
251                                                       &mut name);
252
253     // Get the linkage_name, which is just the symbol name
254     let linkage_name = mangled_name_of_instance(cx, instance);
255
256     let scope_line = span_start(cx, span).line;
257     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
258
259     let function_name = CString::new(name).unwrap();
260     let linkage_name = CString::new(linkage_name.to_string()).unwrap();
261
262     let mut flags = DIFlags::FlagPrototyped;
263
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;
269             }
270         }
271         None => {}
272     };
273     if sig.output().is_never() {
274         flags = flags | DIFlags::FlagNoReturn;
275     }
276
277     let fn_metadata = unsafe {
278         llvm::LLVMRustDIBuilderCreateFunction(
279             DIB(cx),
280             containing_scope,
281             function_name.as_ptr(),
282             linkage_name.as_ptr(),
283             file_metadata,
284             loc.line as c_uint,
285             function_type_metadata,
286             is_local_to_unit,
287             true,
288             scope_line as c_uint,
289             flags,
290             cx.sess().opts.optimize != config::OptLevel::No,
291             llfn,
292             template_parameters,
293             ptr::null_mut())
294     };
295
296     // Initialize fn debug context (including scope map and namespace map)
297     let fn_debug_context = FunctionDebugContextData {
298         fn_metadata,
299         source_locations_enabled: Cell::new(false),
300         defining_crate: def_id.krate,
301     };
302
303     return FunctionDebugContext::RegularContext(fn_debug_context);
304
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), &[]);
309         }
310
311         let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
312
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)
317         });
318
319         let inputs = if sig.abi == Abi::RustCall {
320             &sig.inputs()[..sig.inputs().len() - 1]
321         } else {
322             sig.inputs()
323         };
324
325         // Arguments types
326         if cx.sess().target.target.options.is_like_msvc {
327             // FIXME(#42800):
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 {
339                     ty::TyArray(ct, _)
340                         if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() => {
341                         cx.tcx.mk_imm_ptr(ct)
342                     }
343                     _ => t
344                 };
345                 type_metadata(cx, t, syntax_pos::DUMMY_SP)
346             }));
347         } else {
348             signature.extend(inputs.iter().map(|t| {
349                 type_metadata(cx, t, syntax_pos::DUMMY_SP)
350             }));
351         }
352
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));
357                 }
358             }
359         }
360
361         return create_DIArray(DIB(cx), &signature[..]);
362     }
363
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)
369                                          -> DIArray
370     {
371         if substs.types().next().is_none() {
372             return create_DIArray(DIB(cx), &[]);
373         }
374
375         name_to_append_suffix_to.push('<');
376         for (i, actual_type) in substs.types().enumerate() {
377             if i != 0 {
378                 name_to_append_suffix_to.push_str(",");
379             }
380
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,
384                                                                actual_type,
385                                                                true);
386             name_to_append_suffix_to.push_str(&actual_type_name[..]);
387         }
388         name_to_append_suffix_to.push('>');
389
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();
397                 unsafe {
398                     llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
399                         DIB(cx),
400                         ptr::null_mut(),
401                         name.as_ptr(),
402                         actual_type_metadata,
403                         file_metadata,
404                         0,
405                         0)
406                 }
407             }).collect()
408         } else {
409             vec![]
410         };
411
412         return create_DIArray(DIB(cx), &template_params[..]);
413     }
414
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))
418         });
419         names.extend(generics.types.iter().map(|param| param.name));
420         names
421     }
422
423     fn get_containing_scope<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
424                                         instance: Instance<'tcx>)
425                                         -> DIScope {
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(
433                     instance.substs,
434                     ty::ParamEnv::reveal_all(),
435                     &cx.tcx.type_of(impl_def_id),
436                 );
437
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))
443                     }
444                     _ => None
445                 }
446             } else {
447                 // For trait method impls we still use the "parallel namespace"
448                 // strategy
449                 None
450             }
451         });
452
453         self_type.unwrap_or_else(|| {
454             namespace::item_namespace(cx, DefId {
455                 krate: instance.def_id().krate,
456                 index: cx.tcx
457                          .def_key(instance.def_id())
458                          .parent
459                          .expect("get_containing_scope: missing parent?")
460             })
461         })
462     }
463 }
464
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,
472                                span: Span) {
473     let cx = bx.cx;
474
475     let file = span_start(cx, span).file;
476     let file_metadata = file_metadata(cx,
477                                       &file.name,
478                                       dbg_context.get_ref(span).defining_crate);
479
480     let loc = span_start(cx, span);
481     let type_metadata = type_metadata(cx, variable_type, span);
482
483     let (argument_index, dwarf_tag) = match variable_kind {
484         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
485         LocalVariable    |
486         CapturedVariable => (0, DW_TAG_auto_variable)
487     };
488     let align = cx.align_of(variable_type);
489
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(
496                     DIB(cx),
497                     dwarf_tag,
498                     scope_metadata,
499                     name.as_ptr(),
500                     file_metadata,
501                     loc.line as c_uint,
502                     type_metadata,
503                     cx.sess().opts.optimize != config::OptLevel::No,
504                     DIFlags::FlagZero,
505                     argument_index,
506                     align.abi() as u32,
507                 )
508             };
509             source_loc::set_debug_location(bx,
510                 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
511             unsafe {
512                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bx.llbuilder);
513                 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
514                     DIB(cx),
515                     alloca,
516                     metadata,
517                     address_operations.as_ptr(),
518                     address_operations.len() as c_uint,
519                     debug_loc,
520                     bx.llbb());
521
522                 llvm::LLVMSetInstDebugLocation(bx.llbuilder, instr);
523             }
524         }
525     }
526
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);
531         }
532         _ => { /* nothing to do */ }
533     }
534 }