]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/debuginfo/mod.rs
Rollup merge of #69807 - GuillaumeGomez:cleanup-e0391, r=Dylan-DPC
[rust.git] / src / librustc_codegen_llvm / debuginfo / mod.rs
1 // See doc.rs for documentation.
2 mod doc;
3
4 use rustc_codegen_ssa::mir::debuginfo::VariableKind::*;
5
6 use self::metadata::{file_metadata, type_metadata, TypeMap};
7 use self::namespace::mangled_name_of_instance;
8 use self::type_names::compute_debuginfo_type_name;
9 use self::utils::{create_DIArray, is_node_local_to_unit, span_start, DIB};
10
11 use crate::llvm;
12 use crate::llvm::debuginfo::{
13     DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DISPFlags, DIScope, DIType, DIVariable,
14 };
15 use rustc::ty::subst::{GenericArgKind, SubstsRef};
16 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
17
18 use crate::abi::FnAbi;
19 use crate::builder::Builder;
20 use crate::common::CodegenCx;
21 use crate::value::Value;
22 use rustc::mir;
23 use rustc::session::config::{self, DebugInfo};
24 use rustc::ty::{self, Instance, ParamEnv, Ty};
25 use rustc_codegen_ssa::debuginfo::type_names;
26 use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind};
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
28 use rustc_data_structures::small_c_str::SmallCStr;
29 use rustc_index::vec::IndexVec;
30
31 use libc::c_uint;
32 use log::debug;
33 use std::cell::RefCell;
34 use std::ffi::CString;
35
36 use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, Size};
37 use rustc_ast::ast;
38 use rustc_codegen_ssa::traits::*;
39 use rustc_span::symbol::Symbol;
40 use rustc_span::{self, BytePos, Span};
41 use smallvec::SmallVec;
42
43 mod create_scope_map;
44 pub mod gdb;
45 pub mod metadata;
46 mod namespace;
47 mod source_loc;
48 mod utils;
49
50 pub use self::create_scope_map::compute_mir_scopes;
51 pub use self::metadata::create_global_var_metadata;
52 pub use self::metadata::extend_scope_to_file;
53
54 #[allow(non_upper_case_globals)]
55 const DW_TAG_auto_variable: c_uint = 0x100;
56 #[allow(non_upper_case_globals)]
57 const DW_TAG_arg_variable: c_uint = 0x101;
58
59 /// A context object for maintaining all state needed by the debuginfo module.
60 pub struct CrateDebugContext<'a, 'tcx> {
61     llcontext: &'a llvm::Context,
62     llmod: &'a llvm::Module,
63     builder: &'a mut DIBuilder<'a>,
64     created_files: RefCell<FxHashMap<(Option<String>, Option<String>), &'a DIFile>>,
65     created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), &'a DIType>>,
66
67     type_map: RefCell<TypeMap<'a, 'tcx>>,
68     namespace_map: RefCell<DefIdMap<&'a DIScope>>,
69
70     // This collection is used to assert that composite types (structs, enums,
71     // ...) have their members only set once:
72     composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
73 }
74
75 impl Drop for CrateDebugContext<'a, 'tcx> {
76     fn drop(&mut self) {
77         unsafe {
78             llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
79         }
80     }
81 }
82
83 impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
84     pub fn new(llmod: &'a llvm::Module) -> Self {
85         debug!("CrateDebugContext::new");
86         let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
87         // DIBuilder inherits context from the module, so we'd better use the same one
88         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
89         CrateDebugContext {
90             llcontext,
91             llmod,
92             builder,
93             created_files: Default::default(),
94             created_enum_disr_types: Default::default(),
95             type_map: Default::default(),
96             namespace_map: RefCell::new(Default::default()),
97             composite_types_completed: Default::default(),
98         }
99     }
100 }
101
102 /// Creates any deferred debug metadata nodes
103 pub fn finalize(cx: &CodegenCx<'_, '_>) {
104     if cx.dbg_cx.is_none() {
105         return;
106     }
107
108     debug!("finalize");
109
110     if gdb::needs_gdb_debug_scripts_section(cx) {
111         // Add a .debug_gdb_scripts section to this compile-unit. This will
112         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
113         // which activates the Rust pretty printers for binary this section is
114         // contained in.
115         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
116     }
117
118     unsafe {
119         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
120         // Debuginfo generation in LLVM by default uses a higher
121         // version of dwarf than macOS currently understands. We can
122         // instruct LLVM to emit an older version of dwarf, however,
123         // for macOS to understand. For more info see #11352
124         // This can be overridden using --llvm-opts -dwarf-version,N.
125         // Android has the same issue (#22398)
126         if cx.sess().target.target.options.is_like_osx
127             || cx.sess().target.target.options.is_like_android
128         {
129             llvm::LLVMRustAddModuleFlag(cx.llmod, "Dwarf Version\0".as_ptr().cast(), 2)
130         }
131
132         // Indicate that we want CodeView debug information on MSVC
133         if cx.sess().target.target.options.is_like_msvc {
134             llvm::LLVMRustAddModuleFlag(cx.llmod, "CodeView\0".as_ptr().cast(), 1)
135         }
136
137         // Prevent bitcode readers from deleting the debug info.
138         let ptr = "Debug Info Version\0".as_ptr();
139         llvm::LLVMRustAddModuleFlag(cx.llmod, ptr.cast(), llvm::LLVMRustDebugMetadataVersion());
140     };
141 }
142
143 impl DebugInfoBuilderMethods for Builder<'a, 'll, 'tcx> {
144     // FIXME(eddyb) find a common convention for all of the debuginfo-related
145     // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
146     fn dbg_var_addr(
147         &mut self,
148         dbg_var: &'ll DIVariable,
149         scope_metadata: &'ll DIScope,
150         variable_alloca: Self::Value,
151         direct_offset: Size,
152         indirect_offsets: &[Size],
153         span: Span,
154     ) {
155         let cx = self.cx();
156
157         // Convert the direct and indirect offsets to address ops.
158         // FIXME(eddyb) use `const`s instead of getting the values via FFI,
159         // the values should match the ones in the DWARF standard anyway.
160         let op_deref = || unsafe { llvm::LLVMRustDIBuilderCreateOpDeref() };
161         let op_plus_uconst = || unsafe { llvm::LLVMRustDIBuilderCreateOpPlusUconst() };
162         let mut addr_ops = SmallVec::<[_; 8]>::new();
163
164         if direct_offset.bytes() > 0 {
165             addr_ops.push(op_plus_uconst());
166             addr_ops.push(direct_offset.bytes() as i64);
167         }
168         for &offset in indirect_offsets {
169             addr_ops.push(op_deref());
170             if offset.bytes() > 0 {
171                 addr_ops.push(op_plus_uconst());
172                 addr_ops.push(offset.bytes() as i64);
173             }
174         }
175
176         // FIXME(eddyb) maybe this information could be extracted from `dbg_var`,
177         // to avoid having to pass it down in both places?
178         // NB: `var` doesn't seem to know about the column, so that's a limitation.
179         let dbg_loc = cx.create_debug_loc(scope_metadata, span);
180         unsafe {
181             // FIXME(eddyb) replace `llvm.dbg.declare` with `llvm.dbg.addr`.
182             llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
183                 DIB(cx),
184                 variable_alloca,
185                 dbg_var,
186                 addr_ops.as_ptr(),
187                 addr_ops.len() as c_uint,
188                 dbg_loc,
189                 self.llbb(),
190             );
191         }
192     }
193
194     fn set_source_location(&mut self, scope: &'ll DIScope, span: Span) {
195         debug!("set_source_location: {}", self.sess().source_map().span_to_string(span));
196
197         let dbg_loc = self.cx().create_debug_loc(scope, span);
198
199         unsafe {
200             llvm::LLVMSetCurrentDebugLocation(self.llbuilder, dbg_loc);
201         }
202     }
203     fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
204         gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
205     }
206
207     fn set_var_name(&mut self, value: &'ll Value, name: &str) {
208         // Avoid wasting time if LLVM value names aren't even enabled.
209         if self.sess().fewer_names() {
210             return;
211         }
212
213         // Only function parameters and instructions are local to a function,
214         // don't change the name of anything else (e.g. globals).
215         let param_or_inst = unsafe {
216             llvm::LLVMIsAArgument(value).is_some() || llvm::LLVMIsAInstruction(value).is_some()
217         };
218         if !param_or_inst {
219             return;
220         }
221
222         // Avoid replacing the name if it already exists.
223         // While we could combine the names somehow, it'd
224         // get noisy quick, and the usefulness is dubious.
225         if llvm::get_value_name(value).is_empty() {
226             llvm::set_value_name(value, name.as_bytes());
227         }
228     }
229 }
230
231 impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> {
232     fn create_function_debug_context(
233         &self,
234         instance: Instance<'tcx>,
235         fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
236         llfn: &'ll Value,
237         mir: &mir::Body<'_>,
238     ) -> Option<FunctionDebugContext<&'ll DIScope>> {
239         if self.sess().opts.debuginfo == DebugInfo::None {
240             return None;
241         }
242
243         let span = mir.span;
244
245         // This can be the case for functions inlined from another crate
246         if span.is_dummy() {
247             // FIXME(simulacrum): Probably can't happen; remove.
248             return None;
249         }
250
251         let def_id = instance.def_id();
252         let containing_scope = get_containing_scope(self, instance);
253         let loc = span_start(self, span);
254         let file_metadata = file_metadata(self, &loc.file.name, def_id.krate);
255
256         let function_type_metadata = unsafe {
257             let fn_signature = get_function_signature(self, fn_abi);
258             llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(self), file_metadata, fn_signature)
259         };
260
261         // Find the enclosing function, in case this is a closure.
262         let def_key = self.tcx().def_key(def_id);
263         let mut name = def_key.disambiguated_data.data.to_string();
264
265         let enclosing_fn_def_id = self.tcx().closure_base_def_id(def_id);
266
267         // Get_template_parameters() will append a `<...>` clause to the function
268         // name if necessary.
269         let generics = self.tcx().generics_of(enclosing_fn_def_id);
270         let substs = instance.substs.truncate_to(self.tcx(), generics);
271         let template_parameters =
272             get_template_parameters(self, &generics, substs, file_metadata, &mut name);
273
274         // Get the linkage_name, which is just the symbol name
275         let linkage_name = mangled_name_of_instance(self, instance);
276
277         // FIXME(eddyb) does this need to be separate from `loc.line` for some reason?
278         let scope_line = loc.line;
279
280         let function_name = CString::new(name).unwrap();
281         let linkage_name = SmallCStr::new(&linkage_name.name.as_str());
282
283         let mut flags = DIFlags::FlagPrototyped;
284
285         if fn_abi.ret.layout.abi.is_uninhabited() {
286             flags |= DIFlags::FlagNoReturn;
287         }
288
289         let mut spflags = DISPFlags::SPFlagDefinition;
290         if is_node_local_to_unit(self, def_id) {
291             spflags |= DISPFlags::SPFlagLocalToUnit;
292         }
293         if self.sess().opts.optimize != config::OptLevel::No {
294             spflags |= DISPFlags::SPFlagOptimized;
295         }
296         if let Some((id, _)) = self.tcx.entry_fn(LOCAL_CRATE) {
297             if id == def_id {
298                 spflags |= DISPFlags::SPFlagMainSubprogram;
299             }
300         }
301
302         let fn_metadata = unsafe {
303             llvm::LLVMRustDIBuilderCreateFunction(
304                 DIB(self),
305                 containing_scope,
306                 function_name.as_ptr(),
307                 linkage_name.as_ptr(),
308                 file_metadata,
309                 loc.line as c_uint,
310                 function_type_metadata,
311                 scope_line as c_uint,
312                 flags,
313                 spflags,
314                 llfn,
315                 template_parameters,
316                 None,
317             )
318         };
319
320         // Initialize fn debug context (including scopes).
321         // FIXME(eddyb) figure out a way to not need `Option` for `scope_metadata`.
322         let null_scope = DebugScope {
323             scope_metadata: None,
324             file_start_pos: BytePos(0),
325             file_end_pos: BytePos(0),
326         };
327         let mut fn_debug_context = FunctionDebugContext {
328             scopes: IndexVec::from_elem(null_scope, &mir.source_scopes),
329             defining_crate: def_id.krate,
330         };
331
332         // Fill in all the scopes, with the information from the MIR body.
333         compute_mir_scopes(self, mir, fn_metadata, &mut fn_debug_context);
334
335         return Some(fn_debug_context);
336
337         fn get_function_signature<'ll, 'tcx>(
338             cx: &CodegenCx<'ll, 'tcx>,
339             fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
340         ) -> &'ll DIArray {
341             if cx.sess().opts.debuginfo == DebugInfo::Limited {
342                 return create_DIArray(DIB(cx), &[]);
343             }
344
345             let mut signature = Vec::with_capacity(fn_abi.args.len() + 1);
346
347             // Return type -- llvm::DIBuilder wants this at index 0
348             signature.push(if fn_abi.ret.is_ignore() {
349                 None
350             } else {
351                 Some(type_metadata(cx, fn_abi.ret.layout.ty, rustc_span::DUMMY_SP))
352             });
353
354             // Arguments types
355             if cx.sess().target.target.options.is_like_msvc {
356                 // FIXME(#42800):
357                 // There is a bug in MSDIA that leads to a crash when it encounters
358                 // a fixed-size array of `u8` or something zero-sized in a
359                 // function-type (see #40477).
360                 // As a workaround, we replace those fixed-size arrays with a
361                 // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
362                 // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
363                 // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
364                 // This transformed type is wrong, but these function types are
365                 // already inaccurate due to ABI adjustments (see #42800).
366                 signature.extend(fn_abi.args.iter().map(|arg| {
367                     let t = arg.layout.ty;
368                     let t = match t.kind {
369                         ty::Array(ct, _)
370                             if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() =>
371                         {
372                             cx.tcx.mk_imm_ptr(ct)
373                         }
374                         _ => t,
375                     };
376                     Some(type_metadata(cx, t, rustc_span::DUMMY_SP))
377                 }));
378             } else {
379                 signature.extend(
380                     fn_abi
381                         .args
382                         .iter()
383                         .map(|arg| Some(type_metadata(cx, arg.layout.ty, rustc_span::DUMMY_SP))),
384                 );
385             }
386
387             create_DIArray(DIB(cx), &signature[..])
388         }
389
390         fn get_template_parameters<'ll, 'tcx>(
391             cx: &CodegenCx<'ll, 'tcx>,
392             generics: &ty::Generics,
393             substs: SubstsRef<'tcx>,
394             file_metadata: &'ll DIFile,
395             name_to_append_suffix_to: &mut String,
396         ) -> &'ll DIArray {
397             if substs.types().next().is_none() {
398                 return create_DIArray(DIB(cx), &[]);
399             }
400
401             name_to_append_suffix_to.push('<');
402             for (i, actual_type) in substs.types().enumerate() {
403                 if i != 0 {
404                     name_to_append_suffix_to.push_str(",");
405                 }
406
407                 let actual_type =
408                     cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
409                 // Add actual type name to <...> clause of function name
410                 let actual_type_name = compute_debuginfo_type_name(cx.tcx(), actual_type, true);
411                 name_to_append_suffix_to.push_str(&actual_type_name[..]);
412             }
413             name_to_append_suffix_to.push('>');
414
415             // Again, only create type information if full debuginfo is enabled
416             let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
417                 let names = get_parameter_names(cx, generics);
418                 substs
419                     .iter()
420                     .zip(names)
421                     .filter_map(|(kind, name)| {
422                         if let GenericArgKind::Type(ty) = kind.unpack() {
423                             let actual_type =
424                                 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
425                             let actual_type_metadata =
426                                 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
427                             let name = SmallCStr::new(&name.as_str());
428                             Some(unsafe {
429                                 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
430                                     DIB(cx),
431                                     None,
432                                     name.as_ptr(),
433                                     actual_type_metadata,
434                                     file_metadata,
435                                     0,
436                                     0,
437                                 ))
438                             })
439                         } else {
440                             None
441                         }
442                     })
443                     .collect()
444             } else {
445                 vec![]
446             };
447
448             return create_DIArray(DIB(cx), &template_params[..]);
449         }
450
451         fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
452             let mut names = generics
453                 .parent
454                 .map_or(vec![], |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
455             names.extend(generics.params.iter().map(|param| param.name));
456             names
457         }
458
459         fn get_containing_scope<'ll, 'tcx>(
460             cx: &CodegenCx<'ll, 'tcx>,
461             instance: Instance<'tcx>,
462         ) -> &'ll DIScope {
463             // First, let's see if this is a method within an inherent impl. Because
464             // if yes, we want to make the result subroutine DIE a child of the
465             // subroutine's self-type.
466             let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
467                 // If the method does *not* belong to a trait, proceed
468                 if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
469                     let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
470                         instance.substs,
471                         ty::ParamEnv::reveal_all(),
472                         &cx.tcx.type_of(impl_def_id),
473                     );
474
475                     // Only "class" methods are generally understood by LLVM,
476                     // so avoid methods on other types (e.g., `<*mut T>::null`).
477                     match impl_self_ty.kind {
478                         ty::Adt(def, ..) if !def.is_box() => {
479                             Some(type_metadata(cx, impl_self_ty, rustc_span::DUMMY_SP))
480                         }
481                         _ => None,
482                     }
483                 } else {
484                     // For trait method impls we still use the "parallel namespace"
485                     // strategy
486                     None
487                 }
488             });
489
490             self_type.unwrap_or_else(|| {
491                 namespace::item_namespace(
492                     cx,
493                     DefId {
494                         krate: instance.def_id().krate,
495                         index: cx
496                             .tcx
497                             .def_key(instance.def_id())
498                             .parent
499                             .expect("get_containing_scope: missing parent?"),
500                     },
501                 )
502             })
503         }
504     }
505
506     fn create_vtable_metadata(&self, ty: Ty<'tcx>, vtable: Self::Value) {
507         metadata::create_vtable_metadata(self, ty, vtable)
508     }
509
510     fn extend_scope_to_file(
511         &self,
512         scope_metadata: &'ll DIScope,
513         file: &rustc_span::SourceFile,
514         defining_crate: CrateNum,
515     ) -> &'ll DILexicalBlock {
516         metadata::extend_scope_to_file(&self, scope_metadata, file, defining_crate)
517     }
518
519     fn debuginfo_finalize(&self) {
520         finalize(self)
521     }
522
523     // FIXME(eddyb) find a common convention for all of the debuginfo-related
524     // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
525     fn create_dbg_var(
526         &self,
527         dbg_context: &FunctionDebugContext<&'ll DIScope>,
528         variable_name: ast::Name,
529         variable_type: Ty<'tcx>,
530         scope_metadata: &'ll DIScope,
531         variable_kind: VariableKind,
532         span: Span,
533     ) -> &'ll DIVariable {
534         let loc = span_start(self, span);
535         let file_metadata = file_metadata(self, &loc.file.name, dbg_context.defining_crate);
536
537         let type_metadata = type_metadata(self, variable_type, span);
538
539         let (argument_index, dwarf_tag) = match variable_kind {
540             ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
541             LocalVariable => (0, DW_TAG_auto_variable),
542         };
543         let align = self.align_of(variable_type);
544
545         let name = SmallCStr::new(&variable_name.as_str());
546         unsafe {
547             llvm::LLVMRustDIBuilderCreateVariable(
548                 DIB(self),
549                 dwarf_tag,
550                 scope_metadata,
551                 name.as_ptr(),
552                 file_metadata,
553                 loc.line as c_uint,
554                 type_metadata,
555                 true,
556                 DIFlags::FlagZero,
557                 argument_index,
558                 align.bytes() as u32,
559             )
560         }
561     }
562 }