LLVM 24.0.0git
DIEAttributeCloner.cpp
Go to the documentation of this file.
1//=== DIEAttributeCloner.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12
13using namespace llvm;
14using namespace dwarf_linker;
15using namespace dwarf_linker::parallel;
16
18 // Extract and clone every attribute.
19 DWARFDataExtractor Data = InUnit.getOrigUnit().getDebugInfoExtractor();
20
21 uint64_t Offset = InputDieEntry->getOffset();
22 // Point to the next DIE (generally there is always at least a NULL
23 // entry after the current one). If this is a lone
24 // DW_TAG_compile_unit without any children, point to the next unit.
25 uint64_t NextOffset = (InputDIEIdx + 1 < InUnit.getOrigUnit().getNumDIEs())
26 ? InUnit.getDIEAtIndex(InputDIEIdx + 1).getOffset()
27 : InUnit.getOrigUnit().getNextUnitOffset();
28
29 // We could copy the data only if we need to apply a relocation to it. After
30 // testing, it seems there is no performance downside to doing the copy
31 // unconditionally, and it makes the code simpler.
32 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
33 Data =
34 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
35
36 // Modify the copy with relocated addresses.
37 InUnit.getContainingFile().Addresses->applyValidRelocs(DIECopy, Offset,
38 Data.isLittleEndian());
39
40 // Reset the Offset to 0 as we will be working on the local copy of
41 // the data.
42 Offset = 0;
43
44 const auto *Abbrev = InputDieEntry->getAbbreviationDeclarationPtr();
45 Offset += getULEB128Size(Abbrev->getCode());
46
47 // Set current output offset.
48 AttrOutOffset = OutUnit.isCompileUnit() ? OutDIE->getOffset() : 0;
49 for (const auto &AttrSpec : Abbrev->attributes()) {
50 // Check whether current attribute should be skipped.
51 if (shouldSkipAttribute(AttrSpec)) {
52 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
53 InUnit.getFormParams());
54 continue;
55 }
56
57 DWARFFormValue Val = AttrSpec.getFormValue();
58 uint64_t InputAttrStartOffset = InputDieEntry->getOffset() + Offset;
59 Val.extractValue(Data, &Offset, InUnit.getFormParams(),
60 &InUnit.getOrigUnit());
61 uint64_t InputAttrEndOffset = InputDieEntry->getOffset() + Offset;
62 uint64_t OutputAttrOffset = AttrOutOffset;
63
64 // Clone current attribute.
65 // Only address and block attributes hold relocations against symbols.
66 bool MayHaveRelocs = false;
67 switch (AttrSpec.Form) {
68 case dwarf::DW_FORM_strp:
69 case dwarf::DW_FORM_line_strp:
70 case dwarf::DW_FORM_string:
71 case dwarf::DW_FORM_strx:
72 case dwarf::DW_FORM_strx1:
73 case dwarf::DW_FORM_strx2:
74 case dwarf::DW_FORM_strx3:
75 case dwarf::DW_FORM_strx4:
76 AttrOutOffset += cloneStringAttr(Val, AttrSpec);
77 break;
78 case dwarf::DW_FORM_ref_addr:
79 case dwarf::DW_FORM_ref1:
80 case dwarf::DW_FORM_ref2:
81 case dwarf::DW_FORM_ref4:
82 case dwarf::DW_FORM_ref8:
83 case dwarf::DW_FORM_ref_udata:
84 AttrOutOffset += cloneDieRefAttr(Val, AttrSpec);
85 break;
86 case dwarf::DW_FORM_data1:
87 case dwarf::DW_FORM_data2:
88 case dwarf::DW_FORM_data4:
89 case dwarf::DW_FORM_data8:
90 case dwarf::DW_FORM_udata:
91 case dwarf::DW_FORM_sdata:
92 case dwarf::DW_FORM_sec_offset:
93 case dwarf::DW_FORM_flag:
94 case dwarf::DW_FORM_flag_present:
95 case dwarf::DW_FORM_rnglistx:
96 case dwarf::DW_FORM_loclistx:
97 case dwarf::DW_FORM_implicit_const:
98 AttrOutOffset += cloneScalarAttr(Val, AttrSpec);
99 break;
100 case dwarf::DW_FORM_block:
101 case dwarf::DW_FORM_block1:
102 case dwarf::DW_FORM_block2:
103 case dwarf::DW_FORM_block4:
104 case dwarf::DW_FORM_exprloc:
105 AttrOutOffset += cloneBlockAttr(Val, AttrSpec);
106 MayHaveRelocs = true;
107 break;
108 case dwarf::DW_FORM_addr:
109 case dwarf::DW_FORM_addrx:
110 case dwarf::DW_FORM_addrx1:
111 case dwarf::DW_FORM_addrx2:
112 case dwarf::DW_FORM_addrx3:
113 case dwarf::DW_FORM_addrx4:
114 AttrOutOffset += cloneAddressAttr(Val, AttrSpec);
115 MayHaveRelocs = true;
116 break;
117 default:
118 InUnit.warn("unsupported attribute form " +
119 dwarf::FormEncodingString(AttrSpec.Form) +
120 " in DieAttributeCloner::clone(). Dropping.",
122 }
123
124 if (SaveRelocs && MayHaveRelocs && AttrOutOffset != OutputAttrOffset)
125 OutUnit.getAsCompileUnit()->getRelocFixups().noteAttribute(
126 InputDieEntry->getTag(), AttrSpec.Attr, InputAttrStartOffset,
127 InputAttrEndOffset, OutputAttrOffset, Source);
128 Source.clear();
129 }
130
131 // We convert source strings into the indexed form for DWARFv5.
132 // Check if original unit already has DW_AT_str_offsets_base
133 // attribute.
134 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
135 !AttrInfo.HasStringOffsetBaseAttr && OutUnit.isCompileUnit()) {
136 DebugInfoOutputSection.notePatchWithOffsetUpdate(
138 &OutUnit->getOrCreateSectionDescriptor(
140 true},
142
145 .addScalarAttribute(dwarf::DW_AT_str_offsets_base,
146 dwarf::DW_FORM_sec_offset,
147 OutUnit->getDebugStrOffsetsHeaderSize())
148 .second;
149 }
150
151 // No DW_AT_addr_base: add one for the addrx-indexed entries. Except in
152 // update mode, where HasAddrBaseAttr is never set.
153 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
154 !AttrInfo.HasAddrBaseAttr &&
155 !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
156 DebugInfoOutputSection.notePatchWithOffsetUpdate(
159 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugAddr),
160 true},
162
164 .addScalarAttribute(dwarf::DW_AT_addr_base,
165 dwarf::DW_FORM_sec_offset,
166 OutUnit->getDebugAddrHeaderSize())
167 .second;
168 }
169}
170
173 switch (AttrSpec.Attr) {
174 default:
175 return false;
176 case dwarf::DW_AT_low_pc:
177 case dwarf::DW_AT_high_pc:
178 case dwarf::DW_AT_ranges:
179 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
180 return false;
181
182 // Skip address attribute if we are in function scope and function does not
183 // reference live address.
184 return InUnit.getDIEInfo(InputDIEIdx).getIsInFunctionScope() &&
185 !FuncAddressAdjustment.has_value();
186 case dwarf::DW_AT_rnglists_base:
187 // In case !Update the .debug_addr table is not generated/preserved.
188 // Thus instead of DW_FORM_rnglistx the DW_FORM_sec_offset is used.
189 // Since DW_AT_rnglists_base is used for only DW_FORM_rnglistx the
190 // DW_AT_rnglists_base is removed.
191 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
192 case dwarf::DW_AT_loclists_base:
193 // In case !Update the .debug_addr table is not generated/preserved.
194 // Thus instead of DW_FORM_loclistx the DW_FORM_sec_offset is used.
195 // Since DW_AT_loclists_base is used for only DW_FORM_loclistx the
196 // DW_AT_loclists_base is removed.
197 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
198 case dwarf::DW_AT_location:
199 case dwarf::DW_AT_frame_base:
200 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
201 return false;
202
203 // When location expression contains an address: skip this attribute
204 // if it does not reference live address.
206 return !VarAddressAdjustment.has_value();
207
208 // Skip location attribute if we are in function scope and function does not
209 // reference live address.
210 return InUnit.getDIEInfo(InputDIEIdx).getIsInFunctionScope() &&
211 !FuncAddressAdjustment.has_value();
212 }
213}
214
216 const DWARFFormValue &Val,
218 std::optional<const char *> String = dwarf::toString(Val);
219 if (!String) {
220 InUnit.warn("cann't read string attribute.");
221 return 0;
222 }
223
224 const DWARFFile &File = InUnit.getContainingFile();
225 std::string RemappedPath;
226 if (File.PrefixMap &&
227 isPathAttribute(InputDieEntry->getTag(), AttrSpec.Attr)) {
228 RemappedPath = File.remapPath(*String);
229 String = RemappedPath.c_str();
230 }
231
232 StringEntry *StringInPool =
233 InUnit.getGlobalData().getStringPool().insert(*String).first;
234
235 // Update attributes info.
236 if (AttrSpec.Attr == dwarf::DW_AT_name)
237 AttrInfo.Name = StringInPool;
238 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
239 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
240 AttrInfo.MangledName = StringInPool;
241
242 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
243 if (OutUnit.isTypeUnit()) {
245 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(InputDIEIdx),
246 StringInPool});
247 } else {
248 DebugInfoOutputSection.notePatchWithOffsetUpdate(
250 }
251 return Generator
252 .addStringPlaceholderAttribute(AttrSpec.Attr, dwarf::DW_FORM_line_strp)
253 .second;
254 }
255
256 if (Use_DW_FORM_strp) {
257 if (OutUnit.isTypeUnit()) {
258 DebugInfoOutputSection.notePatch(
260 InUnit.getDieTypeEntry(InputDIEIdx), StringInPool});
261 } else {
262 DebugInfoOutputSection.notePatchWithOffsetUpdate(
263 DebugStrPatch{{AttrOutOffset}, StringInPool}, PatchesOffsets);
264 }
265
266 return Generator
267 .addStringPlaceholderAttribute(AttrSpec.Attr, dwarf::DW_FORM_strp)
268 .second;
269 }
270
271 return Generator
272 .addIndexedStringAttribute(AttrSpec.Attr, dwarf::DW_FORM_strx,
273 OutUnit->getDebugStrIndex(StringInPool))
274 .second;
275}
276
278 const DWARFFormValue &Val,
280 if (AttrSpec.Attr == dwarf::DW_AT_sibling)
281 return 0;
282
283 std::optional<UnitEntryPairTy> RefDiePair =
284 InUnit.resolveDIEReference(Val, ResolveInterCUReferencesMode::Resolve);
285 if (!RefDiePair || !RefDiePair->DieEntry) {
286 // If the referenced DIE is not found, drop the attribute.
287 InUnit.warn("could not find referenced DIE", InputDieEntry);
288 return 0;
289 }
290
291 TypeEntry *RefTypeName = nullptr;
292 const CompileUnit::DIEInfo &RefDIEInfo =
293 RefDiePair->CU->getDIEInfo(RefDiePair->DieEntry);
294 if (RefDIEInfo.needToPlaceInTypeTable())
295 RefTypeName = RefDiePair->CU->getDieTypeEntry(RefDiePair->DieEntry);
296
297 // The importing unit's DW_TAG_module skeleton can have a different
298 // DW_AT_LLVM_include_path than the unit built from the .pcm and the import
299 // must use the latter. The type pool already merges copies, so a reference
300 // with a type entry resolves correctly. Without one, the module's anchor is
301 // the only link between the two, and it is not known until the unit
302 // describing the module has been emitted.
303 if (RefDiePair->DieEntry->getTag() == dwarf::DW_TAG_module &&
304 AttrSpec.Attr == dwarf::DW_AT_import && !OutUnit.isTypeUnit() &&
305 !RefTypeName) {
306 SmallString<128> Path;
307 if (RefDiePair->CU->getModulePath(RefDiePair->DieEntry, Path)) {
308 ModuleAnchor *Anchor =
309 InUnit.getGlobalData().getModulePool().getOrCreate(Path);
310
311 DebugInfoOutputSection.notePatchWithOffsetUpdate(
313 AttrOutOffset, RefDiePair->CU,
314 RefDiePair->CU->getDIEIndex(RefDiePair->DieEntry), Anchor},
316 return Generator
317 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref_addr, 0xBADDEF)
318 .second;
319 }
320 }
321
322 if (OutUnit.isTypeUnit()) {
323 assert(RefTypeName && "Type name for referenced DIE is not set");
324 assert(InUnit.getDieTypeEntry(InputDIEIdx) &&
325 "Type name for DIE is not set");
326
328 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(InputDIEIdx),
329 RefTypeName});
330
331 return Generator
332 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref4, 0xBADDEF)
333 .second;
334 }
335
336 if (RefTypeName) {
337 DebugInfoOutputSection.notePatchWithOffsetUpdate(
339
340 return Generator
341 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref_addr, 0xBADDEF)
342 .second;
343 }
344
345 // Get output offset for referenced DIE.
346 uint64_t OutDieOffset = RefDiePair->CU->getDieOutOffset(RefDiePair->DieEntry);
347
348 // Examine whether referenced DIE is in current compile unit.
349 bool IsLocal = OutUnit->getUniqueID() == RefDiePair->CU->getUniqueID();
350
351 // Set attribute form basing on the kind of referenced DIE(local or not?).
352 dwarf::Form NewForm = IsLocal ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr;
353
354 // Check whether current attribute references already cloned DIE inside
355 // the same compilation unit. If true - write the already known offset value.
356 if (IsLocal && (OutDieOffset != 0))
357 return Generator.addScalarAttribute(AttrSpec.Attr, NewForm, OutDieOffset)
358 .second;
359
360 // If offset value is not known at this point then create patch for the
361 // reference value and write dummy value into the attribute.
362 DebugInfoOutputSection.notePatchWithOffsetUpdate(
363 DebugDieRefPatch{AttrOutOffset, OutUnit.getAsCompileUnit(),
364 RefDiePair->CU,
365 RefDiePair->CU->getDIEIndex(RefDiePair->DieEntry)},
367 return Generator.addScalarAttribute(AttrSpec.Attr, NewForm, 0xBADDEF).second;
368}
369
371 const DWARFFormValue &Val,
373
374 // Create patches for attribute referencing other non invariant section.
375 // Invariant section could not be updated here as this section and
376 // reference to it do not change value in case --update.
377 switch (AttrSpec.Attr) {
378 case dwarf::DW_AT_macro_info: {
379 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
380 const DWARFDebugMacro *Macro =
381 InUnit.getContainingFile().Dwarf->getDebugMacinfo();
382 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
383 return 0;
384
385 DebugInfoOutputSection.notePatchWithOffsetUpdate(
387 &OutUnit->getOrCreateSectionDescriptor(
390 }
391 } break;
392 case dwarf::DW_AT_macros: {
393 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
394 const DWARFDebugMacro *Macro =
395 InUnit.getContainingFile().Dwarf->getDebugMacro();
396 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
397 return 0;
398
399 DebugInfoOutputSection.notePatchWithOffsetUpdate(
401 &OutUnit->getOrCreateSectionDescriptor(
404 }
405 } break;
406 case dwarf::DW_AT_stmt_list: {
407 DebugInfoOutputSection.notePatchWithOffsetUpdate(
408 DebugOffsetPatch{AttrOutOffset, &OutUnit->getOrCreateSectionDescriptor(
411 } break;
412 case dwarf::DW_AT_str_offsets_base: {
413 DebugInfoOutputSection.notePatchWithOffsetUpdate(
415 &OutUnit->getOrCreateSectionDescriptor(
417 true},
419
420 // Use size of .debug_str_offsets header as attribute value. The offset
421 // to .debug_str_offsets would be added later while patching.
422 AttrInfo.HasStringOffsetBaseAttr = true;
423 return Generator
424 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form,
425 OutUnit->getDebugStrOffsetsHeaderSize())
426 .second;
427 } break;
428 case dwarf::DW_AT_decl_file: {
429 // Value of DW_AT_decl_file may exceed original form. Longer
430 // form can affect offsets to the following attributes. To not
431 // update offsets of the following attributes we always remove
432 // original DW_AT_decl_file and attach it to the last position
433 // later.
434 if (OutUnit.isTypeUnit()) {
435 if (std::optional<std::pair<StringRef, StringRef>> DirAndFilename =
436 InUnit.getDirAndFilenameFromLineTable(Val))
438 OutDIE,
439 InUnit.getDieTypeEntry(InputDIEIdx),
440 OutUnit->getGlobalData()
441 .getStringPool()
442 .insert(DirAndFilename->first)
443 .first,
444 OutUnit->getGlobalData()
445 .getStringPool()
446 .insert(DirAndFilename->second)
447 .first,
448 });
449 return 0;
450 }
451 } break;
452 default: {
453 } break;
454 };
455
456 uint64_t Value;
457 if (AttrSpec.Attr == dwarf::DW_AT_const_value &&
458 (InputDieEntry->getTag() == dwarf::DW_TAG_variable ||
459 InputDieEntry->getTag() == dwarf::DW_TAG_constant))
460 AttrInfo.HasLiveAddress = true;
461
462 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
463 if (auto OptionalValue = Val.getAsUnsignedConstant())
464 Value = *OptionalValue;
465 else if (auto OptionalValue = Val.getAsSignedConstant())
466 Value = *OptionalValue;
467 else if (auto OptionalValue = Val.getAsSectionOffset())
468 Value = *OptionalValue;
469 else {
470 InUnit.warn("unsupported scalar attribute form. Dropping attribute.",
472 return 0;
473 }
474
475 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
476 AttrInfo.IsDeclaration = true;
477
478 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
479 return Generator.addLocListAttribute(AttrSpec.Attr, AttrSpec.Form, Value)
480 .second;
481
482 return Generator.addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, Value)
483 .second;
484 }
485
486 dwarf::Form ResultingForm = AttrSpec.Form;
487 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
488 // DWARFLinker does not generate .debug_addr table. Thus we need to change
489 // all "addrx" related forms to "addr" version. Change DW_FORM_rnglistx
490 // to DW_FORM_sec_offset here.
491 std::optional<uint64_t> Index = Val.getAsSectionOffset();
492 if (!Index) {
493 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
494 return 0;
495 }
496 std::optional<uint64_t> Offset =
497 InUnit.getOrigUnit().getRnglistOffset(*Index);
498 if (!Offset) {
499 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
500 return 0;
501 }
502
503 Value = *Offset;
504 ResultingForm = dwarf::DW_FORM_sec_offset;
505 } else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
506 // DWARFLinker does not generate .debug_addr table. Thus we need to change
507 // all "addrx" related forms to "addr" version. Change DW_FORM_loclistx
508 // to DW_FORM_sec_offset here.
509 std::optional<uint64_t> Index = Val.getAsSectionOffset();
510 if (!Index) {
511 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
512 return 0;
513 }
514 std::optional<uint64_t> Offset =
515 InUnit.getOrigUnit().getLoclistOffset(*Index);
516 if (!Offset) {
517 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
518 return 0;
519 }
520
521 Value = *Offset;
522 ResultingForm = dwarf::DW_FORM_sec_offset;
523 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
524 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit) {
525 if (!OutUnit.isCompileUnit())
526 return 0;
527
528 std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc();
529 if (!LowPC)
530 return 0;
531 // Dwarf >= 4 high_pc is an size, not an address.
532 Value = OutUnit.getAsCompileUnit()->getHighPc() - *LowPC;
533 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
534 Value = *Val.getAsSectionOffset();
535 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
536 Value = *Val.getAsSignedConstant();
537 else if (auto OptionalValue = Val.getAsUnsignedConstant())
538 Value = *OptionalValue;
539 else {
540 InUnit.warn("unsupported scalar attribute form. Dropping attribute.",
542 return 0;
543 }
544
545 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
546 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
547 // Create patch for the range offset value.
548 DebugInfoOutputSection.notePatchWithOffsetUpdate(
550 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit},
552 AttrInfo.HasRanges = true;
553 } else if (DWARFAttribute::mayHaveLocationList(AttrSpec.Attr) &&
556 InUnit.getOrigUnit().getVersion())) {
557 int64_t AddrAdjustmentValue = 0;
559 AddrAdjustmentValue = *VarAddressAdjustment;
560 else if (FuncAddressAdjustment)
561 AddrAdjustmentValue = *FuncAddressAdjustment;
562
563 // Create patch for the location offset value.
564 DebugInfoOutputSection.notePatchWithOffsetUpdate(
565 DebugLocPatch{{AttrOutOffset}, AddrAdjustmentValue}, PatchesOffsets);
566 } else if (AttrSpec.Attr == dwarf::DW_AT_addr_base) {
567 DebugInfoOutputSection.notePatchWithOffsetUpdate(
570 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugAddr),
571 true},
573
574 // Use size of .debug_addr header as attribute value. The offset to
575 // .debug_addr would be added later while patching.
576 AttrInfo.HasAddrBaseAttr = true;
577 return Generator
578 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form,
579 OutUnit->getDebugAddrHeaderSize())
580 .second;
581 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
582 AttrInfo.IsDeclaration = true;
583
584 // DW_AT_LLVM_stmt_sequence refers to line info in this unit's
585 // .debug_line contribution, which only exists for compile units.
586 // DependencyTracker can route a module-scope subprogram to a type
587 // unit when ODR deduplication applies (see
588 // DependencyTracker.cpp: DW_TAG_subprogram case), so drop the
589 // attribute on that path — mirroring how cloneBlockAttr handles
590 // type-unit placement.
591 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence &&
592 !OutUnit.isCompileUnit())
593 return 0;
594
595 // A compile unit's high_pc comes from the unit's own linked range and spans
596 // every symbol in it.
597 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
598 InputDieEntry->getTag() != dwarf::DW_TAG_compile_unit)
599 Value = constrainHighPC(Value, /*IsLength=*/true);
600
601 auto Result =
602 Generator.addScalarAttribute(AttrSpec.Attr, ResultingForm, Value);
603 // Record DW_AT_LLVM_stmt_sequence so the attribute value can be
604 // rewritten with the correct .debug_line offset after the line table
605 // for this CU has been emitted. We also register a DebugOffsetPatch so
606 // that the final-section offset of .debug_line gets added when the
607 // section is placed in the combined output.
608 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
609 // Record the attribute's raw input stmt-sequence offset. Resolution
610 // to a first-row index — including the boundary-walk fallback for
611 // sequences the DWARF parser may not have registered — happens in
612 // a post-cloning pass (buildStmtSeqOffsetToFirstRowIndex), so that
613 // matches the classic linker's behaviour.
614 OutUnit.getAsCompileUnit()->noteStmtSeqListAttribute(&Result.first, Value);
615 DebugInfoOutputSection.notePatchWithOffsetUpdate(
618 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugLine),
619 /*AddLocalValue=*/true},
621 }
622 return Result.second;
623}
624
627
628 for (const DWARFExpression::Operation &Op : Expr) {
629 switch (Op.getCode()) {
630 case dwarf::DW_OP_addr:
631 case dwarf::DW_OP_addrx:
632 case dwarf::DW_OP_constx:
633 return true;
634 default:
635 break;
636 }
637
638 if (llvm::is_contained(Op.getDescription().Op, Encoding::BaseTypeRef))
639 return true;
640 }
641
642 return false;
643}
644
646 const DWARFFormValue &Val,
648
649 size_t NumberOfPatchesAtStart = PatchesOffsets.size();
650
651 // If the block is a DWARF Expression, clone it into the temporary
652 // buffer using cloneExpression(), otherwise copy the data directly.
654 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
658 DataExtractor Data(Bytes, InUnit.getOrigUnit().isLittleEndian());
659 DWARFExpression Expr(Data, InUnit.getOrigUnit().getAddressByteSize(),
660 InUnit.getFormParams().Format);
661
662 // A type unit is shared by every compile unit that references the type, so
663 // an expression resolving against one origin unit has no single correct
664 // value there.
665 if (OutUnit.isTypeUnit() && expressionDependsOnOriginUnit(Expr))
666 return 0;
667
668 if (SaveRelocs)
669 Source.Expression.emplace(Bytes.size());
670 InUnit.cloneDieAttrExpression(
672 PatchesOffsets, Source.Expression ? &*Source.Expression : nullptr);
673 Bytes = Buffer;
674 }
675
676 // The expression location data might be updated and exceed the original size.
677 // Check whether the new data fits into the original form.
678 dwarf::Form ResultForm = AttrSpec.Form;
679 if ((ResultForm == dwarf::DW_FORM_block1 && Bytes.size() > UINT8_MAX) ||
680 (ResultForm == dwarf::DW_FORM_block2 && Bytes.size() > UINT16_MAX) ||
681 (ResultForm == dwarf::DW_FORM_block4 && Bytes.size() > UINT32_MAX))
682 ResultForm = dwarf::DW_FORM_block;
683
684 size_t FinalAttributeSize;
685 if (AttrSpec.Form == dwarf::DW_FORM_exprloc)
686 FinalAttributeSize =
687 Generator.addLocationAttribute(AttrSpec.Attr, ResultForm, Bytes).second;
688 else
689 FinalAttributeSize =
690 Generator.addBlockAttribute(AttrSpec.Attr, ResultForm, Bytes).second;
691
692 // Update patches offsets with the size of length field for Bytes.
693 for (size_t Idx = NumberOfPatchesAtStart; Idx < PatchesOffsets.size();
694 Idx++) {
695 assert(FinalAttributeSize > Bytes.size());
696 *PatchesOffsets[Idx] +=
697 (AttrOutOffset + (FinalAttributeSize - Bytes.size()));
698 }
699
700 if (Source.Expression)
701 Source.Expression->addOutputPrefix(FinalAttributeSize - Bytes.size());
702
704 AttrInfo.HasLiveAddress =
705 VarAddressAdjustment.has_value() ||
706 InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
707
708 return FinalAttributeSize;
709}
710
712 const DWARFFormValue &Val,
714 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
715 AttrInfo.HasLiveAddress = true;
716
717 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
718 return Generator
719 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, Val.getRawUValue())
720 .second;
721
722 if (OutUnit.isTypeUnit())
723 return 0;
724
725 // Cloned Die may have address attributes relocated to a
726 // totally unrelated value. This can happen:
727 // - If high_pc is an address (Dwarf version == 2), then it might have been
728 // relocated to a totally unrelated value (because the end address in the
729 // object file might be start address of another function which got moved
730 // independently by the linker).
731 // - If address relocated in an inline_subprogram that happens at the
732 // beginning of its inlining function.
733 // To avoid above cases and to not apply relocation twice (in
734 // applyValidRelocs and here), read address attribute from InputDIE and apply
735 // Info.PCOffset here.
736
737 std::optional<DWARFFormValue> AddrAttribute =
738 InUnit.find(InputDieEntry, AttrSpec.Attr);
739 if (!AddrAttribute)
740 llvm_unreachable("Cann't find attribute");
741
742 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
743 if (!Addr) {
744 InUnit.warn("cann't read address attribute value.");
745 return 0;
746 }
747
748 if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
749 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
750 if (std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc())
751 Addr = *LowPC;
752 else
753 return 0;
754 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
755 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
756 if (uint64_t HighPc = OutUnit.getAsCompileUnit()->getHighPc())
757 Addr = HighPc;
758 else
759 return 0;
760 } else {
761 if (AttrSpec.Attr == dwarf::DW_AT_high_pc)
762 Addr = constrainHighPC(*Addr, /*IsLength=*/false);
764 *Addr += *VarAddressAdjustment;
765 else if (FuncAddressAdjustment)
766 *Addr += *FuncAddressAdjustment;
767 }
768
769 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
770 return Generator.addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, *Addr)
771 .second;
772 }
773
774 uint64_t AddrIndex = OutUnit.getAsCompileUnit()->getDebugAddrIndex(*Addr);
775
776 std::optional<uint64_t> InputOffset =
777 InUnit.getOrigUnit().getIndexedAddressOffset(Val.getRawUValue());
778 if (InputOffset)
779 Source.Entry = RelocationFixups::DebugAddrEntry{*InputOffset, AddrIndex};
780
781 return Generator
782 .addScalarAttribute(AttrSpec.Attr, dwarf::Form::DW_FORM_addrx, AddrIndex)
783 .second;
784}
785
786uint64_t DIEAttributeCloner::constrainHighPC(uint64_t HighPC, bool IsLength) {
788 return HighPC;
789 std::optional<uint64_t> LowPC =
790 dwarf::toAddress(InUnit.find(InputDieEntry, dwarf::DW_AT_low_pc));
791 if (!LowPC)
792 return HighPC;
793 uint64_t Constrained =
794 InUnit.getContainingFile().Addresses->constrainCodeRangeHighPC(
795 *LowPC, IsLength ? *LowPC + HighPC : HighPC, *FuncAddressAdjustment);
796 return IsLength ? Constrained - *LowPC : Constrained;
797}
798
799unsigned DIEAttributeCloner::finalizeAbbreviations(bool HasChildrenToClone) {
800 // Add the size of the abbreviation number to the output offset.
801 size_t AbbrevNumberSize =
802 Generator.finalizeAbbreviations(HasChildrenToClone, &PatchesOffsets);
803 AttrOutOffset += AbbrevNumberSize;
804 if (SaveRelocs)
805 OutUnit.getAsCompileUnit()->getRelocFixups().finishDIE(AbbrevNumberSize);
806
807 return AttrOutOffset;
808}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool expressionDependsOnOriginUnit(const DWARFExpression &Expr)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
This class represents an Operation in the Expression.
Encoding
Size and signedness of expression operations' operands.
LLVM_ABI std::optional< ArrayRef< uint8_t > > getAsBlock() const
LLVM_ABI std::optional< uint64_t > getAsSectionOffset() const
LLVM_ABI bool isFormClass(FormClass FC) const
LLVM_ABI std::optional< int64_t > getAsSignedConstant() const
LLVM_ABI bool extractValue(const DWARFDataExtractor &Data, uint64_t *OffsetPtr, dwarf::FormParams FormParams, const DWARFContext *Context=nullptr, const DWARFUnit *Unit=nullptr)
Extracts a value in Data at offset *OffsetPtr.
LLVM_ABI std::optional< uint64_t > getAsUnsignedConstant() const
bool skipValue(DataExtractor DebugInfoData, uint64_t *OffsetPtr, const dwarf::FormParams Params) const
Skip a form's value in DebugInfoData at the offset specified by OffsetPtr.
uint64_t getRawUValue() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM Value Representation.
Definition Value.h:75
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:27
size_t cloneBlockAttr(const DWARFFormValue &Val, const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec)
Clone block or exprloc attribute.
AttributesInfo AttrInfo
Cannot be used concurrently.
CompileUnit & InUnit
Input compilation unit.
bool HasLocationExpressionAddress
Indicates whether InputDieEntry has an location attribute containg address expression.
SectionDescriptor & DebugInfoOutputSection
.debug_info section descriptor.
unsigned finalizeAbbreviations(bool HasChildrenToClone)
Create abbreviations for the output DIE after all attributes are cloned.
unsigned AttrOutOffset
Output offset after all attributes.
DIEGenerator & Generator
Output DIE generator.
size_t cloneScalarAttr(const DWARFFormValue &Val, const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec)
Clone scalar attribute.
OffsetsPtrVector PatchesOffsets
Patches for the cloned attributes.
size_t cloneDieRefAttr(const DWARFFormValue &Val, const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec)
Clone attribute referencing another DIE.
bool shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec)
Returns true if attribute should be skipped.
size_t cloneStringAttr(const DWARFFormValue &Val, const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec)
Clone string attribute.
const DWARFDebugInfoEntry * InputDieEntry
Input DIE entry.
std::optional< int64_t > FuncAddressAdjustment
Relocation adjustment for the function address ranges.
CompileUnit::OutputUnitVariantPtr OutUnit
Output unit(either "plain" compilation unit, either artificial type unit).
size_t cloneAddressAttr(const DWARFFormValue &Val, const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec)
Clone address attribute.
std::optional< int64_t > VarAddressAdjustment
Relocation adjustment for the variable locations.
uint64_t constrainHighPC(uint64_t HighPC, bool IsLength)
Returns the input DIE's DW_AT_high_pc value HighPC, constrained so the code range it ends stays clear...
bool Use_DW_FORM_strp
This flag forces using DW_FORM_strp for string attributes.
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
Definition Dwarf.cpp:105
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:31
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
bool isPathAttribute(dwarf::Tag Tag, dwarf::Attribute Attr)
Definition Utils.h:150
std::optional< uint64_t > toAddress(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
LLVM_ABI bool doesFormBelongToClass(dwarf::Form Form, DWARFFormValue::FormClass FC, uint16_t DwarfVersion)
Check whether specified Form belongs to the FC class.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition LEB128.cpp:19
DWARFExpression::Operation Op
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
Definition DWARFDie.cpp:836
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:853
An address attribute cloned from one .debug_addr entry into another.
This structure is used to update a DW_AT_import reference to a DW_TAG_module.
This structure is used to update reference to the DIE.
This structure is used to update reference to the type DIE.
This structure is used to update strings offsets into .debug_line_str.
This structure is used to update location list offset into .debug_loc/.debug_loclists.
This structure is used to update range list offset into .debug_ranges/.debug_rnglists.
This structure is used to update strings offsets into .debug_str.
This structure is used to update reference to the type DIE.
Where the DW_TAG_module DIE describing a clang module ended up in the output.
Definition ModulePool.h:30