]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs
Auto merge of #78833 - CDirkx:parse_prefix, r=dtolnay
[rust.git] / compiler / rustc_codegen_cranelift / src / debuginfo / mod.rs
1 //! Handling of everything related to debuginfo.
2
3 mod emit;
4 mod line_info;
5 mod unwind;
6
7 use crate::prelude::*;
8
9 use rustc_index::vec::IndexVec;
10
11 use cranelift_codegen::entity::EntityRef;
12 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
13 use cranelift_codegen::isa::TargetIsa;
14 use cranelift_codegen::ValueLocRange;
15
16 use gimli::write::{
17     Address, AttributeValue, DwarfUnit, Expression, LineProgram, LineString, Location,
18     LocationList, Range, RangeList, UnitEntryId,
19 };
20 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
21
22 pub(crate) use emit::{DebugReloc, DebugRelocName};
23 pub(crate) use unwind::UnwindContext;
24
25 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
26     use rustc_target::abi::Endian;
27
28     match tcx.data_layout.endian {
29         Endian::Big => RunTimeEndian::Big,
30         Endian::Little => RunTimeEndian::Little,
31     }
32 }
33
34 pub(crate) struct DebugContext<'tcx> {
35     tcx: TyCtxt<'tcx>,
36
37     endian: RunTimeEndian,
38
39     dwarf: DwarfUnit,
40     unit_range_list: RangeList,
41
42     clif_types: FxHashMap<Type, UnitEntryId>,
43     types: FxHashMap<Ty<'tcx>, UnitEntryId>,
44 }
45
46 impl<'tcx> DebugContext<'tcx> {
47     pub(crate) fn new(tcx: TyCtxt<'tcx>, isa: &dyn TargetIsa) -> Self {
48         let encoding = Encoding {
49             format: Format::Dwarf32,
50             // TODO: this should be configurable
51             // macOS doesn't seem to support DWARF > 3
52             // 5 version is required for md5 file hash
53             version: if tcx.sess.target.is_like_osx {
54                 3
55             } else {
56                 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
57                 // support it.
58                 4
59             },
60             address_size: isa.frontend_config().pointer_bytes(),
61         };
62
63         let mut dwarf = DwarfUnit::new(encoding);
64
65         // FIXME: how to get version when building out of tree?
66         // Normally this would use option_env!("CFG_VERSION").
67         let producer = format!("cg_clif (rustc {})", "unknown version");
68         let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
69         let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
70             Some(path) => {
71                 let name = path.to_string_lossy().into_owned();
72                 (name, None)
73             }
74             None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
75         };
76
77         let mut line_program = LineProgram::new(
78             encoding,
79             LineEncoding::default(),
80             LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
81             LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
82             file_info,
83         );
84         line_program.file_has_md5 = file_info.is_some();
85
86         dwarf.unit.line_program = line_program;
87
88         {
89             let name = dwarf.strings.add(name);
90             let comp_dir = dwarf.strings.add(comp_dir);
91
92             let root = dwarf.unit.root();
93             let root = dwarf.unit.get_mut(root);
94             root.set(
95                 gimli::DW_AT_producer,
96                 AttributeValue::StringRef(dwarf.strings.add(producer)),
97             );
98             root.set(
99                 gimli::DW_AT_language,
100                 AttributeValue::Language(gimli::DW_LANG_Rust),
101             );
102             root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
103             root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
104             root.set(
105                 gimli::DW_AT_low_pc,
106                 AttributeValue::Address(Address::Constant(0)),
107             );
108         }
109
110         DebugContext {
111             tcx,
112
113             endian: target_endian(tcx),
114
115             dwarf,
116             unit_range_list: RangeList(Vec::new()),
117
118             clif_types: FxHashMap::default(),
119             types: FxHashMap::default(),
120         }
121     }
122
123     fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
124         if let Some(type_id) = self.clif_types.get(&ty) {
125             return *type_id;
126         }
127
128         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
129
130         let primitive = |dwarf: &mut DwarfUnit, ate| {
131             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
132             let type_entry = dwarf.unit.get_mut(type_id);
133             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
134             type_id
135         };
136
137         let type_id = if ty.is_bool() {
138             primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
139         } else if ty.is_int() {
140             primitive(&mut self.dwarf, gimli::DW_ATE_address)
141         } else if ty.is_float() {
142             primitive(&mut self.dwarf, gimli::DW_ATE_float)
143         } else {
144             new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
145         };
146
147         let type_entry = self.dwarf.unit.get_mut(type_id);
148         type_entry.set(
149             gimli::DW_AT_name,
150             AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()),
151         );
152         type_entry.set(
153             gimli::DW_AT_byte_size,
154             AttributeValue::Udata(u64::from(ty.bytes())),
155         );
156
157         type_id
158     }
159
160     fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
161         if let Some(type_id) = self.types.get(ty) {
162             return *type_id;
163         }
164
165         let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
166
167         let primitive = |dwarf: &mut DwarfUnit, ate| {
168             let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
169             let type_entry = dwarf.unit.get_mut(type_id);
170             type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
171             type_id
172         };
173
174         let name = format!("{}", ty);
175         let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
176
177         let type_id = match ty.kind() {
178             ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
179             ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
180             ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
181             ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
182             ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
183             ty::Ref(_, pointee_ty, _mutbl)
184             | ty::RawPtr(ty::TypeAndMut {
185                 ty: pointee_ty,
186                 mutbl: _mutbl,
187             }) => {
188                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
189
190                 // Ensure that type is inserted before recursing to avoid duplicates
191                 self.types.insert(ty, type_id);
192
193                 let pointee = self.dwarf_ty(pointee_ty);
194
195                 let type_entry = self.dwarf.unit.get_mut(type_id);
196
197                 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
198                 type_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(pointee));
199
200                 type_id
201             }
202             ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
203                 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
204
205                 // Ensure that type is inserted before recursing to avoid duplicates
206                 self.types.insert(ty, type_id);
207
208                 let variant = adt_def.non_enum_variant();
209
210                 for (field_idx, field_def) in variant.fields.iter().enumerate() {
211                     let field_offset = layout.fields.offset(field_idx);
212                     let field_layout = layout
213                         .field(
214                             &layout::LayoutCx {
215                                 tcx: self.tcx,
216                                 param_env: ParamEnv::reveal_all(),
217                             },
218                             field_idx,
219                         )
220                         .unwrap();
221
222                     let field_type = self.dwarf_ty(field_layout.ty);
223
224                     let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
225                     let field_entry = self.dwarf.unit.get_mut(field_id);
226
227                     field_entry.set(
228                         gimli::DW_AT_name,
229                         AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()),
230                     );
231                     field_entry.set(
232                         gimli::DW_AT_data_member_location,
233                         AttributeValue::Udata(field_offset.bytes()),
234                     );
235                     field_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(field_type));
236                 }
237
238                 type_id
239             }
240             _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
241         };
242
243         let type_entry = self.dwarf.unit.get_mut(type_id);
244
245         type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
246         type_entry.set(
247             gimli::DW_AT_byte_size,
248             AttributeValue::Udata(layout.size.bytes()),
249         );
250
251         self.types.insert(ty, type_id);
252
253         type_id
254     }
255
256     fn define_local(&mut self, scope: UnitEntryId, name: String, ty: Ty<'tcx>) -> UnitEntryId {
257         let dw_ty = self.dwarf_ty(ty);
258
259         let var_id = self.dwarf.unit.add(scope, gimli::DW_TAG_variable);
260         let var_entry = self.dwarf.unit.get_mut(var_id);
261
262         var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
263         var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
264
265         var_id
266     }
267
268     pub(crate) fn define_function(
269         &mut self,
270         instance: Instance<'tcx>,
271         func_id: FuncId,
272         name: &str,
273         isa: &dyn TargetIsa,
274         context: &Context,
275         source_info_set: &indexmap::IndexSet<SourceInfo>,
276         local_map: IndexVec<mir::Local, CPlace<'tcx>>,
277     ) {
278         let symbol = func_id.as_u32() as usize;
279         let mir = self.tcx.instance_mir(instance.def);
280
281         // FIXME: add to appropriate scope instead of root
282         let scope = self.dwarf.unit.root();
283
284         let entry_id = self.dwarf.unit.add(scope, gimli::DW_TAG_subprogram);
285         let entry = self.dwarf.unit.get_mut(entry_id);
286         let name_id = self.dwarf.strings.add(name);
287         // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
288         entry.set(gimli::DW_AT_name, AttributeValue::StringRef(name_id));
289         entry.set(
290             gimli::DW_AT_linkage_name,
291             AttributeValue::StringRef(name_id),
292         );
293
294         let end =
295             self.create_debug_lines(isa, symbol, entry_id, context, mir.span, source_info_set);
296
297         self.unit_range_list.0.push(Range::StartLength {
298             begin: Address::Symbol { symbol, addend: 0 },
299             length: u64::from(end),
300         });
301
302         if isa.get_mach_backend().is_some() {
303             return; // Not yet implemented for the AArch64 backend.
304         }
305
306         let func_entry = self.dwarf.unit.get_mut(entry_id);
307         // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
308         func_entry.set(
309             gimli::DW_AT_low_pc,
310             AttributeValue::Address(Address::Symbol { symbol, addend: 0 }),
311         );
312         // Using Udata for DW_AT_high_pc requires at least DWARF4
313         func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
314
315         // FIXME Remove once actual debuginfo for locals works.
316         for (i, (param, &val)) in context
317             .func
318             .signature
319             .params
320             .iter()
321             .zip(
322                 context
323                     .func
324                     .dfg
325                     .block_params(context.func.layout.entry_block().unwrap()),
326             )
327             .enumerate()
328         {
329             use cranelift_codegen::ir::ArgumentPurpose;
330             let base_name = match param.purpose {
331                 ArgumentPurpose::Normal => "arg",
332                 ArgumentPurpose::StructArgument(_) => "struct_arg",
333                 ArgumentPurpose::StructReturn => "sret",
334                 ArgumentPurpose::Link
335                 | ArgumentPurpose::FramePointer
336                 | ArgumentPurpose::CalleeSaved => continue,
337                 ArgumentPurpose::VMContext
338                 | ArgumentPurpose::SignatureId
339                 | ArgumentPurpose::CallerTLS
340                 | ArgumentPurpose::CalleeTLS
341                 | ArgumentPurpose::StackLimit => unreachable!(),
342             };
343             let name = format!("{}{}", base_name, i);
344
345             let dw_ty = self.dwarf_ty_for_clif_ty(param.value_type);
346             let loc =
347                 translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap();
348
349             let arg_id = self
350                 .dwarf
351                 .unit
352                 .add(entry_id, gimli::DW_TAG_formal_parameter);
353             let var_entry = self.dwarf.unit.get_mut(arg_id);
354
355             var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
356             var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
357             var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
358         }
359
360         // FIXME make it more reliable and implement scopes before re-enabling this.
361         if false {
362             let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
363
364             for (local, _local_decl) in mir.local_decls.iter_enumerated() {
365                 let ty = self.tcx.subst_and_normalize_erasing_regions(
366                     instance.substs,
367                     ty::ParamEnv::reveal_all(),
368                     mir.local_decls[local].ty,
369                 );
370                 let var_id = self.define_local(entry_id, format!("{:?}", local), ty);
371
372                 let location = place_location(
373                     self,
374                     isa,
375                     symbol,
376                     context,
377                     &local_map,
378                     &value_labels_ranges,
379                     Place {
380                         local,
381                         projection: ty::List::empty(),
382                     },
383                 );
384
385                 let var_entry = self.dwarf.unit.get_mut(var_id);
386                 var_entry.set(gimli::DW_AT_location, location);
387             }
388         }
389
390         // FIXME create locals for all entries in mir.var_debug_info
391     }
392 }
393
394 fn place_location<'tcx>(
395     debug_context: &mut DebugContext<'tcx>,
396     isa: &dyn TargetIsa,
397     symbol: usize,
398     context: &Context,
399     local_map: &IndexVec<mir::Local, CPlace<'tcx>>,
400     #[allow(rustc::default_hash_types)] value_labels_ranges: &std::collections::HashMap<
401         ValueLabel,
402         Vec<ValueLocRange>,
403     >,
404     place: Place<'tcx>,
405 ) -> AttributeValue {
406     assert!(place.projection.is_empty()); // FIXME implement them
407
408     match local_map[place.local].inner() {
409         CPlaceInner::Var(_local, var) => {
410             let value_label = cranelift_codegen::ir::ValueLabel::new(var.index());
411             if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
412                 let loc_list = LocationList(
413                     value_loc_ranges
414                         .iter()
415                         .map(|value_loc_range| Location::StartEnd {
416                             begin: Address::Symbol {
417                                 symbol,
418                                 addend: i64::from(value_loc_range.start),
419                             },
420                             end: Address::Symbol {
421                                 symbol,
422                                 addend: i64::from(value_loc_range.end),
423                             },
424                             data: translate_loc(
425                                 isa,
426                                 value_loc_range.loc,
427                                 &context.func.stack_slots,
428                             )
429                             .unwrap(),
430                         })
431                         .collect(),
432                 );
433                 let loc_list_id = debug_context.dwarf.unit.locations.add(loc_list);
434
435                 AttributeValue::LocationListRef(loc_list_id)
436             } else {
437                 // FIXME set value labels for unused locals
438
439                 AttributeValue::Exprloc(Expression::new())
440             }
441         }
442         CPlaceInner::VarPair(_, _, _) => {
443             // FIXME implement this
444
445             AttributeValue::Exprloc(Expression::new())
446         }
447         CPlaceInner::VarLane(_, _, _) => {
448             // FIXME implement this
449
450             AttributeValue::Exprloc(Expression::new())
451         }
452         CPlaceInner::Addr(_, _) => {
453             // FIXME implement this (used by arguments and returns)
454
455             AttributeValue::Exprloc(Expression::new())
456
457             // For PointerBase::Stack:
458             //AttributeValue::Exprloc(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap())
459         }
460     }
461 }
462
463 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
464 fn translate_loc(
465     isa: &dyn TargetIsa,
466     loc: ValueLoc,
467     stack_slots: &StackSlots,
468 ) -> Option<Expression> {
469     match loc {
470         ValueLoc::Reg(reg) => {
471             let machine_reg = isa.map_dwarf_register(reg).unwrap();
472             let mut expr = Expression::new();
473             expr.op_reg(gimli::Register(machine_reg));
474             Some(expr)
475         }
476         ValueLoc::Stack(ss) => {
477             if let Some(ss_offset) = stack_slots[ss].offset {
478                 let mut expr = Expression::new();
479                 expr.op_breg(X86_64::RBP, i64::from(ss_offset) + 16);
480                 Some(expr)
481             } else {
482                 None
483             }
484         }
485         _ => None,
486     }
487 }