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 // A unit merged out of a library tells which library it comes from.
132 if (InputDIEIdx == 0 && OutUnit.isCompileUnit() && !AttrInfo.HasAppleOrigin) {
133 std::optional<StringRef> InstallName =
134 InUnit.getContainingFile().Addresses->getLibraryInstallName();
135 if (InstallName)
137 dwarf::DW_AT_APPLE_origin,
138 InUnit.getGlobalData().getStringPool().insert(*InstallName).first);
139 }
140
141 // We convert source strings into the indexed form for DWARFv5.
142 // Check if original unit already has DW_AT_str_offsets_base
143 // attribute.
144 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
145 !AttrInfo.HasStringOffsetBaseAttr && OutUnit.isCompileUnit()) {
146 DebugInfoOutputSection.notePatchWithOffsetUpdate(
148 &OutUnit->getOrCreateSectionDescriptor(
150 true},
152
155 .addScalarAttribute(dwarf::DW_AT_str_offsets_base,
156 dwarf::DW_FORM_sec_offset,
157 OutUnit->getDebugStrOffsetsHeaderSize())
158 .second;
159 }
160
161 // No DW_AT_addr_base: add one for the addrx-indexed entries. Except in
162 // update mode, where HasAddrBaseAttr is never set.
163 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
164 !AttrInfo.HasAddrBaseAttr &&
165 !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
166 DebugInfoOutputSection.notePatchWithOffsetUpdate(
169 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugAddr),
170 true},
172
174 .addScalarAttribute(dwarf::DW_AT_addr_base,
175 dwarf::DW_FORM_sec_offset,
176 OutUnit->getDebugAddrHeaderSize())
177 .second;
178 }
179}
180
183 switch (AttrSpec.Attr) {
184 default:
185 return false;
186 case dwarf::DW_AT_low_pc:
187 case dwarf::DW_AT_high_pc:
188 case dwarf::DW_AT_ranges:
189 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
190 return false;
191
192 // Skip address attribute if we are in function scope and function does not
193 // reference live address.
194 return InUnit.getDIEInfo(InputDIEIdx).getIsInFunctionScope() &&
195 !FuncAddressAdjustment.has_value();
196 case dwarf::DW_AT_rnglists_base:
197 // In case !Update the .debug_addr table is not generated/preserved.
198 // Thus instead of DW_FORM_rnglistx the DW_FORM_sec_offset is used.
199 // Since DW_AT_rnglists_base is used for only DW_FORM_rnglistx the
200 // DW_AT_rnglists_base is removed.
201 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
202 case dwarf::DW_AT_loclists_base:
203 // In case !Update the .debug_addr table is not generated/preserved.
204 // Thus instead of DW_FORM_loclistx the DW_FORM_sec_offset is used.
205 // Since DW_AT_loclists_base is used for only DW_FORM_loclistx the
206 // DW_AT_loclists_base is removed.
207 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
208 case dwarf::DW_AT_location:
209 case dwarf::DW_AT_frame_base:
210 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
211 return false;
212
213 // When location expression contains an address: skip this attribute
214 // if it does not reference live address.
216 return !VarAddressAdjustment.has_value();
217
218 // Skip location attribute if we are in function scope and function does not
219 // reference live address.
220 return InUnit.getDIEInfo(InputDIEIdx).getIsInFunctionScope() &&
221 !FuncAddressAdjustment.has_value();
222 }
223}
224
226 const DWARFFormValue &Val,
228 std::optional<const char *> String = dwarf::toString(Val);
229 if (!String) {
230 InUnit.warn("cann't read string attribute.");
231 return 0;
232 }
233
234 const DWARFFile &File = InUnit.getContainingFile();
235 std::string RemappedPath;
236 if (File.PrefixMap &&
237 isPathAttribute(InputDieEntry->getTag(), AttrSpec.Attr)) {
238 RemappedPath = File.remapPath(*String);
239 String = RemappedPath.c_str();
240 }
241
242 StringEntry *StringInPool =
243 InUnit.getGlobalData().getStringPool().insert(*String).first;
244
245 // Update attributes info.
246 if (AttrSpec.Attr == dwarf::DW_AT_name)
247 AttrInfo.Name = StringInPool;
248 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
249 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
250 AttrInfo.MangledName = StringInPool;
251 else if (AttrSpec.Attr == dwarf::DW_AT_APPLE_origin) {
252 // The library being merged is where the unit now comes from.
253 AttrInfo.HasAppleOrigin = true;
254 std::optional<StringRef> InstallName =
255 InUnit.getContainingFile().Addresses->getLibraryInstallName();
256 if (InstallName)
257 StringInPool =
258 InUnit.getGlobalData().getStringPool().insert(*InstallName).first;
259 }
260
261 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
262 if (OutUnit.isTypeUnit()) {
264 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(InputDIEIdx),
265 StringInPool});
266 } else {
267 DebugInfoOutputSection.notePatchWithOffsetUpdate(
269 }
270 return Generator
271 .addStringPlaceholderAttribute(AttrSpec.Attr, dwarf::DW_FORM_line_strp)
272 .second;
273 }
274
275 return addStringAttr(AttrSpec.Attr, StringInPool);
276}
277
280 if (Use_DW_FORM_strp) {
281 if (OutUnit.isTypeUnit()) {
283 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(InputDIEIdx), String});
284 } else {
285 DebugInfoOutputSection.notePatchWithOffsetUpdate(
287 }
288
289 return Generator.addStringPlaceholderAttribute(Attr, dwarf::DW_FORM_strp)
290 .second;
291 }
292
293 return Generator
294 .addIndexedStringAttribute(Attr, dwarf::DW_FORM_strx,
295 OutUnit->getDebugStrIndex(String))
296 .second;
297}
298
300 const DWARFFormValue &Val,
302 if (AttrSpec.Attr == dwarf::DW_AT_sibling)
303 return 0;
304
305 std::optional<UnitEntryPairTy> RefDiePair =
306 InUnit.resolveDIEReference(Val, ResolveInterCUReferencesMode::Resolve);
307 if (!RefDiePair || !RefDiePair->DieEntry) {
308 // If the referenced DIE is not found, drop the attribute.
309 InUnit.warn("could not find referenced DIE", InputDieEntry);
310 return 0;
311 }
312
313 TypeEntry *RefTypeName = nullptr;
314 const CompileUnit::DIEInfo &RefDIEInfo =
315 RefDiePair->CU->getDIEInfo(RefDiePair->DieEntry);
316 if (RefDIEInfo.needToPlaceInTypeTable())
317 RefTypeName = RefDiePair->CU->getDieTypeEntry(RefDiePair->DieEntry);
318
319 // The importing unit's DW_TAG_module skeleton can have a different
320 // DW_AT_LLVM_include_path than the unit built from the .pcm and the import
321 // must use the latter. The type pool already merges copies, so a reference
322 // with a type entry resolves correctly. Without one, the module's anchor is
323 // the only link between the two, and it is not known until the unit
324 // describing the module has been emitted.
325 if (RefDiePair->DieEntry->getTag() == dwarf::DW_TAG_module &&
326 AttrSpec.Attr == dwarf::DW_AT_import && !OutUnit.isTypeUnit() &&
327 !RefTypeName) {
328 SmallString<128> Path;
329 if (RefDiePair->CU->getModulePath(RefDiePair->DieEntry, Path)) {
330 ModuleAnchor *Anchor =
331 InUnit.getGlobalData().getModulePool().getOrCreate(Path);
332
333 DebugInfoOutputSection.notePatchWithOffsetUpdate(
335 AttrOutOffset, RefDiePair->CU,
336 RefDiePair->CU->getDIEIndex(RefDiePair->DieEntry), Anchor},
338 return Generator
339 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref_addr, 0xBADDEF)
340 .second;
341 }
342 }
343
344 if (OutUnit.isTypeUnit()) {
345 assert(RefTypeName && "Type name for referenced DIE is not set");
346 assert(InUnit.getDieTypeEntry(InputDIEIdx) &&
347 "Type name for DIE is not set");
348
350 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(InputDIEIdx),
351 RefTypeName});
352
353 return Generator
354 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref4, 0xBADDEF)
355 .second;
356 }
357
358 if (RefTypeName) {
359 DebugInfoOutputSection.notePatchWithOffsetUpdate(
361
362 return Generator
363 .addScalarAttribute(AttrSpec.Attr, dwarf::DW_FORM_ref_addr, 0xBADDEF)
364 .second;
365 }
366
367 // Get output offset for referenced DIE.
368 uint64_t OutDieOffset = RefDiePair->CU->getDieOutOffset(RefDiePair->DieEntry);
369
370 // Examine whether referenced DIE is in current compile unit.
371 bool IsLocal = OutUnit->getUniqueID() == RefDiePair->CU->getUniqueID();
372
373 // Set attribute form basing on the kind of referenced DIE(local or not?).
374 dwarf::Form NewForm = IsLocal ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr;
375
376 // Check whether current attribute references already cloned DIE inside
377 // the same compilation unit. If true - write the already known offset value.
378 if (IsLocal && (OutDieOffset != 0))
379 return Generator.addScalarAttribute(AttrSpec.Attr, NewForm, OutDieOffset)
380 .second;
381
382 // If offset value is not known at this point then create patch for the
383 // reference value and write dummy value into the attribute.
384 DebugInfoOutputSection.notePatchWithOffsetUpdate(
385 DebugDieRefPatch{AttrOutOffset, OutUnit.getAsCompileUnit(),
386 RefDiePair->CU,
387 RefDiePair->CU->getDIEIndex(RefDiePair->DieEntry)},
389 return Generator.addScalarAttribute(AttrSpec.Attr, NewForm, 0xBADDEF).second;
390}
391
393 const DWARFFormValue &Val,
395
396 // Create patches for attribute referencing other non invariant section.
397 // Invariant section could not be updated here as this section and
398 // reference to it do not change value in case --update.
399 switch (AttrSpec.Attr) {
400 case dwarf::DW_AT_macro_info: {
401 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
402 const DWARFDebugMacro *Macro =
403 InUnit.getContainingFile().Dwarf->getDebugMacinfo();
404 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
405 return 0;
406
407 DebugInfoOutputSection.notePatchWithOffsetUpdate(
409 &OutUnit->getOrCreateSectionDescriptor(
412 }
413 } break;
414 case dwarf::DW_AT_macros: {
415 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
416 const DWARFDebugMacro *Macro =
417 InUnit.getContainingFile().Dwarf->getDebugMacro();
418 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
419 return 0;
420
421 DebugInfoOutputSection.notePatchWithOffsetUpdate(
423 &OutUnit->getOrCreateSectionDescriptor(
426 }
427 } break;
428 case dwarf::DW_AT_stmt_list: {
429 DebugInfoOutputSection.notePatchWithOffsetUpdate(
430 DebugOffsetPatch{AttrOutOffset, &OutUnit->getOrCreateSectionDescriptor(
433 } break;
434 case dwarf::DW_AT_str_offsets_base: {
435 DebugInfoOutputSection.notePatchWithOffsetUpdate(
437 &OutUnit->getOrCreateSectionDescriptor(
439 true},
441
442 // Use size of .debug_str_offsets header as attribute value. The offset
443 // to .debug_str_offsets would be added later while patching.
444 AttrInfo.HasStringOffsetBaseAttr = true;
445 return Generator
446 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form,
447 OutUnit->getDebugStrOffsetsHeaderSize())
448 .second;
449 } break;
450 case dwarf::DW_AT_decl_file: {
451 // Value of DW_AT_decl_file may exceed original form. Longer
452 // form can affect offsets to the following attributes. To not
453 // update offsets of the following attributes we always remove
454 // original DW_AT_decl_file and attach it to the last position
455 // later.
456 if (OutUnit.isTypeUnit()) {
457 if (std::optional<std::pair<StringRef, StringRef>> DirAndFilename =
458 InUnit.getDirAndFilenameFromLineTable(Val))
460 OutDIE,
461 InUnit.getDieTypeEntry(InputDIEIdx),
462 OutUnit->getGlobalData()
463 .getStringPool()
464 .insert(DirAndFilename->first)
465 .first,
466 OutUnit->getGlobalData()
467 .getStringPool()
468 .insert(DirAndFilename->second)
469 .first,
470 });
471 return 0;
472 }
473 } break;
474 default: {
475 } break;
476 };
477
478 uint64_t Value;
479 if (AttrSpec.Attr == dwarf::DW_AT_const_value &&
480 (InputDieEntry->getTag() == dwarf::DW_TAG_variable ||
481 InputDieEntry->getTag() == dwarf::DW_TAG_constant))
482 AttrInfo.HasLiveAddress = true;
483
484 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
485 if (auto OptionalValue = Val.getAsUnsignedConstant())
486 Value = *OptionalValue;
487 else if (auto OptionalValue = Val.getAsSignedConstant())
488 Value = *OptionalValue;
489 else if (auto OptionalValue = Val.getAsSectionOffset())
490 Value = *OptionalValue;
491 else {
492 InUnit.warn("unsupported scalar attribute form. Dropping attribute.",
494 return 0;
495 }
496
497 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
498 AttrInfo.IsDeclaration = true;
499
500 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
501 return Generator.addLocListAttribute(AttrSpec.Attr, AttrSpec.Form, Value)
502 .second;
503
504 return Generator.addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, Value)
505 .second;
506 }
507
508 dwarf::Form ResultingForm = AttrSpec.Form;
509 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
510 // DWARFLinker does not generate .debug_addr table. Thus we need to change
511 // all "addrx" related forms to "addr" version. Change DW_FORM_rnglistx
512 // to DW_FORM_sec_offset here.
513 std::optional<uint64_t> Index = Val.getAsSectionOffset();
514 if (!Index) {
515 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
516 return 0;
517 }
518 std::optional<uint64_t> Offset =
519 InUnit.getOrigUnit().getRnglistOffset(*Index);
520 if (!Offset) {
521 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
522 return 0;
523 }
524
525 Value = *Offset;
526 ResultingForm = dwarf::DW_FORM_sec_offset;
527 } else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
528 // DWARFLinker does not generate .debug_addr table. Thus we need to change
529 // all "addrx" related forms to "addr" version. Change DW_FORM_loclistx
530 // to DW_FORM_sec_offset here.
531 std::optional<uint64_t> Index = Val.getAsSectionOffset();
532 if (!Index) {
533 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
534 return 0;
535 }
536 std::optional<uint64_t> Offset =
537 InUnit.getOrigUnit().getLoclistOffset(*Index);
538 if (!Offset) {
539 InUnit.warn("cann't read the attribute. Dropping.", InputDieEntry);
540 return 0;
541 }
542
543 Value = *Offset;
544 ResultingForm = dwarf::DW_FORM_sec_offset;
545 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
546 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit) {
547 if (!OutUnit.isCompileUnit())
548 return 0;
549
550 std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc();
551 if (!LowPC)
552 return 0;
553 // Dwarf >= 4 high_pc is an size, not an address.
554 Value = OutUnit.getAsCompileUnit()->getHighPc() - *LowPC;
555 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
556 Value = *Val.getAsSectionOffset();
557 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
558 Value = *Val.getAsSignedConstant();
559 else if (auto OptionalValue = Val.getAsUnsignedConstant())
560 Value = *OptionalValue;
561 else {
562 InUnit.warn("unsupported scalar attribute form. Dropping attribute.",
564 return 0;
565 }
566
567 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
568 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
569 // Create patch for the range offset value.
570 DebugInfoOutputSection.notePatchWithOffsetUpdate(
572 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit},
574 AttrInfo.HasRanges = true;
575 } else if (DWARFAttribute::mayHaveLocationList(AttrSpec.Attr) &&
578 InUnit.getOrigUnit().getVersion())) {
579 int64_t AddrAdjustmentValue = 0;
581 AddrAdjustmentValue = *VarAddressAdjustment;
582 else if (FuncAddressAdjustment)
583 AddrAdjustmentValue = *FuncAddressAdjustment;
584
585 // Create patch for the location offset value.
586 DebugInfoOutputSection.notePatchWithOffsetUpdate(
587 DebugLocPatch{{AttrOutOffset}, AddrAdjustmentValue}, PatchesOffsets);
588 } else if (AttrSpec.Attr == dwarf::DW_AT_addr_base) {
589 DebugInfoOutputSection.notePatchWithOffsetUpdate(
592 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugAddr),
593 true},
595
596 // Use size of .debug_addr header as attribute value. The offset to
597 // .debug_addr would be added later while patching.
598 AttrInfo.HasAddrBaseAttr = true;
599 return Generator
600 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form,
601 OutUnit->getDebugAddrHeaderSize())
602 .second;
603 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
604 AttrInfo.IsDeclaration = true;
605
606 // DW_AT_LLVM_stmt_sequence refers to line info in this unit's
607 // .debug_line contribution, which only exists for compile units.
608 // DependencyTracker can route a module-scope subprogram to a type
609 // unit when ODR deduplication applies (see
610 // DependencyTracker.cpp: DW_TAG_subprogram case), so drop the
611 // attribute on that path — mirroring how cloneBlockAttr handles
612 // type-unit placement.
613 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence &&
614 !OutUnit.isCompileUnit())
615 return 0;
616
617 // A compile unit's high_pc comes from the unit's own linked range and spans
618 // every symbol in it.
619 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
620 InputDieEntry->getTag() != dwarf::DW_TAG_compile_unit)
621 Value = constrainHighPC(Value, /*IsLength=*/true);
622
623 auto Result =
624 Generator.addScalarAttribute(AttrSpec.Attr, ResultingForm, Value);
625 // Record DW_AT_LLVM_stmt_sequence so the attribute value can be
626 // rewritten with the correct .debug_line offset after the line table
627 // for this CU has been emitted. We also register a DebugOffsetPatch so
628 // that the final-section offset of .debug_line gets added when the
629 // section is placed in the combined output.
630 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
631 // Record the attribute's raw input stmt-sequence offset. Resolution
632 // to a first-row index — including the boundary-walk fallback for
633 // sequences the DWARF parser may not have registered — happens in
634 // a post-cloning pass (buildStmtSeqOffsetToFirstRowIndex), so that
635 // matches the classic linker's behaviour.
636 OutUnit.getAsCompileUnit()->noteStmtSeqListAttribute(&Result.first, Value);
637 DebugInfoOutputSection.notePatchWithOffsetUpdate(
640 &OutUnit->getOrCreateSectionDescriptor(DebugSectionKind::DebugLine),
641 /*AddLocalValue=*/true},
643 }
644 return Result.second;
645}
646
649
650 for (const DWARFExpression::Operation &Op : Expr) {
651 switch (Op.getCode()) {
652 case dwarf::DW_OP_addr:
653 case dwarf::DW_OP_addrx:
654 case dwarf::DW_OP_constx:
655 return true;
656 default:
657 break;
658 }
659
660 if (llvm::is_contained(Op.getDescription().Op, Encoding::BaseTypeRef))
661 return true;
662 }
663
664 return false;
665}
666
668 const DWARFFormValue &Val,
670
671 size_t NumberOfPatchesAtStart = PatchesOffsets.size();
672
673 // If the block is a DWARF Expression, clone it into the temporary
674 // buffer using cloneExpression(), otherwise copy the data directly.
676 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
680 DataExtractor Data(Bytes, InUnit.getOrigUnit().isLittleEndian());
681 DWARFExpression Expr(Data, InUnit.getOrigUnit().getAddressByteSize(),
682 InUnit.getFormParams().Format);
683
684 // A type unit is shared by every compile unit that references the type, so
685 // an expression resolving against one origin unit has no single correct
686 // value there.
687 if (OutUnit.isTypeUnit() && expressionDependsOnOriginUnit(Expr))
688 return 0;
689
690 if (SaveRelocs)
691 Source.Expression.emplace(Bytes.size());
692 InUnit.cloneDieAttrExpression(
694 PatchesOffsets, Source.Expression ? &*Source.Expression : nullptr);
695 Bytes = Buffer;
696 }
697
698 // The expression location data might be updated and exceed the original size.
699 // Check whether the new data fits into the original form.
700 dwarf::Form ResultForm = AttrSpec.Form;
701 if ((ResultForm == dwarf::DW_FORM_block1 && Bytes.size() > UINT8_MAX) ||
702 (ResultForm == dwarf::DW_FORM_block2 && Bytes.size() > UINT16_MAX) ||
703 (ResultForm == dwarf::DW_FORM_block4 && Bytes.size() > UINT32_MAX))
704 ResultForm = dwarf::DW_FORM_block;
705
706 size_t FinalAttributeSize;
707 if (AttrSpec.Form == dwarf::DW_FORM_exprloc)
708 FinalAttributeSize =
709 Generator.addLocationAttribute(AttrSpec.Attr, ResultForm, Bytes).second;
710 else
711 FinalAttributeSize =
712 Generator.addBlockAttribute(AttrSpec.Attr, ResultForm, Bytes).second;
713
714 // Update patches offsets with the size of length field for Bytes.
715 for (size_t Idx = NumberOfPatchesAtStart; Idx < PatchesOffsets.size();
716 Idx++) {
717 assert(FinalAttributeSize > Bytes.size());
718 *PatchesOffsets[Idx] +=
719 (AttrOutOffset + (FinalAttributeSize - Bytes.size()));
720 }
721
722 if (Source.Expression)
723 Source.Expression->addOutputPrefix(FinalAttributeSize - Bytes.size());
724
726 AttrInfo.HasLiveAddress =
727 VarAddressAdjustment.has_value() ||
728 InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
729
730 return FinalAttributeSize;
731}
732
734 const DWARFFormValue &Val,
736 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
737 AttrInfo.HasLiveAddress = true;
738
739 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
740 return Generator
741 .addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, Val.getRawUValue())
742 .second;
743
744 if (OutUnit.isTypeUnit())
745 return 0;
746
747 // Cloned Die may have address attributes relocated to a
748 // totally unrelated value. This can happen:
749 // - If high_pc is an address (Dwarf version == 2), then it might have been
750 // relocated to a totally unrelated value (because the end address in the
751 // object file might be start address of another function which got moved
752 // independently by the linker).
753 // - If address relocated in an inline_subprogram that happens at the
754 // beginning of its inlining function.
755 // To avoid above cases and to not apply relocation twice (in
756 // applyValidRelocs and here), read address attribute from InputDIE and apply
757 // Info.PCOffset here.
758
759 std::optional<DWARFFormValue> AddrAttribute =
760 InUnit.find(InputDieEntry, AttrSpec.Attr);
761 if (!AddrAttribute)
762 llvm_unreachable("Cann't find attribute");
763
764 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
765 if (!Addr) {
766 InUnit.warn("cann't read address attribute value.");
767 return 0;
768 }
769
770 if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
771 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
772 if (std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc())
773 Addr = *LowPC;
774 else
775 return 0;
776 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
777 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
778 if (uint64_t HighPc = OutUnit.getAsCompileUnit()->getHighPc())
779 Addr = HighPc;
780 else
781 return 0;
782 } else {
783 if (AttrSpec.Attr == dwarf::DW_AT_high_pc)
784 Addr = constrainHighPC(*Addr, /*IsLength=*/false);
786 *Addr += *VarAddressAdjustment;
787 else if (FuncAddressAdjustment)
788 *Addr += *FuncAddressAdjustment;
789 }
790
791 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
792 return Generator.addScalarAttribute(AttrSpec.Attr, AttrSpec.Form, *Addr)
793 .second;
794 }
795
796 uint64_t AddrIndex = OutUnit.getAsCompileUnit()->getDebugAddrIndex(*Addr);
797
798 std::optional<uint64_t> InputOffset =
799 InUnit.getOrigUnit().getIndexedAddressOffset(Val.getRawUValue());
800 if (InputOffset)
801 Source.Entry = RelocationFixups::DebugAddrEntry{*InputOffset, AddrIndex};
802
803 return Generator
804 .addScalarAttribute(AttrSpec.Attr, dwarf::Form::DW_FORM_addrx, AddrIndex)
805 .second;
806}
807
808uint64_t DIEAttributeCloner::constrainHighPC(uint64_t HighPC, bool IsLength) {
810 return HighPC;
811 std::optional<uint64_t> LowPC =
812 dwarf::toAddress(InUnit.find(InputDieEntry, dwarf::DW_AT_low_pc));
813 if (!LowPC)
814 return HighPC;
815 uint64_t Constrained =
816 InUnit.getContainingFile().Addresses->constrainCodeRangeHighPC(
817 *LowPC, IsLength ? *LowPC + HighPC : HighPC, *FuncAddressAdjustment);
818 return IsLength ? Constrained - *LowPC : Constrained;
819}
820
821unsigned DIEAttributeCloner::finalizeAbbreviations(bool HasChildrenToClone) {
822 // Add the size of the abbreviation number to the output offset.
823 size_t AbbrevNumberSize =
824 Generator.finalizeAbbreviations(HasChildrenToClone, &PatchesOffsets);
825 AttrOutOffset += AbbrevNumberSize;
826 if (SaveRelocs)
827 OutUnit.getAsCompileUnit()->getRelocFixups().finishDIE(AbbrevNumberSize);
828
829 return AttrOutOffset;
830}
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.
size_t addStringAttr(dwarf::Attribute Attr, StringEntry *String)
Add the string attribute Attr, in the string form of the unit.
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:30
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.
Attribute
Attributes.
Definition Dwarf.h:125
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