]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/mod.rs
Add invalid unary operator usage error code
[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_item;
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::{self, CrateContext};
31 use builder::Builder;
32 use monomorphize::Instance;
33 use rustc::ty::{self, Ty};
34 use rustc::mir;
35 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
36 use 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;
46 use rustc::ty::layout;
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::extend_scope_to_file;
60 pub use self::source_loc::set_source_location;
61
62 #[allow(non_upper_case_globals)]
63 const DW_TAG_auto_variable: c_uint = 0x100;
64 #[allow(non_upper_case_globals)]
65 const DW_TAG_arg_variable: c_uint = 0x101;
66
67 /// A context object for maintaining all state needed by the debuginfo module.
68 pub struct CrateDebugContext<'tcx> {
69     llcontext: ContextRef,
70     builder: DIBuilderRef,
71     created_files: RefCell<FxHashMap<(Symbol, Symbol), DIFile>>,
72     created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Integer), DIType>>,
73
74     type_map: RefCell<TypeMap<'tcx>>,
75     namespace_map: RefCell<DefIdMap<DIScope>>,
76
77     // This collection is used to assert that composite types (structs, enums,
78     // ...) have their members only set once:
79     composite_types_completed: RefCell<FxHashSet<DIType>>,
80 }
81
82 impl<'tcx> CrateDebugContext<'tcx> {
83     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
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: llcontext,
90             builder: builder,
91             created_files: RefCell::new(FxHashMap()),
92             created_enum_disr_types: RefCell::new(FxHashMap()),
93             type_map: RefCell::new(TypeMap::new()),
94             namespace_map: RefCell::new(DefIdMap()),
95             composite_types_completed: RefCell::new(FxHashSet()),
96         }
97     }
98 }
99
100 pub enum FunctionDebugContext {
101     RegularContext(FunctionDebugContextData),
102     DebugInfoDisabled,
103     FunctionWithoutDebugInfo,
104 }
105
106 impl FunctionDebugContext {
107     pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData {
108         match *self {
109             FunctionDebugContext::RegularContext(ref data) => data,
110             FunctionDebugContext::DebugInfoDisabled => {
111                 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
112             }
113             FunctionDebugContext::FunctionWithoutDebugInfo => {
114                 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
115             }
116         }
117     }
118
119     fn debuginfo_disabled_message() -> &'static str {
120         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
121     }
122
123     fn should_be_ignored_message() -> &'static str {
124         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
125          ignored by debug info!"
126     }
127 }
128
129 pub struct FunctionDebugContextData {
130     fn_metadata: DISubprogram,
131     source_locations_enabled: Cell<bool>,
132     pub defining_crate: CrateNum,
133 }
134
135 pub enum VariableAccess<'a> {
136     // The llptr given is an alloca containing the variable's value
137     DirectVariable { alloca: ValueRef },
138     // The llptr given is an alloca containing the start of some pointer chain
139     // leading to the variable's content.
140     IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
141 }
142
143 pub enum VariableKind {
144     ArgumentVariable(usize /*index*/),
145     LocalVariable,
146     CapturedVariable,
147 }
148
149 /// Create any deferred debug metadata nodes
150 pub fn finalize(cx: &CrateContext) {
151     if cx.dbg_cx().is_none() {
152         return;
153     }
154
155     debug!("finalize");
156
157     if gdb::needs_gdb_debug_scripts_section(cx) {
158         // Add a .debug_gdb_scripts section to this compile-unit. This will
159         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
160         // which activates the Rust pretty printers for binary this section is
161         // contained in.
162         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
163     }
164
165     unsafe {
166         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
167         llvm::LLVMRustDIBuilderDispose(DIB(cx));
168         // Debuginfo generation in LLVM by default uses a higher
169         // version of dwarf than macOS currently understands. We can
170         // instruct LLVM to emit an older version of dwarf, however,
171         // for macOS to understand. For more info see #11352
172         // This can be overridden using --llvm-opts -dwarf-version,N.
173         // Android has the same issue (#22398)
174         if cx.sess().target.target.options.is_like_osx ||
175            cx.sess().target.target.options.is_like_android {
176             llvm::LLVMRustAddModuleFlag(cx.llmod(),
177                                         "Dwarf Version\0".as_ptr() as *const _,
178                                         2)
179         }
180
181         // Indicate that we want CodeView debug information on MSVC
182         if cx.sess().target.target.options.is_like_msvc {
183             llvm::LLVMRustAddModuleFlag(cx.llmod(),
184                                         "CodeView\0".as_ptr() as *const _,
185                                         1)
186         }
187
188         // Prevent bitcode readers from deleting the debug info.
189         let ptr = "Debug Info Version\0".as_ptr();
190         llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
191                                     llvm::LLVMRustDebugMetadataVersion());
192     };
193 }
194
195 /// Creates the function-specific debug context.
196 ///
197 /// Returns the FunctionDebugContext for the function which holds state needed
198 /// for debug info creation. The function may also return another variant of the
199 /// FunctionDebugContext enum which indicates why no debuginfo should be created
200 /// for the function.
201 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
202                                                instance: Instance<'tcx>,
203                                                sig: ty::FnSig<'tcx>,
204                                                llfn: ValueRef,
205                                                mir: &mir::Mir) -> FunctionDebugContext {
206     if cx.sess().opts.debuginfo == NoDebugInfo {
207         return FunctionDebugContext::DebugInfoDisabled;
208     }
209
210     for attr in instance.def.attrs(cx.tcx()).iter() {
211         if attr.check_name("no_debug") {
212             return FunctionDebugContext::FunctionWithoutDebugInfo;
213         }
214     }
215
216     let containing_scope = get_containing_scope(cx, instance);
217     let span = mir.span;
218
219     // This can be the case for functions inlined from another crate
220     if span == syntax_pos::DUMMY_SP {
221         // FIXME(simulacrum): Probably can't happen; remove.
222         return FunctionDebugContext::FunctionWithoutDebugInfo;
223     }
224
225     let def_id = instance.def_id();
226     let loc = span_start(cx, span);
227     let file_metadata = file_metadata(cx, &loc.file.name, def_id.krate);
228
229     let function_type_metadata = unsafe {
230         let fn_signature = get_function_signature(cx, sig);
231         llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
232     };
233
234     // Find the enclosing function, in case this is a closure.
235     let def_key = cx.tcx().def_key(def_id);
236     let mut name = def_key.disambiguated_data.data.to_string();
237     let name_len = name.len();
238
239     let enclosing_fn_def_id = cx.tcx().closure_base_def_id(def_id);
240
241     // Get_template_parameters() will append a `<...>` clause to the function
242     // name if necessary.
243     let generics = cx.tcx().generics_of(enclosing_fn_def_id);
244     let substs = instance.substs.truncate_to(cx.tcx(), generics);
245     let template_parameters = get_template_parameters(cx,
246                                                       &generics,
247                                                       substs,
248                                                       file_metadata,
249                                                       &mut name);
250
251     // Build the linkage_name out of the item path and "template" parameters.
252     let linkage_name = mangled_name_of_item(cx, instance.def_id(), &name[name_len..]);
253
254     let scope_line = span_start(cx, span).line;
255
256     let local_id = cx.tcx().hir.as_local_node_id(instance.def_id());
257     let is_local_to_unit = local_id.map_or(false, |id| is_node_local_to_unit(cx, id));
258
259     let function_name = CString::new(name).unwrap();
260     let linkage_name = CString::new(linkage_name).unwrap();
261
262     let mut flags = DIFlags::FlagPrototyped;
263     match *cx.sess().entry_fn.borrow() {
264         Some((id, _)) => {
265             if local_id == Some(id) {
266                 flags = flags | DIFlags::FlagMainSubprogram;
267             }
268         }
269         None => {}
270     };
271
272     let fn_metadata = unsafe {
273         llvm::LLVMRustDIBuilderCreateFunction(
274             DIB(cx),
275             containing_scope,
276             function_name.as_ptr(),
277             linkage_name.as_ptr(),
278             file_metadata,
279             loc.line as c_uint,
280             function_type_metadata,
281             is_local_to_unit,
282             true,
283             scope_line as c_uint,
284             flags,
285             cx.sess().opts.optimize != config::OptLevel::No,
286             llfn,
287             template_parameters,
288             ptr::null_mut())
289     };
290
291     // Initialize fn debug context (including scope map and namespace map)
292     let fn_debug_context = FunctionDebugContextData {
293         fn_metadata: fn_metadata,
294         source_locations_enabled: Cell::new(false),
295         defining_crate: def_id.krate,
296     };
297
298     return FunctionDebugContext::RegularContext(fn_debug_context);
299
300     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
301                                         sig: ty::FnSig<'tcx>) -> DIArray {
302         if cx.sess().opts.debuginfo == LimitedDebugInfo {
303             return create_DIArray(DIB(cx), &[]);
304         }
305
306         let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
307
308         // Return type -- llvm::DIBuilder wants this at index 0
309         signature.push(match sig.output().sty {
310             ty::TyTuple(ref tys, _) if tys.is_empty() => ptr::null_mut(),
311             _ => type_metadata(cx, sig.output(), syntax_pos::DUMMY_SP)
312         });
313
314         let inputs = if sig.abi == Abi::RustCall {
315             &sig.inputs()[..sig.inputs().len() - 1]
316         } else {
317             sig.inputs()
318         };
319
320         // Arguments types
321         for &argument_type in inputs {
322             signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
323         }
324
325         if sig.abi == Abi::RustCall && !sig.inputs().is_empty() {
326             if let ty::TyTuple(args, _) = sig.inputs()[sig.inputs().len() - 1].sty {
327                 for &argument_type in args {
328                     signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
329                 }
330             }
331         }
332
333         return create_DIArray(DIB(cx), &signature[..]);
334     }
335
336     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
337                                          generics: &ty::Generics,
338                                          substs: &Substs<'tcx>,
339                                          file_metadata: DIFile,
340                                          name_to_append_suffix_to: &mut String)
341                                          -> DIArray
342     {
343         if substs.types().next().is_none() {
344             return create_DIArray(DIB(cx), &[]);
345         }
346
347         name_to_append_suffix_to.push('<');
348         for (i, actual_type) in substs.types().enumerate() {
349             if i != 0 {
350                 name_to_append_suffix_to.push_str(",");
351             }
352
353             let actual_type = cx.tcx().normalize_associated_type(&actual_type);
354             // Add actual type name to <...> clause of function name
355             let actual_type_name = compute_debuginfo_type_name(cx,
356                                                                actual_type,
357                                                                true);
358             name_to_append_suffix_to.push_str(&actual_type_name[..]);
359         }
360         name_to_append_suffix_to.push('>');
361
362         // Again, only create type information if full debuginfo is enabled
363         let template_params: Vec<_> = if cx.sess().opts.debuginfo == FullDebugInfo {
364             let names = get_type_parameter_names(cx, generics);
365             substs.types().zip(names).map(|(ty, name)| {
366                 let actual_type = cx.tcx().normalize_associated_type(&ty);
367                 let actual_type_metadata = type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
368                 let name = CString::new(name.as_str().as_bytes()).unwrap();
369                 unsafe {
370                     llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
371                         DIB(cx),
372                         ptr::null_mut(),
373                         name.as_ptr(),
374                         actual_type_metadata,
375                         file_metadata,
376                         0,
377                         0)
378                 }
379             }).collect()
380         } else {
381             vec![]
382         };
383
384         return create_DIArray(DIB(cx), &template_params[..]);
385     }
386
387     fn get_type_parameter_names(cx: &CrateContext, generics: &ty::Generics) -> Vec<ast::Name> {
388         let mut names = generics.parent.map_or(vec![], |def_id| {
389             get_type_parameter_names(cx, cx.tcx().generics_of(def_id))
390         });
391         names.extend(generics.types.iter().map(|param| param.name));
392         names
393     }
394
395     fn get_containing_scope<'ccx, 'tcx>(cx: &CrateContext<'ccx, 'tcx>,
396                                         instance: Instance<'tcx>)
397                                         -> DIScope {
398         // First, let's see if this is a method within an inherent impl. Because
399         // if yes, we want to make the result subroutine DIE a child of the
400         // subroutine's self-type.
401         let self_type = cx.tcx().impl_of_method(instance.def_id()).and_then(|impl_def_id| {
402             // If the method does *not* belong to a trait, proceed
403             if cx.tcx().trait_id_of_impl(impl_def_id).is_none() {
404                 let impl_self_ty =
405                     common::def_ty(cx.shared(), impl_def_id, instance.substs);
406
407                 // Only "class" methods are generally understood by LLVM,
408                 // so avoid methods on other types (e.g. `<*mut T>::null`).
409                 match impl_self_ty.sty {
410                     ty::TyAdt(def, ..) if !def.is_box() => {
411                         Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
412                     }
413                     _ => None
414                 }
415             } else {
416                 // For trait method impls we still use the "parallel namespace"
417                 // strategy
418                 None
419             }
420         });
421
422         self_type.unwrap_or_else(|| {
423             namespace::item_namespace(cx, DefId {
424                 krate: instance.def_id().krate,
425                 index: cx.tcx()
426                          .def_key(instance.def_id())
427                          .parent
428                          .expect("get_containing_scope: missing parent?")
429             })
430         })
431     }
432 }
433
434 pub fn declare_local<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
435                                dbg_context: &FunctionDebugContext,
436                                variable_name: ast::Name,
437                                variable_type: Ty<'tcx>,
438                                scope_metadata: DIScope,
439                                variable_access: VariableAccess,
440                                variable_kind: VariableKind,
441                                span: Span) {
442     let cx = bcx.ccx;
443
444     let file = span_start(cx, span).file;
445     let file_metadata = file_metadata(cx,
446                                       &file.name[..],
447                                       dbg_context.get_ref(span).defining_crate);
448
449     let loc = span_start(cx, span);
450     let type_metadata = type_metadata(cx, variable_type, span);
451
452     let (argument_index, dwarf_tag) = match variable_kind {
453         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
454         LocalVariable    |
455         CapturedVariable => (0, DW_TAG_auto_variable)
456     };
457     let align = cx.align_of(variable_type);
458
459     let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
460     match (variable_access, &[][..]) {
461         (DirectVariable { alloca }, address_operations) |
462         (IndirectVariable {alloca, address_operations}, _) => {
463             let metadata = unsafe {
464                 llvm::LLVMRustDIBuilderCreateVariable(
465                     DIB(cx),
466                     dwarf_tag,
467                     scope_metadata,
468                     name.as_ptr(),
469                     file_metadata,
470                     loc.line as c_uint,
471                     type_metadata,
472                     cx.sess().opts.optimize != config::OptLevel::No,
473                     DIFlags::FlagZero,
474                     argument_index,
475                     align,
476                 )
477             };
478             source_loc::set_debug_location(bcx,
479                 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
480             unsafe {
481                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bcx.llbuilder);
482                 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
483                     DIB(cx),
484                     alloca,
485                     metadata,
486                     address_operations.as_ptr(),
487                     address_operations.len() as c_uint,
488                     debug_loc,
489                     bcx.llbb());
490
491                 llvm::LLVMSetInstDebugLocation(bcx.llbuilder, instr);
492             }
493         }
494     }
495
496     match variable_kind {
497         ArgumentVariable(_) | CapturedVariable => {
498             assert!(!dbg_context.get_ref(span).source_locations_enabled.get());
499             source_loc::set_debug_location(bcx, UnknownLocation);
500         }
501         _ => { /* nothing to do */ }
502     }
503 }