]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/debuginfo/mod.rs
Generalized base.rs#call_memcpy and everything that it uses
[rust.git] / src / librustc_codegen_llvm / 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::debuginfo::{DIFile, DIType, DIScope, DIBuilder, DISubprogram, DIArray, DIFlags};
25 use rustc::hir::CodegenFnAttrFlags;
26 use rustc::hir::def_id::{DefId, CrateNum};
27 use rustc::ty::subst::{Substs, UnpackedKind};
28
29 use abi::Abi;
30 use common::CodegenCx;
31 use builder::Builder;
32 use monomorphize::Instance;
33 use rustc::ty::{self, ParamEnv, Ty, InstanceDef};
34 use rustc::mir;
35 use rustc::session::config::{self, DebugInfo};
36 use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet};
37 use rustc_data_structures::small_c_str::SmallCStr;
38 use value::Value;
39
40 use libc::c_uint;
41 use std::cell::{Cell, RefCell};
42 use std::ffi::CString;
43
44 use syntax_pos::{self, Span, Pos};
45 use syntax::ast;
46 use syntax::symbol::{Symbol, InternedString};
47 use rustc::ty::layout::{self, LayoutOf};
48 use traits::BuilderMethods;
49
50 pub mod gdb;
51 mod utils;
52 mod namespace;
53 mod type_names;
54 pub mod metadata;
55 mod create_scope_map;
56 mod source_loc;
57
58 pub use self::create_scope_map::{create_mir_scopes, MirDebugScope};
59 pub use self::source_loc::start_emitting_source_locations;
60 pub use self::metadata::create_global_var_metadata;
61 pub use self::metadata::create_vtable_metadata;
62 pub use self::metadata::extend_scope_to_file;
63 pub use self::source_loc::set_source_location;
64
65 #[allow(non_upper_case_globals)]
66 const DW_TAG_auto_variable: c_uint = 0x100;
67 #[allow(non_upper_case_globals)]
68 const DW_TAG_arg_variable: c_uint = 0x101;
69
70 /// A context object for maintaining all state needed by the debuginfo module.
71 pub struct CrateDebugContext<'a, 'tcx> {
72     llcontext: &'a llvm::Context,
73     llmod: &'a llvm::Module,
74     builder: &'a mut DIBuilder<'a>,
75     created_files: RefCell<FxHashMap<(Symbol, Symbol), &'a DIFile>>,
76     created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), &'a DIType>>,
77
78     type_map: RefCell<TypeMap<'a, 'tcx>>,
79     namespace_map: RefCell<DefIdMap<&'a DIScope>>,
80
81     // This collection is used to assert that composite types (structs, enums,
82     // ...) have their members only set once:
83     composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
84 }
85
86 impl Drop for CrateDebugContext<'a, 'tcx> {
87     fn drop(&mut self) {
88         unsafe {
89             llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
90         }
91     }
92 }
93
94 impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
95     pub fn new(llmod: &'a llvm::Module) -> Self {
96         debug!("CrateDebugContext::new");
97         let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
98         // DIBuilder inherits context from the module, so we'd better use the same one
99         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
100         CrateDebugContext {
101             llcontext,
102             llmod,
103             builder,
104             created_files: Default::default(),
105             created_enum_disr_types: Default::default(),
106             type_map: Default::default(),
107             namespace_map: RefCell::new(DefIdMap()),
108             composite_types_completed: Default::default(),
109         }
110     }
111 }
112
113 pub enum FunctionDebugContext<'ll> {
114     RegularContext(FunctionDebugContextData<'ll>),
115     DebugInfoDisabled,
116     FunctionWithoutDebugInfo,
117 }
118
119 impl FunctionDebugContext<'ll> {
120     pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData<'ll> {
121         match *self {
122             FunctionDebugContext::RegularContext(ref data) => data,
123             FunctionDebugContext::DebugInfoDisabled => {
124                 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
125             }
126             FunctionDebugContext::FunctionWithoutDebugInfo => {
127                 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
128             }
129         }
130     }
131
132     fn debuginfo_disabled_message() -> &'static str {
133         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
134     }
135
136     fn should_be_ignored_message() -> &'static str {
137         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
138          ignored by debug info!"
139     }
140 }
141
142 pub struct FunctionDebugContextData<'ll> {
143     fn_metadata: &'ll DISubprogram,
144     source_locations_enabled: Cell<bool>,
145     pub defining_crate: CrateNum,
146 }
147
148 pub enum VariableAccess<'a, 'll> {
149     // The llptr given is an alloca containing the variable's value
150     DirectVariable { alloca: &'ll Value },
151     // The llptr given is an alloca containing the start of some pointer chain
152     // leading to the variable's content.
153     IndirectVariable { alloca: &'ll Value, address_operations: &'a [i64] }
154 }
155
156 pub enum VariableKind {
157     ArgumentVariable(usize /*index*/),
158     LocalVariable,
159 }
160
161 /// Create any deferred debug metadata nodes
162 pub fn finalize(cx: &CodegenCx) {
163     if cx.dbg_cx.is_none() {
164         return;
165     }
166
167     debug!("finalize");
168
169     if gdb::needs_gdb_debug_scripts_section(cx) {
170         // Add a .debug_gdb_scripts section to this compile-unit. This will
171         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
172         // which activates the Rust pretty printers for binary this section is
173         // contained in.
174         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
175     }
176
177     unsafe {
178         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
179         // Debuginfo generation in LLVM by default uses a higher
180         // version of dwarf than macOS currently understands. We can
181         // instruct LLVM to emit an older version of dwarf, however,
182         // for macOS to understand. For more info see #11352
183         // This can be overridden using --llvm-opts -dwarf-version,N.
184         // Android has the same issue (#22398)
185         if cx.sess().target.target.options.is_like_osx ||
186            cx.sess().target.target.options.is_like_android {
187             llvm::LLVMRustAddModuleFlag(cx.llmod,
188                                         "Dwarf Version\0".as_ptr() as *const _,
189                                         2)
190         }
191
192         // Indicate that we want CodeView debug information on MSVC
193         if cx.sess().target.target.options.is_like_msvc {
194             llvm::LLVMRustAddModuleFlag(cx.llmod,
195                                         "CodeView\0".as_ptr() as *const _,
196                                         1)
197         }
198
199         // Prevent bitcode readers from deleting the debug info.
200         let ptr = "Debug Info Version\0".as_ptr();
201         llvm::LLVMRustAddModuleFlag(cx.llmod, ptr as *const _,
202                                     llvm::LLVMRustDebugMetadataVersion());
203     };
204 }
205
206 /// Creates the function-specific debug context.
207 ///
208 /// Returns the FunctionDebugContext for the function which holds state needed
209 /// for debug info creation. The function may also return another variant of the
210 /// FunctionDebugContext enum which indicates why no debuginfo should be created
211 /// for the function.
212 pub fn create_function_debug_context(
213     cx: &CodegenCx<'ll, 'tcx>,
214     instance: Instance<'tcx>,
215     sig: ty::FnSig<'tcx>,
216     llfn: &'ll Value,
217     mir: &mir::Mir,
218 ) -> FunctionDebugContext<'ll> {
219     if cx.sess().opts.debuginfo == DebugInfo::None {
220         return FunctionDebugContext::DebugInfoDisabled;
221     }
222
223     if let InstanceDef::Item(def_id) = instance.def {
224         if cx.tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
225             return FunctionDebugContext::FunctionWithoutDebugInfo;
226         }
227     }
228
229     let span = mir.span;
230
231     // This can be the case for functions inlined from another crate
232     if span.is_dummy() {
233         // FIXME(simulacrum): Probably can't happen; remove.
234         return FunctionDebugContext::FunctionWithoutDebugInfo;
235     }
236
237     let def_id = instance.def_id();
238     let containing_scope = get_containing_scope(cx, instance);
239     let loc = span_start(cx, span);
240     let file_metadata = file_metadata(cx, &loc.file.name, def_id.krate);
241
242     let function_type_metadata = unsafe {
243         let fn_signature = get_function_signature(cx, sig);
244         llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
245     };
246
247     // Find the enclosing function, in case this is a closure.
248     let def_key = cx.tcx.def_key(def_id);
249     let mut name = def_key.disambiguated_data.data.to_string();
250
251     let enclosing_fn_def_id = cx.tcx.closure_base_def_id(def_id);
252
253     // Get_template_parameters() will append a `<...>` clause to the function
254     // name if necessary.
255     let generics = cx.tcx.generics_of(enclosing_fn_def_id);
256     let substs = instance.substs.truncate_to(cx.tcx, generics);
257     let template_parameters = get_template_parameters(cx,
258                                                       &generics,
259                                                       substs,
260                                                       file_metadata,
261                                                       &mut name);
262
263     // Get the linkage_name, which is just the symbol name
264     let linkage_name = mangled_name_of_instance(cx, instance);
265
266     let scope_line = span_start(cx, span).line;
267     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
268
269     let function_name = CString::new(name).unwrap();
270     let linkage_name = SmallCStr::new(&linkage_name.as_str());
271
272     let mut flags = DIFlags::FlagPrototyped;
273
274     let local_id = cx.tcx.hir.as_local_node_id(def_id);
275     if let Some((id, _, _)) = *cx.sess().entry_fn.borrow() {
276         if local_id == Some(id) {
277             flags |= DIFlags::FlagMainSubprogram;
278         }
279     }
280
281     if cx.layout_of(sig.output()).abi.is_uninhabited() {
282         flags |= DIFlags::FlagNoReturn;
283     }
284
285     let fn_metadata = unsafe {
286         llvm::LLVMRustDIBuilderCreateFunction(
287             DIB(cx),
288             containing_scope,
289             function_name.as_ptr(),
290             linkage_name.as_ptr(),
291             file_metadata,
292             loc.line as c_uint,
293             function_type_metadata,
294             is_local_to_unit,
295             true,
296             scope_line as c_uint,
297             flags,
298             cx.sess().opts.optimize != config::OptLevel::No,
299             llfn,
300             template_parameters,
301             None)
302     };
303
304     // Initialize fn debug context (including scope map and namespace map)
305     let fn_debug_context = FunctionDebugContextData {
306         fn_metadata,
307         source_locations_enabled: Cell::new(false),
308         defining_crate: def_id.krate,
309     };
310
311     return FunctionDebugContext::RegularContext(fn_debug_context);
312
313     fn get_function_signature(
314         cx: &CodegenCx<'ll, 'tcx>,
315         sig: ty::FnSig<'tcx>,
316     ) -> &'ll DIArray {
317         if cx.sess().opts.debuginfo == DebugInfo::Limited {
318             return create_DIArray(DIB(cx), &[]);
319         }
320
321         let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
322
323         // Return type -- llvm::DIBuilder wants this at index 0
324         signature.push(match sig.output().sty {
325             ty::Tuple(ref tys) if tys.is_empty() => None,
326             _ => Some(type_metadata(cx, sig.output(), syntax_pos::DUMMY_SP))
327         });
328
329         let inputs = if sig.abi == Abi::RustCall {
330             &sig.inputs()[..sig.inputs().len() - 1]
331         } else {
332             sig.inputs()
333         };
334
335         // Arguments types
336         if cx.sess().target.target.options.is_like_msvc {
337             // FIXME(#42800):
338             // There is a bug in MSDIA that leads to a crash when it encounters
339             // a fixed-size array of `u8` or something zero-sized in a
340             // function-type (see #40477).
341             // As a workaround, we replace those fixed-size arrays with a
342             // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
343             // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
344             // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
345             // This transformed type is wrong, but these function types are
346             // already inaccurate due to ABI adjustments (see #42800).
347             signature.extend(inputs.iter().map(|&t| {
348                 let t = match t.sty {
349                     ty::Array(ct, _)
350                         if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() => {
351                         cx.tcx.mk_imm_ptr(ct)
352                     }
353                     _ => t
354                 };
355                 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
356             }));
357         } else {
358             signature.extend(inputs.iter().map(|t| {
359                 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
360             }));
361         }
362
363         if sig.abi == Abi::RustCall && !sig.inputs().is_empty() {
364             if let ty::Tuple(args) = sig.inputs()[sig.inputs().len() - 1].sty {
365                 signature.extend(
366                     args.iter().map(|argument_type| {
367                         Some(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP))
368                     })
369                 );
370             }
371         }
372
373         create_DIArray(DIB(cx), &signature[..])
374     }
375
376     fn get_template_parameters(
377         cx: &CodegenCx<'ll, 'tcx>,
378         generics: &ty::Generics,
379         substs: &Substs<'tcx>,
380         file_metadata: &'ll DIFile,
381         name_to_append_suffix_to: &mut String,
382     ) -> &'ll DIArray {
383         if substs.types().next().is_none() {
384             return create_DIArray(DIB(cx), &[]);
385         }
386
387         name_to_append_suffix_to.push('<');
388         for (i, actual_type) in substs.types().enumerate() {
389             if i != 0 {
390                 name_to_append_suffix_to.push_str(",");
391             }
392
393             let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
394             // Add actual type name to <...> clause of function name
395             let actual_type_name = compute_debuginfo_type_name(cx,
396                                                                actual_type,
397                                                                true);
398             name_to_append_suffix_to.push_str(&actual_type_name[..]);
399         }
400         name_to_append_suffix_to.push('>');
401
402         // Again, only create type information if full debuginfo is enabled
403         let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
404             let names = get_parameter_names(cx, generics);
405             substs.iter().zip(names).filter_map(|(kind, name)| {
406                 if let UnpackedKind::Type(ty) = kind.unpack() {
407                     let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
408                     let actual_type_metadata =
409                         type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
410                     let name = SmallCStr::new(&name.as_str());
411                     Some(unsafe {
412                         Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
413                             DIB(cx),
414                             None,
415                             name.as_ptr(),
416                             actual_type_metadata,
417                             file_metadata,
418                             0,
419                             0,
420                         ))
421                     })
422                 } else {
423                     None
424                 }
425             }).collect()
426         } else {
427             vec![]
428         };
429
430         create_DIArray(DIB(cx), &template_params[..])
431     }
432
433     fn get_parameter_names(cx: &CodegenCx,
434                            generics: &ty::Generics)
435                            -> Vec<InternedString> {
436         let mut names = generics.parent.map_or(vec![], |def_id| {
437             get_parameter_names(cx, cx.tcx.generics_of(def_id))
438         });
439         names.extend(generics.params.iter().map(|param| param.name));
440         names
441     }
442
443     fn get_containing_scope(
444         cx: &CodegenCx<'ll, 'tcx>,
445         instance: Instance<'tcx>,
446     ) -> &'ll DIScope {
447         // First, let's see if this is a method within an inherent impl. Because
448         // if yes, we want to make the result subroutine DIE a child of the
449         // subroutine's self-type.
450         let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
451             // If the method does *not* belong to a trait, proceed
452             if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
453                 let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
454                     instance.substs,
455                     ty::ParamEnv::reveal_all(),
456                     &cx.tcx.type_of(impl_def_id),
457                 );
458
459                 // Only "class" methods are generally understood by LLVM,
460                 // so avoid methods on other types (e.g. `<*mut T>::null`).
461                 match impl_self_ty.sty {
462                     ty::Adt(def, ..) if !def.is_box() => {
463                         Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
464                     }
465                     _ => None
466                 }
467             } else {
468                 // For trait method impls we still use the "parallel namespace"
469                 // strategy
470                 None
471             }
472         });
473
474         self_type.unwrap_or_else(|| {
475             namespace::item_namespace(cx, DefId {
476                 krate: instance.def_id().krate,
477                 index: cx.tcx
478                          .def_key(instance.def_id())
479                          .parent
480                          .expect("get_containing_scope: missing parent?")
481             })
482         })
483     }
484 }
485
486 pub fn declare_local(
487     bx: &Builder<'a, 'll, 'tcx>,
488     dbg_context: &FunctionDebugContext<'ll>,
489     variable_name: ast::Name,
490     variable_type: Ty<'tcx>,
491     scope_metadata: &'ll DIScope,
492     variable_access: VariableAccess<'_, 'll>,
493     variable_kind: VariableKind,
494     span: Span,
495 ) {
496     assert!(!dbg_context.get_ref(span).source_locations_enabled.get());
497     let cx = bx.cx;
498
499     let file = span_start(cx, span).file;
500     let file_metadata = file_metadata(cx,
501                                       &file.name,
502                                       dbg_context.get_ref(span).defining_crate);
503
504     let loc = span_start(cx, span);
505     let type_metadata = type_metadata(cx, variable_type, span);
506
507     let (argument_index, dwarf_tag) = match variable_kind {
508         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
509         LocalVariable => (0, DW_TAG_auto_variable)
510     };
511     let align = cx.align_of(variable_type);
512
513     let name = SmallCStr::new(&variable_name.as_str());
514     match (variable_access, &[][..]) {
515         (DirectVariable { alloca }, address_operations) |
516         (IndirectVariable {alloca, address_operations}, _) => {
517             let metadata = unsafe {
518                 llvm::LLVMRustDIBuilderCreateVariable(
519                     DIB(cx),
520                     dwarf_tag,
521                     scope_metadata,
522                     name.as_ptr(),
523                     file_metadata,
524                     loc.line as c_uint,
525                     type_metadata,
526                     cx.sess().opts.optimize != config::OptLevel::No,
527                     DIFlags::FlagZero,
528                     argument_index,
529                     align.abi() as u32,
530                 )
531             };
532             source_loc::set_debug_location(bx,
533                 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
534             unsafe {
535                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bx.llbuilder);
536                 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
537                     DIB(cx),
538                     alloca,
539                     metadata,
540                     address_operations.as_ptr(),
541                     address_operations.len() as c_uint,
542                     debug_loc,
543                     bx.llbb());
544
545                 llvm::LLVMSetInstDebugLocation(bx.llbuilder, instr);
546             }
547             source_loc::set_debug_location(bx, UnknownLocation);
548         }
549     }
550 }