blob: b928e903730b6af9a355185629a462d1c190c511 [file] [log] [blame]
Chris Wailes32f78352021-07-20 14:04:55 -07001#![doc = include_str!("doc.md")]
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +01002
3use rustc_codegen_ssa::mir::debuginfo::VariableKind::*;
4
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +01005use self::metadata::{file_metadata, type_metadata, TypeMap};
6use self::metadata::{UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER};
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +01007use self::namespace::mangled_name_of_instance;
8use self::type_names::compute_debuginfo_type_name;
9use self::utils::{create_DIArray, is_node_local_to_unit, DIB};
10
11use crate::abi::FnAbi;
12use crate::builder::Builder;
13use crate::common::CodegenCx;
14use crate::llvm;
15use crate::llvm::debuginfo::{
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +010016 DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType,
17 DIVariable,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +010018};
19use crate::value::Value;
20
21use rustc_codegen_ssa::debuginfo::type_names;
22use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind};
23use rustc_codegen_ssa::traits::*;
24use rustc_data_structures::fx::{FxHashMap, FxHashSet};
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +010025use rustc_data_structures::sync::Lrc;
26use rustc_hir::def_id::{DefId, DefIdMap, LOCAL_CRATE};
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +010027use rustc_index::vec::IndexVec;
28use rustc_middle::mir;
29use rustc_middle::ty::layout::HasTyCtxt;
30use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
31use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TypeFoldable};
32use rustc_session::config::{self, DebugInfo};
33use rustc_span::symbol::Symbol;
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +010034use rustc_span::{self, BytePos, Pos, SourceFile, SourceFileAndLine, Span};
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +010035use rustc_target::abi::{LayoutOf, Primitive, Size};
36
37use libc::c_uint;
38use smallvec::SmallVec;
39use std::cell::RefCell;
Chris Wailes32f78352021-07-20 14:04:55 -070040use std::iter;
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +010041use tracing::debug;
42
43mod create_scope_map;
44pub mod gdb;
45pub mod metadata;
46mod namespace;
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +010047mod utils;
48
49pub use self::create_scope_map::compute_mir_scopes;
50pub use self::metadata::create_global_var_metadata;
51pub use self::metadata::extend_scope_to_file;
52
53#[allow(non_upper_case_globals)]
54const DW_TAG_auto_variable: c_uint = 0x100;
55#[allow(non_upper_case_globals)]
56const DW_TAG_arg_variable: c_uint = 0x101;
57
58/// A context object for maintaining all state needed by the debuginfo module.
59pub struct CrateDebugContext<'a, 'tcx> {
60 llcontext: &'a llvm::Context,
61 llmod: &'a llvm::Module,
62 builder: &'a mut DIBuilder<'a>,
63 created_files: RefCell<FxHashMap<(Option<String>, Option<String>), &'a DIFile>>,
64 created_enum_disr_types: RefCell<FxHashMap<(DefId, Primitive), &'a DIType>>,
65
66 type_map: RefCell<TypeMap<'a, 'tcx>>,
67 namespace_map: RefCell<DefIdMap<&'a DIScope>>,
68
69 // This collection is used to assert that composite types (structs, enums,
70 // ...) have their members only set once:
71 composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
72}
73
74impl Drop for CrateDebugContext<'a, 'tcx> {
75 fn drop(&mut self) {
76 unsafe {
77 llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
78 }
79 }
80}
81
82impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
83 pub fn new(llmod: &'a llvm::Module) -> Self {
84 debug!("CrateDebugContext::new");
85 let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
86 // DIBuilder inherits context from the module, so we'd better use the same one
87 let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
88 CrateDebugContext {
89 llcontext,
90 llmod,
91 builder,
92 created_files: Default::default(),
93 created_enum_disr_types: Default::default(),
94 type_map: Default::default(),
95 namespace_map: RefCell::new(Default::default()),
96 composite_types_completed: Default::default(),
97 }
98 }
99}
100
101/// Creates any deferred debug metadata nodes
102pub fn finalize(cx: &CodegenCx<'_, '_>) {
103 if cx.dbg_cx.is_none() {
104 return;
105 }
106
107 debug!("finalize");
108
109 if gdb::needs_gdb_debug_scripts_section(cx) {
110 // Add a .debug_gdb_scripts section to this compile-unit. This will
111 // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
112 // which activates the Rust pretty printers for binary this section is
113 // contained in.
114 gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
115 }
116
117 unsafe {
118 llvm::LLVMRustDIBuilderFinalize(DIB(cx));
119 // Debuginfo generation in LLVM by default uses a higher
120 // version of dwarf than macOS currently understands. We can
121 // instruct LLVM to emit an older version of dwarf, however,
122 // for macOS to understand. For more info see #11352
123 // This can be overridden using --llvm-opts -dwarf-version,N.
124 // Android has the same issue (#22398)
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100125 if let Some(version) = cx.sess().target.dwarf_version {
126 llvm::LLVMRustAddModuleFlag(cx.llmod, "Dwarf Version\0".as_ptr().cast(), version)
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100127 }
128
129 // Indicate that we want CodeView debug information on MSVC
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100130 if cx.sess().target.is_like_msvc {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100131 llvm::LLVMRustAddModuleFlag(cx.llmod, "CodeView\0".as_ptr().cast(), 1)
132 }
133
134 // Prevent bitcode readers from deleting the debug info.
135 let ptr = "Debug Info Version\0".as_ptr();
136 llvm::LLVMRustAddModuleFlag(cx.llmod, ptr.cast(), llvm::LLVMRustDebugMetadataVersion());
137 };
138}
139
140impl DebugInfoBuilderMethods for Builder<'a, 'll, 'tcx> {
141 // FIXME(eddyb) find a common convention for all of the debuginfo-related
142 // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
143 fn dbg_var_addr(
144 &mut self,
145 dbg_var: &'ll DIVariable,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100146 dbg_loc: &'ll DILocation,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100147 variable_alloca: Self::Value,
148 direct_offset: Size,
149 indirect_offsets: &[Size],
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100150 ) {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100151 // Convert the direct and indirect offsets to address ops.
152 // FIXME(eddyb) use `const`s instead of getting the values via FFI,
153 // the values should match the ones in the DWARF standard anyway.
154 let op_deref = || unsafe { llvm::LLVMRustDIBuilderCreateOpDeref() };
155 let op_plus_uconst = || unsafe { llvm::LLVMRustDIBuilderCreateOpPlusUconst() };
156 let mut addr_ops = SmallVec::<[_; 8]>::new();
157
158 if direct_offset.bytes() > 0 {
159 addr_ops.push(op_plus_uconst());
160 addr_ops.push(direct_offset.bytes() as i64);
161 }
162 for &offset in indirect_offsets {
163 addr_ops.push(op_deref());
164 if offset.bytes() > 0 {
165 addr_ops.push(op_plus_uconst());
166 addr_ops.push(offset.bytes() as i64);
167 }
168 }
169
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100170 unsafe {
171 // FIXME(eddyb) replace `llvm.dbg.declare` with `llvm.dbg.addr`.
172 llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100173 DIB(self.cx()),
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100174 variable_alloca,
175 dbg_var,
176 addr_ops.as_ptr(),
177 addr_ops.len() as c_uint,
178 dbg_loc,
179 self.llbb(),
180 );
181 }
182 }
183
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100184 fn set_dbg_loc(&mut self, dbg_loc: &'ll DILocation) {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100185 unsafe {
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100186 let dbg_loc_as_llval = llvm::LLVMRustMetadataAsValue(self.cx().llcx, dbg_loc);
187 llvm::LLVMSetCurrentDebugLocation(self.llbuilder, dbg_loc_as_llval);
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100188 }
189 }
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100190
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100191 fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
192 gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
193 }
194
195 fn set_var_name(&mut self, value: &'ll Value, name: &str) {
196 // Avoid wasting time if LLVM value names aren't even enabled.
197 if self.sess().fewer_names() {
198 return;
199 }
200
201 // Only function parameters and instructions are local to a function,
202 // don't change the name of anything else (e.g. globals).
203 let param_or_inst = unsafe {
204 llvm::LLVMIsAArgument(value).is_some() || llvm::LLVMIsAInstruction(value).is_some()
205 };
206 if !param_or_inst {
207 return;
208 }
209
210 // Avoid replacing the name if it already exists.
211 // While we could combine the names somehow, it'd
212 // get noisy quick, and the usefulness is dubious.
213 if llvm::get_value_name(value).is_empty() {
214 llvm::set_value_name(value, name.as_bytes());
215 }
216 }
217}
218
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100219/// A source code location used to generate debug information.
220// FIXME(eddyb) rename this to better indicate it's a duplicate of
221// `rustc_span::Loc` rather than `DILocation`, perhaps by making
222// `lookup_char_pos` return the right information instead.
223pub struct DebugLoc {
224 /// Information about the original source file.
225 pub file: Lrc<SourceFile>,
226 /// The (1-based) line number.
Chris Wailese3116c42021-07-13 14:40:48 -0700227 pub line: u32,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100228 /// The (1-based) column number.
Chris Wailese3116c42021-07-13 14:40:48 -0700229 pub col: u32,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100230}
231
232impl CodegenCx<'ll, '_> {
233 /// Looks up debug source information about a `BytePos`.
234 // FIXME(eddyb) rename this to better indicate it's a duplicate of
235 // `lookup_char_pos` rather than `dbg_loc`, perhaps by making
236 // `lookup_char_pos` return the right information instead.
237 pub fn lookup_debug_loc(&self, pos: BytePos) -> DebugLoc {
238 let (file, line, col) = match self.sess().source_map().lookup_line(pos) {
239 Ok(SourceFileAndLine { sf: file, line }) => {
240 let line_pos = file.line_begin_pos(pos);
241
242 // Use 1-based indexing.
243 let line = (line + 1) as u32;
244 let col = (pos - line_pos).to_u32() + 1;
245
Chris Wailese3116c42021-07-13 14:40:48 -0700246 (file, line, col)
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100247 }
Chris Wailese3116c42021-07-13 14:40:48 -0700248 Err(file) => (file, UNKNOWN_LINE_NUMBER, UNKNOWN_COLUMN_NUMBER),
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100249 };
250
251 // For MSVC, omit the column number.
252 // Otherwise, emit it. This mimics clang behaviour.
253 // See discussion in https://github.com/rust-lang/rust/issues/42921
254 if self.sess().target.is_like_msvc {
Chris Wailese3116c42021-07-13 14:40:48 -0700255 DebugLoc { file, line, col: UNKNOWN_COLUMN_NUMBER }
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100256 } else {
257 DebugLoc { file, line, col }
258 }
259 }
260}
261
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100262impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> {
263 fn create_function_debug_context(
264 &self,
265 instance: Instance<'tcx>,
266 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
267 llfn: &'ll Value,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100268 mir: &mir::Body<'tcx>,
269 ) -> Option<FunctionDebugContext<&'ll DIScope, &'ll DILocation>> {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100270 if self.sess().opts.debuginfo == DebugInfo::None {
271 return None;
272 }
273
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100274 // Initialize fn debug context (including scopes).
275 // FIXME(eddyb) figure out a way to not need `Option` for `dbg_scope`.
276 let empty_scope = DebugScope {
277 dbg_scope: None,
278 inlined_at: None,
279 file_start_pos: BytePos(0),
280 file_end_pos: BytePos(0),
281 };
282 let mut fn_debug_context =
283 FunctionDebugContext { scopes: IndexVec::from_elem(empty_scope, &mir.source_scopes) };
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100284
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100285 // Fill in all the scopes, with the information from the MIR body.
286 compute_mir_scopes(
287 self,
288 instance,
289 mir,
290 self.dbg_scope_fn(instance, fn_abi, Some(llfn)),
291 &mut fn_debug_context,
292 );
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100293
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100294 Some(fn_debug_context)
295 }
296
297 fn dbg_scope_fn(
298 &self,
299 instance: Instance<'tcx>,
300 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
301 maybe_definition_llfn: Option<&'ll Value>,
302 ) -> &'ll DIScope {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100303 let def_id = instance.def_id();
304 let containing_scope = get_containing_scope(self, instance);
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100305 let span = self.tcx.def_span(def_id);
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100306 let loc = self.lookup_debug_loc(span.lo());
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100307 let file_metadata = file_metadata(self, &loc.file);
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100308
309 let function_type_metadata = unsafe {
310 let fn_signature = get_function_signature(self, fn_abi);
311 llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(self), fn_signature)
312 };
313
314 // Find the enclosing function, in case this is a closure.
315 let def_key = self.tcx().def_key(def_id);
316 let mut name = def_key.disambiguated_data.data.to_string();
317
318 let enclosing_fn_def_id = self.tcx().closure_base_def_id(def_id);
319
320 // Get_template_parameters() will append a `<...>` clause to the function
321 // name if necessary.
322 let generics = self.tcx().generics_of(enclosing_fn_def_id);
323 let substs = instance.substs.truncate_to(self.tcx(), generics);
324 let template_parameters = get_template_parameters(self, &generics, substs, &mut name);
325
326 let linkage_name = &mangled_name_of_instance(self, instance).name;
327 // Omit the linkage_name if it is the same as subprogram name.
328 let linkage_name = if &name == linkage_name { "" } else { linkage_name };
329
330 // FIXME(eddyb) does this need to be separate from `loc.line` for some reason?
331 let scope_line = loc.line;
332
333 let mut flags = DIFlags::FlagPrototyped;
334
335 if fn_abi.ret.layout.abi.is_uninhabited() {
336 flags |= DIFlags::FlagNoReturn;
337 }
338
339 let mut spflags = DISPFlags::SPFlagDefinition;
340 if is_node_local_to_unit(self, def_id) {
341 spflags |= DISPFlags::SPFlagLocalToUnit;
342 }
343 if self.sess().opts.optimize != config::OptLevel::No {
344 spflags |= DISPFlags::SPFlagOptimized;
345 }
346 if let Some((id, _)) = self.tcx.entry_fn(LOCAL_CRATE) {
Chris Wailes32f78352021-07-20 14:04:55 -0700347 if id == def_id {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100348 spflags |= DISPFlags::SPFlagMainSubprogram;
349 }
350 }
351
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100352 unsafe {
353 return llvm::LLVMRustDIBuilderCreateFunction(
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100354 DIB(self),
355 containing_scope,
356 name.as_ptr().cast(),
357 name.len(),
358 linkage_name.as_ptr().cast(),
359 linkage_name.len(),
360 file_metadata,
Chris Wailese3116c42021-07-13 14:40:48 -0700361 loc.line,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100362 function_type_metadata,
Chris Wailese3116c42021-07-13 14:40:48 -0700363 scope_line,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100364 flags,
365 spflags,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100366 maybe_definition_llfn,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100367 template_parameters,
368 None,
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100369 );
370 }
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100371
372 fn get_function_signature<'ll, 'tcx>(
373 cx: &CodegenCx<'ll, 'tcx>,
374 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
375 ) -> &'ll DIArray {
376 if cx.sess().opts.debuginfo == DebugInfo::Limited {
377 return create_DIArray(DIB(cx), &[]);
378 }
379
380 let mut signature = Vec::with_capacity(fn_abi.args.len() + 1);
381
382 // Return type -- llvm::DIBuilder wants this at index 0
383 signature.push(if fn_abi.ret.is_ignore() {
384 None
385 } else {
386 Some(type_metadata(cx, fn_abi.ret.layout.ty, rustc_span::DUMMY_SP))
387 });
388
389 // Arguments types
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100390 if cx.sess().target.is_like_msvc {
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100391 // FIXME(#42800):
392 // There is a bug in MSDIA that leads to a crash when it encounters
393 // a fixed-size array of `u8` or something zero-sized in a
394 // function-type (see #40477).
395 // As a workaround, we replace those fixed-size arrays with a
396 // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
397 // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
398 // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
399 // This transformed type is wrong, but these function types are
400 // already inaccurate due to ABI adjustments (see #42800).
401 signature.extend(fn_abi.args.iter().map(|arg| {
402 let t = arg.layout.ty;
403 let t = match t.kind() {
404 ty::Array(ct, _)
405 if (*ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() =>
406 {
407 cx.tcx.mk_imm_ptr(ct)
408 }
409 _ => t,
410 };
411 Some(type_metadata(cx, t, rustc_span::DUMMY_SP))
412 }));
413 } else {
414 signature.extend(
415 fn_abi
416 .args
417 .iter()
418 .map(|arg| Some(type_metadata(cx, arg.layout.ty, rustc_span::DUMMY_SP))),
419 );
420 }
421
422 create_DIArray(DIB(cx), &signature[..])
423 }
424
425 fn get_template_parameters<'ll, 'tcx>(
426 cx: &CodegenCx<'ll, 'tcx>,
427 generics: &ty::Generics,
428 substs: SubstsRef<'tcx>,
429 name_to_append_suffix_to: &mut String,
430 ) -> &'ll DIArray {
431 if substs.types().next().is_none() {
432 return create_DIArray(DIB(cx), &[]);
433 }
434
435 name_to_append_suffix_to.push('<');
436 for (i, actual_type) in substs.types().enumerate() {
437 if i != 0 {
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100438 name_to_append_suffix_to.push(',');
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100439 }
440
441 let actual_type =
442 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
443 // Add actual type name to <...> clause of function name
444 let actual_type_name = compute_debuginfo_type_name(cx.tcx(), actual_type, true);
445 name_to_append_suffix_to.push_str(&actual_type_name[..]);
446 }
447 name_to_append_suffix_to.push('>');
448
449 // Again, only create type information if full debuginfo is enabled
450 let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
451 let names = get_parameter_names(cx, generics);
Chris Wailes32f78352021-07-20 14:04:55 -0700452 iter::zip(substs, names)
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100453 .filter_map(|(kind, name)| {
454 if let GenericArgKind::Type(ty) = kind.unpack() {
455 let actual_type =
456 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
457 let actual_type_metadata =
458 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
459 let name = name.as_str();
460 Some(unsafe {
461 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
462 DIB(cx),
463 None,
464 name.as_ptr().cast(),
465 name.len(),
466 actual_type_metadata,
467 ))
468 })
469 } else {
470 None
471 }
472 })
473 .collect()
474 } else {
475 vec![]
476 };
477
478 create_DIArray(DIB(cx), &template_params[..])
479 }
480
481 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
Chris Wailese3116c42021-07-13 14:40:48 -0700482 let mut names = generics.parent.map_or_else(Vec::new, |def_id| {
483 get_parameter_names(cx, cx.tcx.generics_of(def_id))
484 });
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100485 names.extend(generics.params.iter().map(|param| param.name));
486 names
487 }
488
489 fn get_containing_scope<'ll, 'tcx>(
490 cx: &CodegenCx<'ll, 'tcx>,
491 instance: Instance<'tcx>,
492 ) -> &'ll DIScope {
493 // First, let's see if this is a method within an inherent impl. Because
494 // if yes, we want to make the result subroutine DIE a child of the
495 // subroutine's self-type.
496 let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
497 // If the method does *not* belong to a trait, proceed
498 if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
499 let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
500 instance.substs,
501 ty::ParamEnv::reveal_all(),
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100502 cx.tcx.type_of(impl_def_id),
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100503 );
504
505 // Only "class" methods are generally understood by LLVM,
506 // so avoid methods on other types (e.g., `<*mut T>::null`).
507 match impl_self_ty.kind() {
508 ty::Adt(def, ..) if !def.is_box() => {
509 // Again, only create type information if full debuginfo is enabled
510 if cx.sess().opts.debuginfo == DebugInfo::Full
511 && !impl_self_ty.needs_subst()
512 {
513 Some(type_metadata(cx, impl_self_ty, rustc_span::DUMMY_SP))
514 } else {
515 Some(namespace::item_namespace(cx, def.did))
516 }
517 }
518 _ => None,
519 }
520 } else {
521 // For trait method impls we still use the "parallel namespace"
522 // strategy
523 None
524 }
525 });
526
527 self_type.unwrap_or_else(|| {
528 namespace::item_namespace(
529 cx,
530 DefId {
531 krate: instance.def_id().krate,
532 index: cx
533 .tcx
534 .def_key(instance.def_id())
535 .parent
536 .expect("get_containing_scope: missing parent?"),
537 },
538 )
539 })
540 }
541 }
542
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100543 fn dbg_loc(
544 &self,
545 scope: &'ll DIScope,
546 inlined_at: Option<&'ll DILocation>,
547 span: Span,
548 ) -> &'ll DILocation {
549 let DebugLoc { line, col, .. } = self.lookup_debug_loc(span.lo());
550
Chris Wailese3116c42021-07-13 14:40:48 -0700551 unsafe { llvm::LLVMRustDIBuilderCreateDebugLocation(line, col, scope, inlined_at) }
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100552 }
553
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100554 fn create_vtable_metadata(&self, ty: Ty<'tcx>, vtable: Self::Value) {
555 metadata::create_vtable_metadata(self, ty, vtable)
556 }
557
558 fn extend_scope_to_file(
559 &self,
560 scope_metadata: &'ll DIScope,
561 file: &rustc_span::SourceFile,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100562 ) -> &'ll DILexicalBlock {
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100563 metadata::extend_scope_to_file(&self, scope_metadata, file)
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100564 }
565
566 fn debuginfo_finalize(&self) {
567 finalize(self)
568 }
569
570 // FIXME(eddyb) find a common convention for all of the debuginfo-related
571 // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
572 fn create_dbg_var(
573 &self,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100574 variable_name: Symbol,
575 variable_type: Ty<'tcx>,
576 scope_metadata: &'ll DIScope,
577 variable_kind: VariableKind,
578 span: Span,
579 ) -> &'ll DIVariable {
580 let loc = self.lookup_debug_loc(span.lo());
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100581 let file_metadata = file_metadata(self, &loc.file);
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100582
583 let type_metadata = type_metadata(self, variable_type, span);
584
585 let (argument_index, dwarf_tag) = match variable_kind {
586 ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
587 LocalVariable => (0, DW_TAG_auto_variable),
588 };
589 let align = self.align_of(variable_type);
590
591 let name = variable_name.as_str();
592 unsafe {
593 llvm::LLVMRustDIBuilderCreateVariable(
594 DIB(self),
595 dwarf_tag,
596 scope_metadata,
597 name.as_ptr().cast(),
598 name.len(),
599 file_metadata,
Chris Wailese3116c42021-07-13 14:40:48 -0700600 loc.line,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100601 type_metadata,
602 true,
603 DIFlags::FlagZero,
604 argument_index,
605 align.bytes() as u32,
606 )
607 }
608 }
609}