LLVM 23.0.0git
DWARFLinkerCompileUnit.cpp
Go to the documentation of this file.
1//=== DWARFLinkerCompileUnit.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
11#include "DIEAttributeCloner.h"
12#include "DIEGenerator.h"
13#include "DependencyTracker.h"
20#include "llvm/Support/Path.h"
21#include <utility>
22
23using namespace llvm;
24using namespace dwarf_linker;
25using namespace dwarf_linker::parallel;
26
29 OffsetToUnitTy UnitFromOffset,
31 : DwarfUnit(GlobalData, ID, ClangModuleName), File(File),
32 getUnitFromOffset(UnitFromOffset), Stage(Stage::CreatedNotLoaded),
33 AcceleratorRecords(&GlobalData.getAllocator()) {
34 UnitName = File.FileName;
35 setOutputFormat(Format, Endianess);
37}
38
41 DWARFFile &File, OffsetToUnitTy UnitFromOffset,
43 : DwarfUnit(GlobalData, ID, ClangModuleName), File(File),
44 OrigUnit(&OrigUnit), getUnitFromOffset(UnitFromOffset),
46 AcceleratorRecords(&GlobalData.getAllocator()) {
47 setOutputFormat(Format, Endianess);
49
50 DWARFDie CUDie = OrigUnit.getUnitDIE();
51 if (!CUDie)
52 return;
53
54 Language = CUDie.getLanguage();
55
56 if (!GlobalData.getOptions().NoODR && Language.has_value() &&
57 isODRLanguage(*Language))
58 NoODR = false;
59
60 if (const char *CUName = CUDie.getName(DINameKind::ShortName))
61 UnitName = CUName;
62 else
63 UnitName = File.FileName;
64 SysRoot = dwarf::toStringRef(CUDie.find(dwarf::DW_AT_LLVM_sysroot)).str();
65}
66
68 LineTablePtr = File.Dwarf->getLineTableForUnit(&getOrigUnit());
69}
70
72 // Nothing to reset if stage is less than "Loaded".
73 if (getStage() < Stage::Loaded)
74 return;
75
76 // Note: We need to do erasing for "Loaded" stage because
77 // if live analysys failed then we will have "Loaded" stage
78 // with marking from "LivenessAnalysisDone" stage partially
79 // done. That marking should be cleared.
80
81 for (DIEInfo &Info : DieInfoArray)
82 Info.unsetFlagsWhichSetDuringLiveAnalysis();
83
84 LowPc = std::nullopt;
85 HighPc = 0;
86 Labels.clear();
87 Ranges.clear();
88 Dependencies.reset(nullptr);
89
90 if (getStage() < Stage::Cloned) {
92 return;
93 }
94
95 AcceleratorRecords.erase();
96 AbbreviationsSet.clear();
97 Abbreviations.clear();
98 OutUnitDIE = nullptr;
99 DebugAddrIndexMap.clear();
100 StmtSeqListAttributes.clear();
101
102 llvm::fill(OutDieOffsetArray, 0);
103 llvm::fill(TypeEntries, nullptr);
105
107}
108
110 DWARFDie InputUnitDIE = getUnitDIE(false);
111 if (!InputUnitDIE)
112 return false;
113
114 // load input dies, resize Info structures array.
115 DieInfoArray.resize(getOrigUnit().getNumDIEs());
116 OutDieOffsetArray.resize(getOrigUnit().getNumDIEs(), 0);
117 if (!NoODR)
118 TypeEntries.resize(getOrigUnit().getNumDIEs());
119 return true;
120}
121
122void CompileUnit::analyzeDWARFStructureRec(const DWARFDebugInfoEntry *DieEntry,
123 bool IsODRUnavailableFunctionScope) {
124 CompileUnit::DIEInfo &DieInfo = getDIEInfo(DieEntry);
125
126 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(DieEntry);
127 CurChild && CurChild->getAbbreviationDeclarationPtr();
128 CurChild = getSiblingEntry(CurChild)) {
129 CompileUnit::DIEInfo &ChildInfo = getDIEInfo(CurChild);
130 bool ChildIsODRUnavailableFunctionScope = IsODRUnavailableFunctionScope;
131
132 if (DieInfo.getIsInMouduleScope())
133 ChildInfo.setIsInMouduleScope();
134
135 if (DieInfo.getIsInFunctionScope())
136 ChildInfo.setIsInFunctionScope();
137
138 if (DieInfo.getIsInAnonNamespaceScope())
139 ChildInfo.setIsInAnonNamespaceScope();
140
141 switch (CurChild->getTag()) {
142 case dwarf::DW_TAG_module:
143 ChildInfo.setIsInMouduleScope();
144 if (DieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
145 dwarf::toString(find(CurChild, dwarf::DW_AT_name), "") !=
147 analyzeImportedModule(CurChild);
148 break;
149 case dwarf::DW_TAG_subprogram:
150 ChildInfo.setIsInFunctionScope();
151 if (!ChildIsODRUnavailableFunctionScope &&
152 !ChildInfo.getIsInMouduleScope()) {
153 if (find(CurChild,
154 {dwarf::DW_AT_abstract_origin, dwarf::DW_AT_specification}))
155 ChildIsODRUnavailableFunctionScope = true;
156 }
157 break;
158 case dwarf::DW_TAG_namespace: {
159 UnitEntryPairTy NamespaceEntry = {this, CurChild};
160
161 if (find(CurChild, dwarf::DW_AT_extension))
162 NamespaceEntry = NamespaceEntry.getNamespaceOrigin();
163
164 if (!NamespaceEntry.CU->find(NamespaceEntry.DieEntry, dwarf::DW_AT_name))
165 ChildInfo.setIsInAnonNamespaceScope();
166 } break;
167 default:
168 break;
169 }
170
171 if (!isClangModule() && !getGlobalData().getOptions().UpdateIndexTablesOnly)
172 ChildInfo.setTrackLiveness();
173
174 if ((!ChildInfo.getIsInAnonNamespaceScope() &&
175 !ChildIsODRUnavailableFunctionScope && !NoODR))
176 ChildInfo.setODRAvailable();
177
178 if (CurChild->hasChildren())
179 analyzeDWARFStructureRec(CurChild, ChildIsODRUnavailableFunctionScope);
180 }
181}
182
184 StringPool &GlobalStrings) {
185 if (LineTablePtr) {
186 if (LineTablePtr->hasFileAtIndex(FileIdx)) {
187 // Cache the resolved paths based on the index in the line table,
188 // because calling realpath is expensive.
189 ResolvedPathsMap::const_iterator It = ResolvedFullPaths.find(FileIdx);
190 if (It == ResolvedFullPaths.end()) {
191 std::string OrigFileName;
192 bool FoundFileName = LineTablePtr->getFileNameByIndex(
193 FileIdx, getOrigUnit().getCompilationDir(),
195 OrigFileName);
196 (void)FoundFileName;
197 assert(FoundFileName && "Must get file name from line table");
198
199 // Second level of caching, this time based on the file's parent
200 // path.
201 StringRef FileName = sys::path::filename(OrigFileName);
202 StringRef ParentPath = sys::path::parent_path(OrigFileName);
203
204 // If the ParentPath has not yet been resolved, resolve and cache it for
205 // future look-ups.
207 ResolvedParentPaths.find(ParentPath);
208 if (ParentIt == ResolvedParentPaths.end()) {
209 SmallString<256> RealPath;
210 sys::fs::real_path(ParentPath, RealPath);
211 ParentIt =
212 ResolvedParentPaths
213 .insert({ParentPath, GlobalStrings.insert(RealPath).first})
214 .first;
215 }
216
217 // Join the file name again with the resolved path.
218 SmallString<256> ResolvedPath(ParentIt->second->first());
219 sys::path::append(ResolvedPath, FileName);
220
221 It = ResolvedFullPaths
222 .insert(std::make_pair(
223 FileIdx, GlobalStrings.insert(ResolvedPath).first))
224 .first;
225 }
226
227 return It->second;
228 }
229 }
230
231 return nullptr;
232}
233
235 if (ObjFileIdx > std::numeric_limits<uint32_t>::max())
236 return llvm::createStringError("cannot compute priority when number of "
237 "object files exceeds UINT32_MAX");
238 if (LocalIdx > std::numeric_limits<uint32_t>::max())
239 return llvm::createStringError("cannot compute priority when number of "
240 "local index exceeds UINT32_MAX");
241
242 Priority = (ObjFileIdx << 32) | LocalIdx;
243 return llvm::Error::success();
244}
245
247 AbbreviationsSet.clear();
248 ResolvedFullPaths.shrink_and_clear();
249 ResolvedParentPaths.clear();
250 FileNames.shrink_and_clear();
251 DieInfoArray = SmallVector<DIEInfo>();
252 OutDieOffsetArray = SmallVector<uint64_t>();
253 TypeEntries = SmallVector<TypeEntry *>();
254 Dependencies.reset(nullptr);
255 StmtSeqListAttributes.clear();
256 getOrigUnit().clear();
257}
258
259/// Collect references to parseable Swift interfaces in imported
260/// DW_TAG_module blocks.
262 if (!Language || Language != dwarf::DW_LANG_Swift)
263 return;
264
265 if (!GlobalData.getOptions().ParseableSwiftInterfaces)
266 return;
267
268 StringRef Path =
269 dwarf::toStringRef(find(DieEntry, dwarf::DW_AT_LLVM_include_path));
270 if (!Path.ends_with(".swiftinterface"))
271 return;
272 // Don't track interfaces that are part of the SDK.
274 dwarf::toStringRef(find(DieEntry, dwarf::DW_AT_LLVM_sysroot));
275 if (SysRoot.empty())
277 if (!SysRoot.empty() && Path.starts_with(SysRoot))
278 return;
279 // Don't track interfaces that are part of the toolchain.
280 // For example: Swift, _Concurrency, ...
281 StringRef DeveloperDir = guessDeveloperDir(SysRoot);
282 if (!DeveloperDir.empty() && Path.starts_with(DeveloperDir))
283 return;
284 if (isInToolchainDir(Path))
285 return;
286 if (std::optional<DWARFFormValue> Val = find(DieEntry, dwarf::DW_AT_name)) {
287 Expected<const char *> Name = Val->getAsCString();
288 if (!Name) {
289 warn(Name.takeError());
290 return;
291 }
292
293 // The prepend path is applied later when copying.
294 SmallString<128> ResolvedPath;
295 if (sys::path::is_relative(Path))
297 ResolvedPath,
298 dwarf::toString(getUnitDIE().find(dwarf::DW_AT_comp_dir), ""));
299 sys::path::append(ResolvedPath, Path);
300
301 // Stage the entry. It will be merged into the shared
302 // ParseableSwiftInterfaces map after the parallel analysis phase so that
303 // the final contents and any conflict warnings are deterministic.
304 PendingSwiftInterfaces.emplace_back(*Name, ResolvedPath);
305 }
306}
307
310 for (auto &Pending : PendingSwiftInterfaces) {
311 auto &Entry = Map[Pending.ModuleName];
312 if (!Entry.empty() && Entry != Pending.ResolvedPath)
313 warn(Twine("conflicting parseable interfaces for Swift Module ") +
314 Pending.ModuleName + ": " + Entry + " and " + Pending.ResolvedPath +
315 ".");
316 Entry = Pending.ResolvedPath;
317 }
318 PendingSwiftInterfaces.clear();
319}
320
322 if (!getUnitDIE().isValid())
323 return Error::success();
324
325 SyntheticTypeNameBuilder NameBuilder(TypePoolRef);
326 return assignTypeNamesRec(getDebugInfoEntry(0), NameBuilder);
327}
328
329Error CompileUnit::assignTypeNamesRec(const DWARFDebugInfoEntry *DieEntry,
330 SyntheticTypeNameBuilder &NameBuilder) {
331 OrderedChildrenIndexAssigner ChildrenIndexAssigner(*this, DieEntry);
332 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(DieEntry);
333 CurChild && CurChild->getAbbreviationDeclarationPtr();
334 CurChild = getSiblingEntry(CurChild)) {
335 CompileUnit::DIEInfo &ChildInfo = getDIEInfo(CurChild);
336 if (!ChildInfo.needToPlaceInTypeTable())
337 continue;
338
339 assert(ChildInfo.getODRAvailable());
340 if (Error Err = NameBuilder.assignName(
341 {this, CurChild},
342 ChildrenIndexAssigner.getChildIndex(*this, CurChild)))
343 return Err;
344
345 if (Error Err = assignTypeNamesRec(CurChild, NameBuilder))
346 return Err;
347 }
348
349 return Error::success();
350}
351
353 if (std::optional<SectionDescriptor *> DebugInfoSection =
355
356 (*DebugInfoSection)
357 ->ListDebugDieRefPatch.forEach([&](DebugDieRefPatch &Patch) {
358 /// Replace stored DIE indexes with DIE output offsets.
360 Patch.RefCU.getPointer()->getDieOutOffset(
362 });
363
364 (*DebugInfoSection)
365 ->ListDebugULEB128DieRefPatch.forEach(
366 [&](DebugULEB128DieRefPatch &Patch) {
367 /// Replace stored DIE indexes with DIE output offsets.
369 Patch.RefCU.getPointer()->getDieOutOffset(
371 });
372 }
373
374 if (std::optional<SectionDescriptor *> DebugLocSection =
376 (*DebugLocSection)
377 ->ListDebugULEB128DieRefPatch.forEach(
378 [](DebugULEB128DieRefPatch &Patch) {
379 /// Replace stored DIE indexes with DIE output offsets.
381 Patch.RefCU.getPointer()->getDieOutOffset(
383 });
384 }
385
386 if (std::optional<SectionDescriptor *> DebugLocListsSection =
388 (*DebugLocListsSection)
389 ->ListDebugULEB128DieRefPatch.forEach(
390 [](DebugULEB128DieRefPatch &Patch) {
391 /// Replace stored DIE indexes with DIE output offsets.
393 Patch.RefCU.getPointer()->getDieOutOffset(
395 });
396 }
397}
398
399std::optional<UnitEntryPairTy> CompileUnit::resolveDIEReference(
400 const DWARFFormValue &RefValue,
401 ResolveInterCUReferencesMode CanResolveInterCUReferences) {
402 CompileUnit *RefCU;
403 uint64_t RefDIEOffset;
404 if (std::optional<uint64_t> Offset = RefValue.getAsRelativeReference()) {
405 RefCU = this;
406 RefDIEOffset = RefValue.getUnit()->getOffset() + *Offset;
407 } else if (Offset = RefValue.getAsDebugInfoReference(); Offset) {
408 RefCU = getUnitFromOffset(*Offset);
409 RefDIEOffset = *Offset;
410 } else {
411 return std::nullopt;
412 }
413
414 if (RefCU == this) {
415 // Referenced DIE is in current compile unit.
416 if (std::optional<uint32_t> RefDieIdx =
417 getDIEIndexForOffset(RefDIEOffset)) {
418 const DWARFDebugInfoEntry *RefEntry = getDebugInfoEntry(*RefDieIdx);
419 // In a file with broken references, an attribute might point to a
420 // NULL DIE. Treat that as a resolution failure so callers can warn.
421 if (RefEntry && RefEntry->getAbbreviationDeclarationPtr())
422 return UnitEntryPairTy{this, RefEntry};
423 }
424 } else if (RefCU && CanResolveInterCUReferences) {
425 // Referenced DIE is in other compile unit.
426
427 // Check whether DIEs are loaded for that compile unit.
428 enum Stage ReferredCUStage = RefCU->getStage();
429 if (ReferredCUStage < Stage::Loaded || ReferredCUStage > Stage::Cloned)
430 return UnitEntryPairTy{RefCU, nullptr};
431
432 if (std::optional<uint32_t> RefDieIdx =
433 RefCU->getDIEIndexForOffset(RefDIEOffset)) {
434 const DWARFDebugInfoEntry *RefEntry =
435 RefCU->getDebugInfoEntry(*RefDieIdx);
436 if (RefEntry && RefEntry->getAbbreviationDeclarationPtr())
437 return UnitEntryPairTy{RefCU, RefEntry};
438 }
439 } else {
440 return UnitEntryPairTy{RefCU, nullptr};
441 }
442 return std::nullopt;
443}
444
445std::optional<UnitEntryPairTy> CompileUnit::resolveDIEReference(
446 const DWARFDebugInfoEntry *DieEntry, dwarf::Attribute Attr,
447 ResolveInterCUReferencesMode CanResolveInterCUReferences) {
448 if (std::optional<DWARFFormValue> AttrVal = find(DieEntry, Attr))
449 return resolveDIEReference(*AttrVal, CanResolveInterCUReferences);
450
451 return std::nullopt;
452}
453
454void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
455 int64_t PcOffset) {
456 std::lock_guard<std::mutex> Guard(RangesMutex);
457
458 Ranges.insert({FuncLowPc, FuncHighPc}, PcOffset);
459 if (LowPc)
460 LowPc = std::min(*LowPc, FuncLowPc + PcOffset);
461 else
462 LowPc = FuncLowPc + PcOffset;
463 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
464}
465
466void CompileUnit::addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset) {
467 std::lock_guard<std::mutex> Guard(LabelsMutex);
468 Labels.insert({LabelLowPc, PcOffset});
469}
470
472 if (getGlobalData().getOptions().UpdateIndexTablesOnly)
473 return Error::success();
474
475 if (getOrigUnit().getVersion() < 5) {
476 emitLocations(DebugSectionKind::DebugLoc);
477 return Error::success();
478 }
479
480 emitLocations(DebugSectionKind::DebugLocLists);
481 return Error::success();
482}
483
484void CompileUnit::emitLocations(DebugSectionKind LocationSectionKind) {
485 SectionDescriptor &DebugInfoSection =
487
488 if (!DebugInfoSection.ListDebugLocPatch.empty()) {
489 SectionDescriptor &OutLocationSection =
490 getOrCreateSectionDescriptor(LocationSectionKind);
491 DWARFUnit &OrigUnit = getOrigUnit();
492
493 uint64_t OffsetAfterUnitLength = emitLocListHeader(OutLocationSection);
494
495 DebugInfoSection.ListDebugLocPatch.forEach([&](DebugLocPatch &Patch) {
496 // Get location expressions vector corresponding to the current
497 // attribute from the source DWARF.
498 uint64_t InputDebugLocSectionOffset = DebugInfoSection.getIntVal(
499 Patch.PatchOffset,
500 DebugInfoSection.getFormParams().getDwarfOffsetByteSize());
502 OrigUnit.findLoclistFromOffset(InputDebugLocSectionOffset);
503
504 if (!OriginalLocations) {
505 warn(OriginalLocations.takeError());
506 return;
507 }
508
509 LinkedLocationExpressionsVector LinkedLocationExpressions;
510 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
511 LinkedLocationExpressionsWithOffsetPatches LinkedExpression;
512
513 if (CurExpression.Range) {
514 // Relocate address range.
515 LinkedExpression.Expression.Range = {
516 CurExpression.Range->LowPC + Patch.AddrAdjustmentValue,
517 CurExpression.Range->HighPC + Patch.AddrAdjustmentValue};
518 }
519
520 DataExtractor Data(CurExpression.Expr, OrigUnit.isLittleEndian());
521
522 DWARFExpression InputExpression(Data, OrigUnit.getAddressByteSize(),
523 OrigUnit.getFormParams().Format);
524 cloneDieAttrExpression(InputExpression,
525 LinkedExpression.Expression.Expr,
526 OutLocationSection, Patch.AddrAdjustmentValue,
527 LinkedExpression.Patches);
528
529 LinkedLocationExpressions.push_back({LinkedExpression});
530 }
531
532 // Emit locations list table fragment corresponding to the CurLocAttr.
533 DebugInfoSection.apply(Patch.PatchOffset, dwarf::DW_FORM_sec_offset,
534 OutLocationSection.OS.tell());
535 emitLocListFragment(LinkedLocationExpressions, OutLocationSection);
536 });
537
538 if (OffsetAfterUnitLength > 0) {
539 assert(OffsetAfterUnitLength -
540 OutLocationSection.getFormParams().getDwarfOffsetByteSize() <
541 OffsetAfterUnitLength);
542 OutLocationSection.apply(
543 OffsetAfterUnitLength -
544 OutLocationSection.getFormParams().getDwarfOffsetByteSize(),
545 dwarf::DW_FORM_sec_offset,
546 OutLocationSection.OS.tell() - OffsetAfterUnitLength);
547 }
548 }
549}
550
551/// Emit debug locations(.debug_loc, .debug_loclists) header.
552uint64_t CompileUnit::emitLocListHeader(SectionDescriptor &OutLocationSection) {
553 if (getOrigUnit().getVersion() < 5)
554 return 0;
555
556 // unit_length.
557 OutLocationSection.emitUnitLength(0xBADDEF);
558 uint64_t OffsetAfterUnitLength = OutLocationSection.OS.tell();
559
560 // Version.
561 OutLocationSection.emitIntVal(5, 2);
562
563 // Address size.
564 OutLocationSection.emitIntVal(OutLocationSection.getFormParams().AddrSize, 1);
565
566 // Seg_size
567 OutLocationSection.emitIntVal(0, 1);
568
569 // Offset entry count
570 OutLocationSection.emitIntVal(0, 4);
571
572 return OffsetAfterUnitLength;
573}
574
575/// Emit debug locations(.debug_loc, .debug_loclists) fragment.
576uint64_t CompileUnit::emitLocListFragment(
577 const LinkedLocationExpressionsVector &LinkedLocationExpression,
578 SectionDescriptor &OutLocationSection) {
579 uint64_t OffsetBeforeLocationExpression = 0;
580
581 if (getOrigUnit().getVersion() < 5) {
582 uint64_t BaseAddress = 0;
583 if (std::optional<uint64_t> LowPC = getLowPc())
584 BaseAddress = *LowPC;
585
586 for (const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
587 LinkedLocationExpression) {
588 if (LocExpression.Expression.Range) {
589 OutLocationSection.emitIntVal(
590 LocExpression.Expression.Range->LowPC - BaseAddress,
591 OutLocationSection.getFormParams().AddrSize);
592 OutLocationSection.emitIntVal(
593 LocExpression.Expression.Range->HighPC - BaseAddress,
594 OutLocationSection.getFormParams().AddrSize);
595 }
596
597 OutLocationSection.emitIntVal(LocExpression.Expression.Expr.size(), 2);
598 OffsetBeforeLocationExpression = OutLocationSection.OS.tell();
599 for (uint64_t *OffsetPtr : LocExpression.Patches)
600 *OffsetPtr += OffsetBeforeLocationExpression;
601
602 OutLocationSection.OS
603 << StringRef((const char *)LocExpression.Expression.Expr.data(),
604 LocExpression.Expression.Expr.size());
605 }
606
607 // Emit the terminator entry.
608 OutLocationSection.emitIntVal(0,
609 OutLocationSection.getFormParams().AddrSize);
610 OutLocationSection.emitIntVal(0,
611 OutLocationSection.getFormParams().AddrSize);
612 return OffsetBeforeLocationExpression;
613 }
614
615 std::optional<uint64_t> BaseAddress;
616 for (const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
617 LinkedLocationExpression) {
618 if (LocExpression.Expression.Range) {
619 // Check whether base address is set. If it is not set yet
620 // then set current base address and emit base address selection entry.
621 if (!BaseAddress) {
622 BaseAddress = LocExpression.Expression.Range->LowPC;
623
624 // Emit base address.
625 OutLocationSection.emitIntVal(dwarf::DW_LLE_base_addressx, 1);
626 encodeULEB128(DebugAddrIndexMap.getValueIndex(*BaseAddress),
627 OutLocationSection.OS);
628 }
629
630 // Emit type of entry.
631 OutLocationSection.emitIntVal(dwarf::DW_LLE_offset_pair, 1);
632
633 // Emit start offset relative to base address.
634 encodeULEB128(LocExpression.Expression.Range->LowPC - *BaseAddress,
635 OutLocationSection.OS);
636
637 // Emit end offset relative to base address.
638 encodeULEB128(LocExpression.Expression.Range->HighPC - *BaseAddress,
639 OutLocationSection.OS);
640 } else
641 // Emit type of entry.
642 OutLocationSection.emitIntVal(dwarf::DW_LLE_default_location, 1);
643
644 encodeULEB128(LocExpression.Expression.Expr.size(), OutLocationSection.OS);
645 OffsetBeforeLocationExpression = OutLocationSection.OS.tell();
646 for (uint64_t *OffsetPtr : LocExpression.Patches)
647 *OffsetPtr += OffsetBeforeLocationExpression;
648
649 OutLocationSection.OS << StringRef(
650 (const char *)LocExpression.Expression.Expr.data(),
651 LocExpression.Expression.Expr.size());
652 }
653
654 // Emit the terminator entry.
655 OutLocationSection.emitIntVal(dwarf::DW_LLE_end_of_list, 1);
656 return OffsetBeforeLocationExpression;
657}
658
659Error CompileUnit::emitDebugAddrSection() {
660 if (GlobalData.getOptions().UpdateIndexTablesOnly)
661 return Error::success();
662
663 if (getVersion() < 5)
664 return Error::success();
665
666 if (DebugAddrIndexMap.empty())
667 return Error::success();
668
669 SectionDescriptor &OutAddrSection =
671
672 // Emit section header.
673
674 // Emit length.
675 OutAddrSection.emitUnitLength(0xBADDEF);
676 uint64_t OffsetAfterSectionLength = OutAddrSection.OS.tell();
677
678 // Emit version.
679 OutAddrSection.emitIntVal(5, 2);
680
681 // Emit address size.
682 OutAddrSection.emitIntVal(getFormParams().AddrSize, 1);
683
684 // Emit segment size.
685 OutAddrSection.emitIntVal(0, 1);
686
687 // Emit addresses.
688 for (uint64_t AddrValue : DebugAddrIndexMap.getValues())
689 OutAddrSection.emitIntVal(AddrValue, getFormParams().AddrSize);
690
691 // Patch section length.
692 OutAddrSection.apply(
693 OffsetAfterSectionLength -
694 OutAddrSection.getFormParams().getDwarfOffsetByteSize(),
695 dwarf::DW_FORM_sec_offset,
696 OutAddrSection.OS.tell() - OffsetAfterSectionLength);
697
698 return Error::success();
699}
700
702 if (getGlobalData().getOptions().UpdateIndexTablesOnly)
703 return Error::success();
704
705 // Build set of linked address ranges for unit function ranges.
706 AddressRanges LinkedFunctionRanges;
708 LinkedFunctionRanges.insert(
709 {Range.Range.start() + Range.Value, Range.Range.end() + Range.Value});
710
711 emitAranges(LinkedFunctionRanges);
712
713 if (getOrigUnit().getVersion() < 5) {
714 cloneAndEmitRangeList(DebugSectionKind::DebugRange, LinkedFunctionRanges);
715 return Error::success();
716 }
717
718 cloneAndEmitRangeList(DebugSectionKind::DebugRngLists, LinkedFunctionRanges);
719 return Error::success();
720}
721
722void CompileUnit::cloneAndEmitRangeList(DebugSectionKind RngSectionKind,
723 AddressRanges &LinkedFunctionRanges) {
724 SectionDescriptor &DebugInfoSection =
726 SectionDescriptor &OutRangeSection =
727 getOrCreateSectionDescriptor(RngSectionKind);
728
729 if (!DebugInfoSection.ListDebugRangePatch.empty()) {
730 std::optional<AddressRangeValuePair> CachedRange;
731 uint64_t OffsetAfterUnitLength = emitRangeListHeader(OutRangeSection);
732
733 DebugRangePatch *CompileUnitRangePtr = nullptr;
734 DebugInfoSection.ListDebugRangePatch.forEach([&](DebugRangePatch &Patch) {
735 if (Patch.IsCompileUnitRanges) {
736 CompileUnitRangePtr = &Patch;
737 } else {
738 // Get ranges from the source DWARF corresponding to the current
739 // attribute.
740 AddressRanges LinkedRanges;
741 uint64_t InputDebugRangesSectionOffset = DebugInfoSection.getIntVal(
742 Patch.PatchOffset,
743 DebugInfoSection.getFormParams().getDwarfOffsetByteSize());
744 if (Expected<DWARFAddressRangesVector> InputRanges =
745 getOrigUnit().findRnglistFromOffset(
746 InputDebugRangesSectionOffset)) {
747 // Apply relocation adjustment.
748 for (const auto &Range : *InputRanges) {
749 if (!CachedRange || !CachedRange->Range.contains(Range.LowPC))
750 CachedRange =
752
753 // All range entries should lie in the function range.
754 if (!CachedRange) {
755 warn("inconsistent range data.");
756 continue;
757 }
758
759 // Store range for emiting.
760 LinkedRanges.insert({Range.LowPC + CachedRange->Value,
761 Range.HighPC + CachedRange->Value});
762 }
763 } else {
764 llvm::consumeError(InputRanges.takeError());
765 warn("invalid range list ignored.");
766 }
767
768 // Emit linked ranges.
769 DebugInfoSection.apply(Patch.PatchOffset, dwarf::DW_FORM_sec_offset,
770 OutRangeSection.OS.tell());
771 emitRangeListFragment(LinkedRanges, OutRangeSection);
772 }
773 });
774
775 if (CompileUnitRangePtr != nullptr) {
776 // Emit compile unit ranges last to be binary compatible with classic
777 // dsymutil.
778 DebugInfoSection.apply(CompileUnitRangePtr->PatchOffset,
779 dwarf::DW_FORM_sec_offset,
780 OutRangeSection.OS.tell());
781 emitRangeListFragment(LinkedFunctionRanges, OutRangeSection);
782 }
783
784 if (OffsetAfterUnitLength > 0) {
785 assert(OffsetAfterUnitLength -
786 OutRangeSection.getFormParams().getDwarfOffsetByteSize() <
787 OffsetAfterUnitLength);
788 OutRangeSection.apply(
789 OffsetAfterUnitLength -
790 OutRangeSection.getFormParams().getDwarfOffsetByteSize(),
791 dwarf::DW_FORM_sec_offset,
792 OutRangeSection.OS.tell() - OffsetAfterUnitLength);
793 }
794 }
795}
796
797uint64_t CompileUnit::emitRangeListHeader(SectionDescriptor &OutRangeSection) {
798 if (OutRangeSection.getFormParams().Version < 5)
799 return 0;
800
801 // unit_length.
802 OutRangeSection.emitUnitLength(0xBADDEF);
803 uint64_t OffsetAfterUnitLength = OutRangeSection.OS.tell();
804
805 // Version.
806 OutRangeSection.emitIntVal(5, 2);
807
808 // Address size.
809 OutRangeSection.emitIntVal(OutRangeSection.getFormParams().AddrSize, 1);
810
811 // Seg_size
812 OutRangeSection.emitIntVal(0, 1);
813
814 // Offset entry count
815 OutRangeSection.emitIntVal(0, 4);
816
817 return OffsetAfterUnitLength;
818}
819
820void CompileUnit::emitRangeListFragment(const AddressRanges &LinkedRanges,
821 SectionDescriptor &OutRangeSection) {
822 if (OutRangeSection.getFormParams().Version < 5) {
823 // Emit ranges.
824 uint64_t BaseAddress = 0;
825 if (std::optional<uint64_t> LowPC = getLowPc())
826 BaseAddress = *LowPC;
827
828 for (const AddressRange &Range : LinkedRanges) {
829 OutRangeSection.emitIntVal(Range.start() - BaseAddress,
830 OutRangeSection.getFormParams().AddrSize);
831 OutRangeSection.emitIntVal(Range.end() - BaseAddress,
832 OutRangeSection.getFormParams().AddrSize);
833 }
834
835 // Add the terminator entry.
836 OutRangeSection.emitIntVal(0, OutRangeSection.getFormParams().AddrSize);
837 OutRangeSection.emitIntVal(0, OutRangeSection.getFormParams().AddrSize);
838 return;
839 }
840
841 std::optional<uint64_t> BaseAddress;
842 for (const AddressRange &Range : LinkedRanges) {
843 if (!BaseAddress) {
844 BaseAddress = Range.start();
845
846 // Emit base address.
847 OutRangeSection.emitIntVal(dwarf::DW_RLE_base_addressx, 1);
848 encodeULEB128(getDebugAddrIndex(*BaseAddress), OutRangeSection.OS);
849 }
850
851 // Emit type of entry.
852 OutRangeSection.emitIntVal(dwarf::DW_RLE_offset_pair, 1);
853
854 // Emit start offset relative to base address.
855 encodeULEB128(Range.start() - *BaseAddress, OutRangeSection.OS);
856
857 // Emit end offset relative to base address.
858 encodeULEB128(Range.end() - *BaseAddress, OutRangeSection.OS);
859 }
860
861 // Emit the terminator entry.
862 OutRangeSection.emitIntVal(dwarf::DW_RLE_end_of_list, 1);
863}
864
865void CompileUnit::emitAranges(AddressRanges &LinkedFunctionRanges) {
866 if (LinkedFunctionRanges.empty())
867 return;
868
869 SectionDescriptor &DebugInfoSection =
871 SectionDescriptor &OutArangesSection =
873
874 // Emit Header.
875 unsigned HeaderSize =
876 sizeof(int32_t) + // Size of contents (w/o this field
877 sizeof(int16_t) + // DWARF ARange version number
878 sizeof(int32_t) + // Offset of CU in the .debug_info section
879 sizeof(int8_t) + // Pointer Size (in bytes)
880 sizeof(int8_t); // Segment Size (in bytes)
881
882 unsigned TupleSize = OutArangesSection.getFormParams().AddrSize * 2;
883 unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
884
885 OutArangesSection.emitOffset(0xBADDEF); // Aranges length
886 uint64_t OffsetAfterArangesLengthField = OutArangesSection.OS.tell();
887
888 OutArangesSection.emitIntVal(dwarf::DW_ARANGES_VERSION, 2); // Version number
889 OutArangesSection.notePatch(
890 DebugOffsetPatch{OutArangesSection.OS.tell(), &DebugInfoSection});
891 OutArangesSection.emitOffset(0xBADDEF); // Corresponding unit's offset
892 OutArangesSection.emitIntVal(OutArangesSection.getFormParams().AddrSize,
893 1); // Address size
894 OutArangesSection.emitIntVal(0, 1); // Segment size
895
896 for (size_t Idx = 0; Idx < Padding; Idx++)
897 OutArangesSection.emitIntVal(0, 1); // Padding
898
899 // Emit linked ranges.
900 for (const AddressRange &Range : LinkedFunctionRanges) {
901 OutArangesSection.emitIntVal(Range.start(),
902 OutArangesSection.getFormParams().AddrSize);
903 OutArangesSection.emitIntVal(Range.end() - Range.start(),
904 OutArangesSection.getFormParams().AddrSize);
905 }
906
907 // Emit terminator.
908 OutArangesSection.emitIntVal(0, OutArangesSection.getFormParams().AddrSize);
909 OutArangesSection.emitIntVal(0, OutArangesSection.getFormParams().AddrSize);
910
911 uint64_t OffsetAfterArangesEnd = OutArangesSection.OS.tell();
912
913 // Update Aranges lentgh.
914 OutArangesSection.apply(
915 OffsetAfterArangesLengthField -
916 OutArangesSection.getFormParams().getDwarfOffsetByteSize(),
917 dwarf::DW_FORM_sec_offset,
918 OffsetAfterArangesEnd - OffsetAfterArangesLengthField);
919}
920
922 if (getOutUnitDIE() == nullptr)
923 return Error::success();
924
925 DWARFUnit &OrigUnit = getOrigUnit();
926 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
927
928 // Check for .debug_macro table.
929 if (std::optional<uint64_t> MacroAttr =
930 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macros))) {
931 if (const DWARFDebugMacro *Table =
932 getContaingFile().Dwarf->getDebugMacro()) {
933 emitMacroTableImpl(Table, *MacroAttr, true);
934 }
935 }
936
937 // Check for .debug_macinfo table.
938 if (std::optional<uint64_t> MacroAttr =
939 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macro_info))) {
940 if (const DWARFDebugMacro *Table =
941 getContaingFile().Dwarf->getDebugMacinfo()) {
942 emitMacroTableImpl(Table, *MacroAttr, false);
943 }
944 }
945
946 return Error::success();
947}
948
949void CompileUnit::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
950 uint64_t OffsetToMacroTable,
951 bool hasDWARFv5Header) {
952 SectionDescriptor &OutSection =
953 hasDWARFv5Header
956
957 bool DefAttributeIsReported = false;
958 bool UndefAttributeIsReported = false;
959 bool ImportAttributeIsReported = false;
960
961 for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
962 if (OffsetToMacroTable == List.Offset) {
963 // Write DWARFv5 header.
964 if (hasDWARFv5Header) {
965 // Write header version.
966 OutSection.emitIntVal(List.Header.Version, sizeof(List.Header.Version));
967
968 uint8_t Flags = List.Header.Flags;
969
970 // Check for OPCODE_OPERANDS_TABLE.
971 if (Flags &
972 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
973 Flags &=
974 ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
975 warn("opcode_operands_table is not supported yet.");
976 }
977
978 // Check for DEBUG_LINE_OFFSET.
979 std::optional<uint64_t> StmtListOffset;
980 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
981 // Get offset to the line table from the cloned compile unit.
982 for (auto &V : getOutUnitDIE()->values()) {
983 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
984 StmtListOffset = V.getDIEInteger().getValue();
985 break;
986 }
987 }
988
989 if (!StmtListOffset) {
990 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
991 warn("couldn`t find line table for macro table.");
992 }
993 }
994
995 // Write flags.
996 OutSection.emitIntVal(Flags, sizeof(Flags));
997
998 // Write offset to line table.
999 if (StmtListOffset) {
1000 OutSection.notePatch(DebugOffsetPatch{
1001 OutSection.OS.tell(),
1002 &getOrCreateSectionDescriptor(DebugSectionKind::DebugLine)});
1003 // TODO: check that List.Header.getOffsetByteSize() and
1004 // DebugOffsetPatch agree on size.
1005 OutSection.emitIntVal(0xBADDEF, List.Header.getOffsetByteSize());
1006 }
1007 }
1008
1009 // Write macro entries.
1010 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1011 if (MacroEntry.Type == 0) {
1012 encodeULEB128(MacroEntry.Type, OutSection.OS);
1013 continue;
1014 }
1015
1016 uint8_t MacroType = MacroEntry.Type;
1017 switch (MacroType) {
1018 default: {
1019 bool HasVendorSpecificExtension =
1020 (!hasDWARFv5Header &&
1021 MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1022 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1023 MacroType <= dwarf::DW_MACRO_hi_user));
1024
1025 if (HasVendorSpecificExtension) {
1026 // Write macinfo type.
1027 OutSection.emitIntVal(MacroType, 1);
1028
1029 // Write vendor extension constant.
1030 encodeULEB128(MacroEntry.ExtConstant, OutSection.OS);
1031
1032 // Write vendor extension string.
1033 OutSection.emitString(dwarf::DW_FORM_string, MacroEntry.ExtStr);
1034 } else
1035 warn("unknown macro type. skip.");
1036 } break;
1037 // debug_macro and debug_macinfo share some common encodings.
1038 // DW_MACRO_define == DW_MACINFO_define
1039 // DW_MACRO_undef == DW_MACINFO_undef
1040 // DW_MACRO_start_file == DW_MACINFO_start_file
1041 // DW_MACRO_end_file == DW_MACINFO_end_file
1042 // For readibility/uniformity we are using DW_MACRO_*.
1043 case dwarf::DW_MACRO_define:
1044 case dwarf::DW_MACRO_undef: {
1045 // Write macinfo type.
1046 OutSection.emitIntVal(MacroType, 1);
1047
1048 // Write source line.
1049 encodeULEB128(MacroEntry.Line, OutSection.OS);
1050
1051 // Write macro string.
1052 OutSection.emitString(dwarf::DW_FORM_string, MacroEntry.MacroStr);
1053 } break;
1054 case dwarf::DW_MACRO_define_strp:
1055 case dwarf::DW_MACRO_undef_strp:
1056 case dwarf::DW_MACRO_define_strx:
1057 case dwarf::DW_MACRO_undef_strx: {
1058 // DW_MACRO_*_strx forms are not supported currently.
1059 // Convert to *_strp.
1060 switch (MacroType) {
1061 case dwarf::DW_MACRO_define_strx: {
1062 MacroType = dwarf::DW_MACRO_define_strp;
1063 if (!DefAttributeIsReported) {
1064 warn("DW_MACRO_define_strx unsupported yet. Convert to "
1065 "DW_MACRO_define_strp.");
1066 DefAttributeIsReported = true;
1067 }
1068 } break;
1069 case dwarf::DW_MACRO_undef_strx: {
1070 MacroType = dwarf::DW_MACRO_undef_strp;
1071 if (!UndefAttributeIsReported) {
1072 warn("DW_MACRO_undef_strx unsupported yet. Convert to "
1073 "DW_MACRO_undef_strp.");
1074 UndefAttributeIsReported = true;
1075 }
1076 } break;
1077 default:
1078 // Nothing to do.
1079 break;
1080 }
1081
1082 // Write macinfo type.
1083 OutSection.emitIntVal(MacroType, 1);
1084
1085 // Write source line.
1086 encodeULEB128(MacroEntry.Line, OutSection.OS);
1087
1088 // Write macro string.
1089 OutSection.emitString(dwarf::DW_FORM_strp, MacroEntry.MacroStr);
1090 break;
1091 }
1092 case dwarf::DW_MACRO_start_file: {
1093 // Write macinfo type.
1094 OutSection.emitIntVal(MacroType, 1);
1095 // Write source line.
1096 encodeULEB128(MacroEntry.Line, OutSection.OS);
1097 // Write source file id.
1098 encodeULEB128(MacroEntry.File, OutSection.OS);
1099 } break;
1100 case dwarf::DW_MACRO_end_file: {
1101 // Write macinfo type.
1102 OutSection.emitIntVal(MacroType, 1);
1103 } break;
1104 case dwarf::DW_MACRO_import:
1105 case dwarf::DW_MACRO_import_sup: {
1106 if (!ImportAttributeIsReported) {
1107 warn("DW_MACRO_import and DW_MACRO_import_sup are unsupported "
1108 "yet. remove.");
1109 ImportAttributeIsReported = true;
1110 }
1111 } break;
1112 }
1113 }
1114
1115 return;
1116 }
1117 }
1118}
1119
1121 const DWARFExpression &InputExpression,
1122 SmallVectorImpl<uint8_t> &OutputExpression, SectionDescriptor &Section,
1123 std::optional<int64_t> VarAddressAdjustment,
1124 OffsetsPtrVector &PatchesOffsets) {
1125 using Encoding = DWARFExpression::Operation::Encoding;
1126
1127 DWARFUnit &OrigUnit = getOrigUnit();
1128 uint8_t OrigAddressByteSize = OrigUnit.getAddressByteSize();
1129
1130 uint64_t OpOffset = 0;
1131 for (auto &Op : InputExpression) {
1132 auto Desc = Op.getDescription();
1133 // DW_OP_const_type is variable-length and has 3
1134 // operands. Thus far we only support 2.
1135 if ((Desc.Op.size() == 2 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1136 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1137 Desc.Op[0] != Encoding::Size1))
1138 warn("unsupported DW_OP encoding.");
1139
1140 if ((Desc.Op.size() == 1 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1141 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1142 Desc.Op[0] == Encoding::Size1)) {
1143 // This code assumes that the other non-typeref operand fits into 1 byte.
1144 assert(OpOffset < Op.getEndOffset());
1145 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1146 assert(ULEBsize <= 16);
1147
1148 // Copy over the operation.
1149 assert(!Op.getSubCode() && "SubOps not yet supported");
1150 OutputExpression.push_back(Op.getCode());
1151 uint64_t RefOffset;
1152 if (Desc.Op.size() == 1) {
1153 RefOffset = Op.getRawOperand(0);
1154 } else {
1155 OutputExpression.push_back(Op.getRawOperand(0));
1156 RefOffset = Op.getRawOperand(1);
1157 }
1158 uint8_t ULEB[16];
1159 uint32_t Offset = 0;
1160 unsigned RealSize = 0;
1161 // Look up the base type. For DW_OP_convert, the operand may be 0 to
1162 // instead indicate the generic type. The same holds for
1163 // DW_OP_reinterpret, which is currently not supported.
1164 if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1165 RefOffset += OrigUnit.getOffset();
1166 uint32_t RefDieIdx = 0;
1167 if (std::optional<uint32_t> Idx =
1168 OrigUnit.getDIEIndexForOffset(RefOffset))
1169 RefDieIdx = *Idx;
1170
1171 // Use fixed size for ULEB128 data, since we need to update that size
1172 // later with the proper offsets. Use 5 for DWARF32, 9 for DWARF64.
1173 ULEBsize = getFormParams().getDwarfOffsetByteSize() + 1;
1174
1175 RealSize = encodeULEB128(0xBADDEF, ULEB, ULEBsize);
1176
1177 Section.notePatchWithOffsetUpdate(
1178 DebugULEB128DieRefPatch(OutputExpression.size(), this, this,
1179 RefDieIdx),
1180 PatchesOffsets);
1181 } else
1182 RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1183
1184 if (RealSize > ULEBsize) {
1185 // Emit the generic type as a fallback.
1186 RealSize = encodeULEB128(0, ULEB, ULEBsize);
1187 warn("base type ref doesn't fit.");
1188 }
1189 assert(RealSize == ULEBsize && "padding failed");
1190 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1191 OutputExpression.append(ULEBbytes.begin(), ULEBbytes.end());
1192 } else if (!getGlobalData().getOptions().UpdateIndexTablesOnly &&
1193 Op.getCode() == dwarf::DW_OP_addrx) {
1194 if (std::optional<object::SectionedAddress> SA =
1195 OrigUnit.getAddrOffsetSectionItem(Op.getRawOperand(0))) {
1196 // DWARFLinker does not use addrx forms since it generates relocated
1197 // addresses. Replace DW_OP_addrx with DW_OP_addr here.
1198 // Argument of DW_OP_addrx should be relocated here as it is not
1199 // processed by applyValidRelocs.
1200 OutputExpression.push_back(dwarf::DW_OP_addr);
1201 uint64_t LinkedAddress = SA->Address + VarAddressAdjustment.value_or(0);
1203 sys::swapByteOrder(LinkedAddress);
1204 ArrayRef<uint8_t> AddressBytes(
1205 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1206 OrigAddressByteSize);
1207 OutputExpression.append(AddressBytes.begin(), AddressBytes.end());
1208 } else
1209 warn("cann't read DW_OP_addrx operand.");
1210 } else if (!getGlobalData().getOptions().UpdateIndexTablesOnly &&
1211 Op.getCode() == dwarf::DW_OP_constx) {
1212 if (std::optional<object::SectionedAddress> SA =
1213 OrigUnit.getAddrOffsetSectionItem(Op.getRawOperand(0))) {
1214 // DWARFLinker does not use constx forms since it generates relocated
1215 // addresses. Replace DW_OP_constx with DW_OP_const[*]u here.
1216 // Argument of DW_OP_constx should be relocated here as it is not
1217 // processed by applyValidRelocs.
1218 std::optional<uint8_t> OutOperandKind;
1219 switch (OrigAddressByteSize) {
1220 case 2:
1221 OutOperandKind = dwarf::DW_OP_const2u;
1222 break;
1223 case 4:
1224 OutOperandKind = dwarf::DW_OP_const4u;
1225 break;
1226 case 8:
1227 OutOperandKind = dwarf::DW_OP_const8u;
1228 break;
1229 default:
1230 warn(
1231 formatv(("unsupported address size: {0}."), OrigAddressByteSize));
1232 break;
1233 }
1234
1235 if (OutOperandKind) {
1236 OutputExpression.push_back(*OutOperandKind);
1237 uint64_t LinkedAddress =
1238 SA->Address + VarAddressAdjustment.value_or(0);
1240 sys::swapByteOrder(LinkedAddress);
1241 ArrayRef<uint8_t> AddressBytes(
1242 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1243 OrigAddressByteSize);
1244 OutputExpression.append(AddressBytes.begin(), AddressBytes.end());
1245 }
1246 } else
1247 warn("cann't read DW_OP_constx operand.");
1248 } else {
1249 // Copy over everything else unmodified.
1250 StringRef Bytes =
1251 InputExpression.getData().slice(OpOffset, Op.getEndOffset());
1252 OutputExpression.append(Bytes.begin(), Bytes.end());
1253 }
1254 OpOffset = Op.getEndOffset();
1255 }
1256}
1257
1259 std::optional<std::reference_wrapper<const Triple>> TargetTriple,
1260 TypeUnit *ArtificialTypeUnit) {
1261 BumpPtrAllocator Allocator;
1262
1263 DWARFDie OrigUnitDIE = getOrigUnit().getUnitDIE();
1264 if (!OrigUnitDIE.isValid())
1265 return Error::success();
1266
1267 TypeEntry *RootEntry = nullptr;
1268 if (ArtificialTypeUnit)
1269 RootEntry = ArtificialTypeUnit->getTypePool().getRoot();
1270
1271 // Clone input DIE entry recursively.
1272 std::pair<DIE *, TypeEntry *> OutCUDie = cloneDIE(
1273 OrigUnitDIE.getDebugInfoEntry(), RootEntry, getDebugInfoHeaderSize(),
1274 std::nullopt, std::nullopt, Allocator, ArtificialTypeUnit);
1275 setOutUnitDIE(OutCUDie.first);
1276
1277 if (!TargetTriple.has_value() || (OutCUDie.first == nullptr))
1278 return Error::success();
1279
1280 if (Error Err = cloneAndEmitLineTable((*TargetTriple).get()))
1281 return Err;
1282
1283 if (Error Err = cloneAndEmitDebugMacro())
1284 return Err;
1285
1287 if (Error Err = emitDebugInfo((*TargetTriple).get()))
1288 return Err;
1289
1290 // ASSUMPTION: .debug_info section should already be emitted at this point.
1291 // cloneAndEmitRanges & cloneAndEmitDebugLocations use .debug_info section
1292 // data.
1293
1294 if (Error Err = cloneAndEmitRanges())
1295 return Err;
1296
1298 return Err;
1299
1300 if (Error Err = emitDebugAddrSection())
1301 return Err;
1302
1303 // Generate Pub accelerator tables.
1304 if (llvm::is_contained(GlobalData.getOptions().AccelTables,
1307
1309 return Err;
1310
1311 return emitAbbreviations();
1312}
1313
1314std::pair<DIE *, TypeEntry *> CompileUnit::cloneDIE(
1315 const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *ClonedParentTypeDIE,
1316 uint64_t OutOffset, std::optional<int64_t> FuncAddressAdjustment,
1317 std::optional<int64_t> VarAddressAdjustment, BumpPtrAllocator &Allocator,
1318 TypeUnit *ArtificialTypeUnit, uint32_t SiblingOrdinal) {
1319 uint32_t InputDieIdx = getDIEIndex(InputDieEntry);
1320 CompileUnit::DIEInfo &Info = getDIEInfo(InputDieIdx);
1321
1322 bool NeedToClonePlainDIE = Info.needToKeepInPlainDwarf();
1323 bool NeedToCloneTypeDIE =
1324 (InputDieEntry->getTag() != dwarf::DW_TAG_compile_unit) &&
1325 Info.needToPlaceInTypeTable();
1326 std::pair<DIE *, TypeEntry *> ClonedDIE;
1327
1328 DIEGenerator PlainDIEGenerator(Allocator, *this);
1329
1330 if (NeedToClonePlainDIE)
1331 // Create a cloned DIE which would be placed into the cloned version
1332 // of input compile unit.
1333 ClonedDIE.first = createPlainDIEandCloneAttributes(
1334 InputDieEntry, PlainDIEGenerator, OutOffset, FuncAddressAdjustment,
1335 VarAddressAdjustment);
1336 if (NeedToCloneTypeDIE) {
1337 // Create a cloned DIE which would be placed into the artificial type
1338 // unit.
1339 assert(ArtificialTypeUnit != nullptr);
1340 DIEGenerator TypeDIEGenerator(
1341 ArtificialTypeUnit->getTypePool().getThreadLocalAllocator(), *this);
1342
1343 ClonedDIE.second = createTypeDIEandCloneAttributes(
1344 InputDieEntry, TypeDIEGenerator, ClonedParentTypeDIE,
1345 ArtificialTypeUnit, SiblingOrdinal);
1346 }
1347 TypeEntry *TypeParentForChild =
1348 ClonedDIE.second ? ClonedDIE.second : ClonedParentTypeDIE;
1349
1350 bool HasPlainChildrenToClone =
1351 (ClonedDIE.first && Info.getKeepPlainChildren());
1352
1353 bool HasTypeChildrenToClone =
1354 ((ClonedDIE.second ||
1355 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit) &&
1356 Info.getKeepTypeChildren());
1357
1358 // Recursively clone children.
1359 if (HasPlainChildrenToClone || HasTypeChildrenToClone) {
1360 uint32_t ChildOrdinal = 0;
1361 for (const DWARFDebugInfoEntry *CurChild =
1362 getFirstChildEntry(InputDieEntry);
1363 CurChild && CurChild->getAbbreviationDeclarationPtr();
1364 CurChild = getSiblingEntry(CurChild), ++ChildOrdinal) {
1365 std::pair<DIE *, TypeEntry *> ClonedChild = cloneDIE(
1366 CurChild, TypeParentForChild, OutOffset, FuncAddressAdjustment,
1367 VarAddressAdjustment, Allocator, ArtificialTypeUnit, ChildOrdinal);
1368
1369 if (ClonedChild.first) {
1370 OutOffset =
1371 ClonedChild.first->getOffset() + ClonedChild.first->getSize();
1372 PlainDIEGenerator.addChild(ClonedChild.first);
1373 }
1374 }
1375 assert(ClonedDIE.first == nullptr ||
1376 HasPlainChildrenToClone == ClonedDIE.first->hasChildren());
1377
1378 // Account for the end of children marker.
1379 if (HasPlainChildrenToClone)
1380 OutOffset += sizeof(int8_t);
1381 }
1382
1383 // Update our size.
1384 if (ClonedDIE.first != nullptr)
1385 ClonedDIE.first->setSize(OutOffset - ClonedDIE.first->getOffset());
1386
1387 return ClonedDIE;
1388}
1389
1390DIE *CompileUnit::createPlainDIEandCloneAttributes(
1391 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &PlainDIEGenerator,
1392 uint64_t &OutOffset, std::optional<int64_t> &FuncAddressAdjustment,
1393 std::optional<int64_t> &VarAddressAdjustment) {
1394 uint32_t InputDieIdx = getDIEIndex(InputDieEntry);
1395 CompileUnit::DIEInfo &Info = getDIEInfo(InputDieIdx);
1396 DIE *ClonedDIE = nullptr;
1397 bool HasLocationExpressionAddress = false;
1398 if (InputDieEntry->getTag() == dwarf::DW_TAG_subprogram) {
1399 // Get relocation adjustment value for the current function.
1400 FuncAddressAdjustment =
1401 getContaingFile().Addresses->getSubprogramRelocAdjustment(
1402 getDIE(InputDieEntry), false);
1403 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_label) {
1404 // Get relocation adjustment value for the current label.
1405 std::optional<uint64_t> lowPC =
1406 dwarf::toAddress(find(InputDieEntry, dwarf::DW_AT_low_pc));
1407 if (lowPC) {
1408 LabelMapTy::iterator It = Labels.find(*lowPC);
1409 if (It != Labels.end())
1410 FuncAddressAdjustment = It->second;
1411 }
1412 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_variable) {
1413 // Get relocation adjustment value for the current variable.
1414 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
1415 getContaingFile().Addresses->getVariableRelocAdjustment(
1416 getDIE(InputDieEntry), false);
1417
1418 HasLocationExpressionAddress = LocExprAddrAndRelocAdjustment.first;
1419 if (LocExprAddrAndRelocAdjustment.first &&
1420 LocExprAddrAndRelocAdjustment.second)
1421 VarAddressAdjustment = *LocExprAddrAndRelocAdjustment.second;
1422 }
1423
1424 ClonedDIE = PlainDIEGenerator.createDIE(InputDieEntry->getTag(), OutOffset);
1425
1426 // Offset to the DIE would be used after output DIE tree is deleted.
1427 // Thus we need to remember DIE offset separately.
1428 rememberDieOutOffset(InputDieIdx, OutOffset);
1429
1430 // Clone Attributes.
1431 DIEAttributeCloner AttributesCloner(ClonedDIE, *this, this, InputDieEntry,
1432 PlainDIEGenerator, FuncAddressAdjustment,
1433 VarAddressAdjustment,
1434 HasLocationExpressionAddress);
1435 AttributesCloner.clone();
1436
1437 // Remember accelerator info.
1438 AcceleratorRecordsSaver AccelRecordsSaver(getGlobalData(), *this, this);
1439 AccelRecordsSaver.save(InputDieEntry, ClonedDIE, AttributesCloner.AttrInfo,
1440 nullptr);
1441
1442 OutOffset =
1443 AttributesCloner.finalizeAbbreviations(Info.getKeepPlainChildren());
1444
1445 return ClonedDIE;
1446}
1447
1448/// Allocates output DIE for the specified \p TypeDescriptor.
1449DIE *CompileUnit::allocateTypeDie(TypeEntryBody *TypeDescriptor,
1450 DIEGenerator &TypeDIEGenerator,
1451 dwarf::Tag DieTag, bool IsDeclaration,
1452 bool IsParentDeclaration) {
1453 uint64_t Priority = getPriority();
1454
1455 // Lock-free pre-checks: skip the lock (and downstream cloning) when this CU
1456 // has no chance of winning the type slot.
1457 if (!IsDeclaration && !IsParentDeclaration) {
1458 // DiePriority only ever decreases, so a relaxed read that is <= our
1459 // priority means we definitely cannot win.
1460 if (Priority >= TypeDescriptor->DiePriority.load(std::memory_order_relaxed))
1461 return nullptr;
1462 } else {
1463 // Once a definition exists the declaration slot is dead.
1464 if (TypeDescriptor->Die.load(std::memory_order_relaxed))
1465 return nullptr;
1466 }
1467
1468 while (TypeDescriptor->Lock.test_and_set(std::memory_order_acquire))
1469 ; // spin
1470
1471 DIE *Result = nullptr;
1472
1473 if (!IsDeclaration && !IsParentDeclaration) {
1474 // Definition: lowest priority wins.
1475 if (Priority <
1476 TypeDescriptor->DiePriority.load(std::memory_order_relaxed)) {
1477 TypeDescriptor->DiePriority.store(Priority, std::memory_order_relaxed);
1478 Result = TypeDIEGenerator.createDIE(DieTag, 0);
1479 TypeDescriptor->Die.store(Result, std::memory_order_relaxed);
1480 }
1481 } else if (!TypeDescriptor->Die.load(std::memory_order_relaxed)) {
1482 // Declaration (no definition exists yet).
1483 // Prefer declarations whose parent is a definition (better context);
1484 // break ties by CU priority (lower wins).
1485 bool WorseParent =
1486 IsParentDeclaration && !TypeDescriptor->DeclarationParentIsDeclaration;
1487 bool BetterParent =
1488 !IsParentDeclaration && TypeDescriptor->DeclarationParentIsDeclaration;
1489 if (!WorseParent &&
1490 (BetterParent || Priority < TypeDescriptor->DeclarationDiePriority)) {
1491 TypeDescriptor->DeclarationDiePriority = Priority;
1492 TypeDescriptor->DeclarationParentIsDeclaration = IsParentDeclaration;
1493 Result = TypeDIEGenerator.createDIE(DieTag, 0);
1494 TypeDescriptor->DeclarationDie.store(Result, std::memory_order_relaxed);
1495 }
1496 }
1497
1498 TypeDescriptor->Lock.clear(std::memory_order_release);
1499 return Result;
1500}
1501
1502TypeEntry *CompileUnit::createTypeDIEandCloneAttributes(
1503 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &TypeDIEGenerator,
1504 TypeEntry *ClonedParentTypeDIE, TypeUnit *ArtificialTypeUnit,
1505 uint32_t SiblingOrdinal) {
1506 assert(ArtificialTypeUnit != nullptr);
1507 uint32_t InputDieIdx = getDIEIndex(InputDieEntry);
1508
1509 TypeEntry *Entry = getDieTypeEntry(InputDieIdx);
1510 assert(Entry != nullptr);
1511 assert(ClonedParentTypeDIE != nullptr);
1512 TypeEntryBody *EntryBody =
1513 ArtificialTypeUnit->getTypePool().getOrCreateTypeEntryBody(
1514 Entry, ClonedParentTypeDIE);
1515 assert(EntryBody);
1516
1517 // Min-merge this child's ordinal in its parent's child list so children of
1518 // record-like types (class/struct/union/interface) sort in source order.
1519 // Min across CUs because Clang appends template instantiations lazily, so
1520 // positions vary between CUs.
1521 if (std::optional<uint32_t> ParentIdx = InputDieEntry->getParentIdx()) {
1522 dwarf::Tag ParentTag = getDebugInfoEntry(*ParentIdx)->getTag();
1523 if (ParentTag == dwarf::DW_TAG_structure_type ||
1524 ParentTag == dwarf::DW_TAG_class_type ||
1525 ParentTag == dwarf::DW_TAG_union_type ||
1526 ParentTag == dwarf::DW_TAG_interface_type) {
1527 uint32_t Prev = EntryBody->SortKey.load(std::memory_order_relaxed);
1528 while (SiblingOrdinal < Prev &&
1529 !EntryBody->SortKey.compare_exchange_weak(
1530 Prev, SiblingOrdinal, std::memory_order_relaxed,
1531 std::memory_order_relaxed))
1532 ;
1533 }
1534 }
1535
1536 bool IsDeclaration =
1537 dwarf::toUnsigned(find(InputDieEntry, dwarf::DW_AT_declaration), 0);
1538
1539 bool ParentIsDeclaration = false;
1540 if (std::optional<uint32_t> ParentIdx = InputDieEntry->getParentIdx())
1541 ParentIsDeclaration =
1542 dwarf::toUnsigned(find(*ParentIdx, dwarf::DW_AT_declaration), 0);
1543
1544 DIE *OutDIE =
1545 allocateTypeDie(EntryBody, TypeDIEGenerator, InputDieEntry->getTag(),
1546 IsDeclaration, ParentIsDeclaration);
1547
1548 if (OutDIE != nullptr) {
1549 assert(ArtificialTypeUnit != nullptr);
1551
1552 DIEAttributeCloner AttributesCloner(OutDIE, *this, ArtificialTypeUnit,
1553 InputDieEntry, TypeDIEGenerator,
1554 std::nullopt, std::nullopt, false);
1555 AttributesCloner.clone();
1556
1557 // Remember accelerator info.
1558 AcceleratorRecordsSaver AccelRecordsSaver(getGlobalData(), *this,
1559 ArtificialTypeUnit);
1560 AccelRecordsSaver.save(InputDieEntry, OutDIE, AttributesCloner.AttrInfo,
1561 Entry);
1562
1563 // if AttributesCloner.getOutOffset() == 0 then we need to add
1564 // 1 to avoid assertion for zero size. We will subtract it back later.
1565 OutDIE->setSize(AttributesCloner.getOutOffset() + 1);
1566 }
1567
1568 return Entry;
1569}
1570
1572 const DWARFDebugLine::LineTable *InputLineTable =
1573 getContaingFile().Dwarf->getLineTableForUnit(&getOrigUnit());
1574 if (InputLineTable == nullptr) {
1575 if (getOrigUnit().getUnitDIE().find(dwarf::DW_AT_stmt_list))
1576 warn("cann't load line table.");
1577 return Error::success();
1578 }
1579
1580 DWARFDebugLine::LineTable OutLineTable;
1581
1582 // Set Line Table header.
1583 OutLineTable.Prologue = InputLineTable->Prologue;
1585
1586 // Set Line Table Rows.
1587 if (getGlobalData().getOptions().UpdateIndexTablesOnly) {
1588 OutLineTable.Rows = InputLineTable->Rows;
1589 // If all the line table contains is a DW_LNE_end_sequence, clear the line
1590 // table rows, it will be inserted again in the DWARFStreamer.
1591 if (OutLineTable.Rows.size() == 1 && OutLineTable.Rows[0].EndSequence)
1592 OutLineTable.Rows.clear();
1593
1594 OutLineTable.Sequences = InputLineTable->Sequences;
1595 return emitDebugLine(TargetTriple, OutLineTable);
1596 }
1597
1598 SmallVector<uint64_t> OrigRowIndices;
1599 filterLineTableRows(*InputLineTable, OutLineTable.Rows, OrigRowIndices);
1600
1601 if (StmtSeqListAttributes.empty())
1602 return emitDebugLine(TargetTriple, OutLineTable);
1603
1604 // When DW_AT_LLVM_stmt_sequence attributes on this CU need their values
1605 // rewritten to point at the correct output sequence, have the emitter
1606 // record, for every row that originated from an input row, the byte
1607 // offset of the DW_LNE_set_address that opens the sequence containing
1608 // that row. Keying the map on the input row index (rather than on an
1609 // output address) avoids collisions when two input sequences would
1610 // relocate to the same output address — e.g. ICF folding two functions
1611 // from the same CU to a single output range.
1612 //
1613 // The patching below MUST run before emitDebugInfo() serializes the
1614 // DIE bytes and before OutputSections::applyPatches() runs for this
1615 // unit's .debug_info — it writes a local offset into the DIEValue that
1616 // the serializer then emits, and a DebugOffsetPatch (registered at DIE
1617 // cloning time) later adds the CU's .debug_line start offset to reach
1618 // the final absolute value.
1619 DenseMap<uint64_t, uint64_t> RowIndexToSeqStartOffset;
1620 if (Error Err = emitDebugLine(TargetTriple, OutLineTable, OrigRowIndices,
1621 &RowIndexToSeqStartOffset))
1622 return Err;
1623
1624 DenseMap<uint64_t, uint64_t> SeqOffsetToFirstRowIndex =
1625 buildStmtSeqOffsetToFirstRowIndex(*InputLineTable);
1626 patchStmtSeqAttributes(SeqOffsetToFirstRowIndex, RowIndexToSeqStartOffset);
1627 return Error::success();
1628}
1629
1630void CompileUnit::filterLineTableRows(
1631 const DWARFDebugLine::LineTable &InputLineTable,
1632 std::vector<DWARFDebugLine::Row> &NewRows,
1633 SmallVectorImpl<uint64_t> &NewRowIndices) {
1634 NewRows.reserve(InputLineTable.Rows.size());
1635 NewRowIndices.reserve(InputLineTable.Rows.size());
1636
1637 // Current sequence of rows being extracted, before being inserted
1638 // in NewRows. Kept in lockstep with SeqIndices, which stores the
1639 // originating input row index (or InvalidRowIndex for manufactured
1640 // end-of-range rows).
1641 std::vector<DWARFDebugLine::Row> Seq;
1642 SmallVector<uint64_t> SeqIndices;
1643 constexpr uint64_t InvalidRowIndex = std::numeric_limits<uint64_t>::max();
1644
1645 const auto &FunctionRanges = getFunctionRanges();
1646 std::optional<AddressRangeValuePair> CurrRange;
1647
1648 // FIXME: This logic is meant to generate exactly the same output as
1649 // Darwin's classic dsymutil. There is a nicer way to implement this
1650 // by simply putting all the relocated line info in NewRows and simply
1651 // sorting NewRows before passing it to emitLineTableForUnit. This
1652 // should be correct as sequences for a function should stay
1653 // together in the sorted output. There are a few corner cases that
1654 // look suspicious though, and that required to implement the logic
1655 // this way. Revisit that once initial validation is finished.
1656
1657 // Iterate over the object file line info and extract the sequences
1658 // that correspond to linked functions.
1659 for (auto [InputRowIdx, InputRow] : llvm::enumerate(InputLineTable.Rows)) {
1660 DWARFDebugLine::Row Row = InputRow;
1661 // Check whether we stepped out of the range. The range is
1662 // half-open, but consider accept the end address of the range if
1663 // it is marked as end_sequence in the input (because in that
1664 // case, the relocation offset is accurate and that entry won't
1665 // serve as the start of another function).
1666 if (!CurrRange || !CurrRange->Range.contains(Row.Address.Address)) {
1667 // We just stepped out of a known range. Insert a end_sequence
1668 // corresponding to the end of the range.
1669 uint64_t StopAddress =
1670 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
1671 CurrRange = FunctionRanges.getRangeThatContains(Row.Address.Address);
1672 if (StopAddress != -1ULL && !Seq.empty()) {
1673 // Insert end sequence row with the computed end address, but
1674 // the same line as the previous one. This row is synthesised
1675 // and has no input counterpart, so tag it with
1676 // InvalidRowIndex.
1677 auto NextLine = Seq.back();
1678 NextLine.Address.Address = StopAddress;
1679 NextLine.EndSequence = 1;
1680 NextLine.PrologueEnd = 0;
1681 NextLine.BasicBlock = 0;
1682 NextLine.EpilogueBegin = 0;
1683 Seq.push_back(NextLine);
1684 SeqIndices.push_back(InvalidRowIndex);
1685 insertLineSequence(Seq, SeqIndices, NewRows, NewRowIndices);
1686 }
1687
1688 if (!CurrRange)
1689 continue;
1690 }
1691
1692 // Ignore empty sequences.
1693 if (Row.EndSequence && Seq.empty())
1694 continue;
1695
1696 // Relocate row address and add it to the current sequence.
1697 Row.Address.Address += CurrRange->Value;
1698 Seq.emplace_back(Row);
1699 SeqIndices.push_back(InputRowIdx);
1700
1701 if (Row.EndSequence)
1702 insertLineSequence(Seq, SeqIndices, NewRows, NewRowIndices);
1703 }
1704}
1705
1706void CompileUnit::patchStmtSeqAttributes(
1707 const DenseMap<uint64_t, uint64_t> &SeqOffsetToFirstRowIndex,
1708 const DenseMap<uint64_t, uint64_t> &RowIndexToSeqStartOffset) {
1709 const uint64_t InvalidOffset = getFormParams().getDwarfMaxOffset();
1710
1711 for (const CompileUnit::StmtSeqPatch &Patch : StmtSeqListAttributes) {
1712 uint64_t NewStmtSeq = InvalidOffset;
1713 auto RowIt = SeqOffsetToFirstRowIndex.find(Patch.InputStmtSeqOffset);
1714 if (RowIt != SeqOffsetToFirstRowIndex.end()) {
1715 auto OffIt = RowIndexToSeqStartOffset.find(RowIt->second);
1716 if (OffIt != RowIndexToSeqStartOffset.end())
1717 NewStmtSeq = OffIt->second;
1718 }
1719 // When resolution fails, the InvalidOffset sentinel must survive the
1720 // combination-time section-offset fixup. The patch applier preserves
1721 // InvalidOffset as-is so consumers see a clean invalid marker rather
1722 // than StartOffset - 1.
1723 *Patch.Value = DIEValue(Patch.Value->getAttribute(), Patch.Value->getForm(),
1724 DIEInteger(NewStmtSeq));
1725 }
1726}
1727
1728DenseMap<uint64_t, uint64_t> CompileUnit::buildStmtSeqOffsetToFirstRowIndex(
1729 const DWARFDebugLine::LineTable &InputLineTable) const {
1730 // Collect this CU's stmt-sequence attribute values (input offsets),
1731 // sorted ascending and deduplicated.
1732 SmallVector<uint64_t> StmtAttrs;
1733 StmtAttrs.reserve(StmtSeqListAttributes.size());
1734 for (const StmtSeqPatch &Patch : StmtSeqListAttributes)
1735 StmtAttrs.push_back(Patch.InputStmtSeqOffset);
1736 llvm::sort(StmtAttrs);
1737 StmtAttrs.erase(llvm::unique(StmtAttrs), StmtAttrs.end());
1738
1739 DenseMap<uint64_t, uint64_t> Result;
1740 dwarf_linker::buildStmtSeqOffsetToFirstRowIndex(InputLineTable, StmtAttrs,
1741 Result);
1742 return Result;
1743}
1744
1745void CompileUnit::insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1746 SmallVectorImpl<uint64_t> &SeqIndices,
1747 std::vector<DWARFDebugLine::Row> &Rows,
1748 SmallVectorImpl<uint64_t> &RowIndices) {
1749 assert(Seq.size() == SeqIndices.size() &&
1750 "Seq and SeqIndices must be kept in lockstep");
1751 assert(Rows.size() == RowIndices.size() &&
1752 "Rows and RowIndices must be kept in lockstep");
1753 if (Seq.empty())
1754 return;
1755
1756 auto ClearSeq = [&] {
1757 Seq.clear();
1758 SeqIndices.clear();
1759 };
1760
1761 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1762 llvm::append_range(Rows, Seq);
1763 llvm::append_range(RowIndices, SeqIndices);
1764 ClearSeq();
1765 return;
1766 }
1767
1768 object::SectionedAddress Front = Seq.front().Address;
1769 auto InsertPoint = partition_point(
1770 Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1771 size_t InsertIdx = std::distance(Rows.begin(), InsertPoint);
1772
1773 // FIXME: this only removes the unneeded end_sequence if the
1774 // sequences have been inserted in order. Using a global sort like
1775 // described in cloneAndEmitLineTable() and delaying the end_sequene
1776 // elimination to DebugLineEmitter::emit() we can get rid of all of them.
1777 if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1778 InsertPoint->EndSequence) {
1779 *InsertPoint = Seq.front();
1780 RowIndices[InsertIdx] = SeqIndices.front();
1781 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1782 RowIndices.insert(RowIndices.begin() + InsertIdx + 1,
1783 SeqIndices.begin() + 1, SeqIndices.end());
1784 } else {
1785 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1786 RowIndices.insert(RowIndices.begin() + InsertIdx, SeqIndices.begin(),
1787 SeqIndices.end());
1788 }
1789
1790 ClearSeq();
1791}
1792
1793#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1795 llvm::errs() << "{";
1796 llvm::errs() << " Placement: ";
1797 switch (getPlacement()) {
1798 case NotSet:
1799 llvm::errs() << "NotSet";
1800 break;
1801 case TypeTable:
1802 llvm::errs() << "TypeTable";
1803 break;
1804 case PlainDwarf:
1805 llvm::errs() << "PlainDwarf";
1806 break;
1807 case Both:
1808 llvm::errs() << "Both";
1809 break;
1810 }
1811
1812 llvm::errs() << " Keep: " << getKeep();
1813 llvm::errs() << " KeepPlainChildren: " << getKeepPlainChildren();
1814 llvm::errs() << " KeepTypeChildren: " << getKeepTypeChildren();
1815 llvm::errs() << " IsInMouduleScope: " << getIsInMouduleScope();
1816 llvm::errs() << " IsInFunctionScope: " << getIsInFunctionScope();
1817 llvm::errs() << " IsInAnonNamespaceScope: " << getIsInAnonNamespaceScope();
1818 llvm::errs() << " ODRAvailable: " << getODRAvailable();
1819 llvm::errs() << " TrackLiveness: " << getTrackLiveness();
1820 llvm::errs() << "}\n";
1821}
1822#endif // if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1823
1824std::optional<std::pair<StringRef, StringRef>>
1826 const DWARFFormValue &FileIdxValue) {
1827 uint64_t FileIdx;
1828 if (std::optional<uint64_t> Val = FileIdxValue.getAsUnsignedConstant())
1829 FileIdx = *Val;
1830 else if (std::optional<int64_t> Val = FileIdxValue.getAsSignedConstant())
1831 FileIdx = *Val;
1832 else if (std::optional<uint64_t> Val = FileIdxValue.getAsSectionOffset())
1833 FileIdx = *Val;
1834 else
1835 return std::nullopt;
1836
1837 return getDirAndFilenameFromLineTable(FileIdx);
1838}
1839
1840std::optional<std::pair<StringRef, StringRef>>
1842 FileNamesCache::iterator FileData = FileNames.find(FileIdx);
1843 if (FileData != FileNames.end())
1844 return std::make_pair(StringRef(FileData->second.first),
1845 StringRef(FileData->second.second));
1846
1847 if (const DWARFDebugLine::LineTable *LineTable =
1848 getOrigUnit().getContext().getLineTableForUnit(&getOrigUnit())) {
1849 if (LineTable->hasFileAtIndex(FileIdx)) {
1850
1852 LineTable->Prologue.getFileNameEntry(FileIdx);
1853
1854 Expected<const char *> Name = Entry.Name.getAsCString();
1855 if (!Name) {
1856 warn(Name.takeError());
1857 return std::nullopt;
1858 }
1859
1860 std::string FileName = *Name;
1861 if (isPathAbsoluteOnWindowsOrPosix(FileName)) {
1862 FileNamesCache::iterator FileData =
1863 FileNames
1864 .insert(std::make_pair(
1865 FileIdx,
1866 std::make_pair(std::string(""), std::move(FileName))))
1867 .first;
1868 return std::make_pair(StringRef(FileData->second.first),
1869 StringRef(FileData->second.second));
1870 }
1871
1872 SmallString<256> FilePath;
1873 StringRef IncludeDir;
1874 // Be defensive about the contents of Entry.
1875 if (getVersion() >= 5) {
1876 // DirIdx 0 is the compilation directory, so don't include it for
1877 // relative names.
1878 if ((Entry.DirIdx != 0) &&
1879 Entry.DirIdx < LineTable->Prologue.IncludeDirectories.size()) {
1880 Expected<const char *> DirName =
1881 LineTable->Prologue.IncludeDirectories[Entry.DirIdx]
1882 .getAsCString();
1883 if (DirName)
1884 IncludeDir = *DirName;
1885 else {
1886 warn(DirName.takeError());
1887 return std::nullopt;
1888 }
1889 }
1890 } else {
1891 if (0 < Entry.DirIdx &&
1892 Entry.DirIdx <= LineTable->Prologue.IncludeDirectories.size()) {
1893 Expected<const char *> DirName =
1894 LineTable->Prologue.IncludeDirectories[Entry.DirIdx - 1]
1895 .getAsCString();
1896 if (DirName)
1897 IncludeDir = *DirName;
1898 else {
1899 warn(DirName.takeError());
1900 return std::nullopt;
1901 }
1902 }
1903 }
1904
1906
1907 if (!CompDir.empty() && !isPathAbsoluteOnWindowsOrPosix(IncludeDir)) {
1908 sys::path::append(FilePath, sys::path::Style::native, CompDir);
1909 }
1910
1911 sys::path::append(FilePath, sys::path::Style::native, IncludeDir);
1912
1913 FileNamesCache::iterator FileData =
1914 FileNames
1915 .insert(
1916 std::make_pair(FileIdx, std::make_pair(std::string(FilePath),
1917 std::move(FileName))))
1918 .first;
1919 return std::make_pair(StringRef(FileData->second.first),
1920 StringRef(FileData->second.second));
1921 }
1922 }
1923
1924 return std::nullopt;
1925}
1926
1927#define MAX_REFERENCIES_DEPTH 1000
1929 UnitEntryPairTy CUDiePair(*this);
1930 std::optional<UnitEntryPairTy> RefDiePair;
1931 int refDepth = 0;
1932 do {
1933 RefDiePair = CUDiePair.CU->resolveDIEReference(
1934 CUDiePair.DieEntry, dwarf::DW_AT_extension,
1936 if (!RefDiePair || !RefDiePair->DieEntry)
1937 return CUDiePair;
1938
1939 CUDiePair = *RefDiePair;
1940 } while (refDepth++ < MAX_REFERENCIES_DEPTH);
1941
1942 return CUDiePair;
1943}
1944
1945std::optional<UnitEntryPairTy> UnitEntryPairTy::getParent() {
1946 if (std::optional<uint32_t> ParentIdx = DieEntry->getParentIdx())
1947 return UnitEntryPairTy{CU, CU->getDebugInfoEntry(*ParentIdx)};
1948
1949 return std::nullopt;
1950}
1951
1956
1960
1962 if (isCompileUnit())
1963 return getAsCompileUnit();
1964 else
1965 return getAsTypeUnit();
1966}
1967
1971
1975
1979
1983
1985 bool InterCUProcessingStarted, std::atomic<bool> &HasNewInterconnectedCUs) {
1986 if (!Dependencies)
1987 Dependencies.reset(new DependencyTracker(*this));
1988
1989 return Dependencies->resolveDependenciesAndMarkLiveness(
1990 InterCUProcessingStarted, HasNewInterconnectedCUs);
1991}
1992
1994 assert(Dependencies.get());
1995
1996 return Dependencies->updateDependenciesCompleteness();
1997}
1998
2000 assert(Dependencies.get());
2001
2002 Dependencies->verifyKeepChain();
2003}
2004
2006 static dwarf::Attribute ODRAttributes[] = {
2007 dwarf::DW_AT_type, dwarf::DW_AT_specification,
2008 dwarf::DW_AT_abstract_origin, dwarf::DW_AT_import};
2009
2010 return ODRAttributes;
2011}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:672
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define MAX_REFERENCIES_DEPTH
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
std::optional< T > getRangeThatContains(uint64_t Addr) const
void insert(AddressRange Range, int64_t Value)
The AddressRanges class helps normalize address range collections.
Collection::const_iterator insert(AddressRange Range)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
std::pair< KeyDataTy *, bool > insert(const KeyTy &NewValue)
Insert new value NewValue or return already existing entry.
A structured debug information entry.
Definition DIE.h:840
void setSize(unsigned S)
Definition DIE.h:953
DWARFDebugInfoEntry - A DIE with only the minimum required data.
std::optional< uint32_t > getParentIdx() const
Returns index of the parent die.
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:317
const DWARFDebugInfoEntry * getDebugInfoEntry() const
Definition DWARFDie.h:54
LLVM_ABI const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
Definition DWARFDie.cpp:542
LLVM_ABI std::optional< uint64_t > getLanguage() const
Returns the DW_LANG_ code for this DIE's DWARF unit, if it exists.
Definition DWARFDie.cpp:488
bool isValid() const
Definition DWARFDie.h:52
Encoding
Size and signedness of expression operations' operands.
StringRef getData() const
LLVM_ABI std::optional< uint64_t > getAsSectionOffset() const
LLVM_ABI std::optional< int64_t > getAsSignedConstant() const
LLVM_ABI std::optional< uint64_t > getAsRelativeReference() const
getAsFoo functions below return the extracted value as Foo if only DWARFFormValue has form class is s...
LLVM_ABI std::optional< uint64_t > getAsDebugInfoReference() const
LLVM_ABI std::optional< uint64_t > getAsUnsignedConstant() const
const DWARFUnit * getUnit() const
const dwarf::FormParams & getFormParams() const
Definition DWARFUnit.h:329
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition DWARFUnit.h:450
uint8_t getAddressByteSize() const
Definition DWARFUnit.h:333
const char * getCompilationDir()
Expected< DWARFLocationExpressionsVector > findLoclistFromOffset(uint64_t Offset)
bool isLittleEndian() const
Definition DWARFUnit.h:324
uint64_t getOffset() const
Definition DWARFUnit.h:328
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:134
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMapIterBase< ValueTy, false > iterator
Definition StringMap.h:208
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
iterator end() const
Definition StringRef.h:116
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:25
std::unique_ptr< AddressesMap > Addresses
Helpful address information(list of valid address ranges, relocations).
Definition DWARFFile.h:42
std::unique_ptr< DWARFContext > Dwarf
Source DWARF information.
Definition DWARFFile.h:39
std::map< std::string, std::string > SwiftInterfacesMapTy
CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR, StringRef ClangModuleName)
CompileUnit * getAsCompileUnit()
Returns CompileUnit if applicable.
void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset)
Add the low_pc of a label that is relocated by applying offset PCOffset.
Error cloneAndEmitDebugLocations()
Clone and emit debug locations(.debug_loc/.debug_loclists).
void cloneDieAttrExpression(const DWARFExpression &InputExpression, SmallVectorImpl< uint8_t > &OutputExpression, SectionDescriptor &Section, std::optional< int64_t > VarAddressAdjustment, OffsetsPtrVector &PatchesOffsets)
Clone attribute location axpression.
void maybeResetToLoadedStage()
Reset compile units data(results of liveness analysis, clonning) if current stage greater than Stage:...
void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset)
Add a function range [LowPC, HighPC) that is relocated by applying offset PCOffset.
void analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
std::pair< DIE *, TypeEntry * > cloneDIE(const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *ClonedParentTypeDIE, uint64_t OutOffset, std::optional< int64_t > FuncAddressAdjustment, std::optional< int64_t > VarAddressAdjustment, BumpPtrAllocator &Allocator, TypeUnit *ArtificialTypeUnit, uint32_t SiblingOrdinal=std::numeric_limits< uint32_t >::max())
void cleanupDataAfterClonning()
Cleanup unneeded resources after compile unit is cloned.
Error assignTypeNames(TypePool &TypePoolRef)
Search for type entries and assign names.
llvm::Error setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx)
Set deterministic priority for type DIE allocation ordering.
@ TypeTable
Corresponding DIE goes to the type table only.
@ PlainDwarf
Corresponding DIE goes to the plain dwarf only.
Error cloneAndEmitLineTable(const Triple &TargetTriple)
void mergeSwiftInterfaces(DWARFLinkerBase::SwiftInterfacesMapTy &Map)
Merge the Swift interface entries collected by analyzeImportedModule into Map, emitting a warning for...
void updateDieRefPatchesWithClonedOffsets()
After cloning stage the output DIEs offsets are deallocated.
uint64_t getDebugAddrIndex(uint64_t Addr)
Returns index(inside .debug_addr) of an address.
const DWARFFile & getContaingFile() const
Returns DWARFFile containing this compile unit.
bool resolveDependenciesAndMarkLiveness(bool InterCUProcessingStarted, std::atomic< bool > &HasNewInterconnectedCUs)
Search for subprograms and variables referencing live code and discover dependend DIEs.
bool updateDependenciesCompleteness()
Check dependend DIEs for incompatible placement.
bool loadInputDIEs()
Load DIEs of input compilation unit.
const RangesTy & getFunctionRanges() const
Returns function ranges of this unit.
Error cloneAndEmitDebugMacro()
Clone and emit debug macros(.debug_macinfo/.debug_macro).
Error cloneAndEmit(std::optional< std::reference_wrapper< const Triple > > TargetTriple, TypeUnit *ArtificialTypeUnit)
Clone and emit this compilation unit.
void setStage(Stage Stage)
Set stage of overall processing.
Stage getStage() const
Returns stage of overall processing.
CompileUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName, DWARFFile &File, OffsetToUnitTy UnitFromOffset, dwarf::FormParams Format, llvm::endianness Endianess)
void verifyDependencies()
Check DIEs to have a consistent marking(keep marking, placement marking).
Stage
The stages of new compile unit processing.
@ CreatedNotLoaded
Created, linked with input DWARF file.
std::optional< uint64_t > getLowPc() const
Returns value of DW_AT_low_pc attribute.
std::optional< std::pair< StringRef, StringRef > > getDirAndFilenameFromLineTable(const DWARFFormValue &FileIdxValue)
Returns directory and file from the line table by index.
std::optional< UnitEntryPairTy > resolveDIEReference(const DWARFFormValue &RefValue, ResolveInterCUReferencesMode CanResolveInterCUReferences)
Resolve the DIE attribute reference that has been extracted in RefValue.
StringEntry * getFileName(unsigned FileIdx, StringPool &GlobalStrings)
Returns name of the file for the FileIdx from the unit`s line table.
This class is a helper to create output DIE tree.
void addChild(DIE *Child)
Adds a specified Child to the current DIE.
DIE * createDIE(dwarf::Tag DieTag, uint32_t OutOffset)
Creates a DIE of specified tag DieTag and OutOffset.
This class discovers DIEs dependencies: marks "live" DIEs, marks DIE locations (whether DIE should be...
std::string UnitName
The name of this unit.
LinkingGlobalData & getGlobalData()
Return global data.
std::vector< std::unique_ptr< DIEAbbrev > > Abbreviations
Storage for the unique Abbreviations.
std::string SysRoot
The DW_AT_LLVM_sysroot of this unit.
bool isClangModule() const
Return true if this compile unit is from Clang module.
unsigned ID
Unique ID for the unit.
const std::string & getClangModuleName() const
Return Clang module name;.
void setOutUnitDIE(DIE *UnitDie)
Set output unit DIE.
DwarfUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName)
std::string ClangModuleName
If this is a Clang module, this holds the module's name.
FoldingSet< DIEAbbrev > AbbreviationsSet
FoldingSet that uniques the abbreviations.
StringRef getSysRoot()
Return the DW_AT_LLVM_sysroot of the compile unit or an empty StringRef.
DIE * getOutUnitDIE()
Returns output unit DIE.
This class keeps data and services common for the whole linking process.
This class helps to assign indexes for DIE children.
dwarf::FormParams Format
Format for sections.
const dwarf::FormParams & getFormParams() const
Return size of address.
void eraseSections()
Erases data of all sections.
std::optional< const SectionDescriptor * > tryGetSectionDescriptor(DebugSectionKind SectionKind) const
Returns descriptor for the specified section of SectionKind.
void setOutputFormat(dwarf::FormParams Format, llvm::endianness Endianness)
Sets output format for all keeping sections.
uint16_t getVersion() const
Return DWARF version.
uint16_t getDebugInfoHeaderSize() const
Return size of header of debug_info table.
llvm::endianness getEndianness() const
Endiannes for the sections.
SectionDescriptor & getOrCreateSectionDescriptor(DebugSectionKind SectionKind)
Returns descriptor for the specified section of SectionKind.
const SectionDescriptor & getSectionDescriptor(DebugSectionKind SectionKind) const
Returns descriptor for the specified section of SectionKind.
The helper class to build type name based on DIE properties.
Error assignName(UnitEntryPairTy InputUnitEntryPair, std::optional< std::pair< size_t, size_t > > ChildIndex)
Create synthetic name for the specified DIE InputUnitEntryPair and assign created name to the DIE typ...
Keeps cloned data for the type DIE.
Definition TypePool.h:31
std::atomic< DIE * > Die
TypeEntryBody keeps partially cloned DIEs corresponding to this type.
Definition TypePool.h:60
std::atomic< uint64_t > DiePriority
Definition TypePool.h:71
TypePool keeps type descriptors which contain partially cloned DIE correspinding to each type.
Definition TypePool.h:129
BumpPtrAllocator & getThreadLocalAllocator()
Return thread local allocator used by pool.
Definition TypePool.h:182
TypeEntryBody * getOrCreateTypeEntryBody(TypeEntry *Entry, TypeEntry *ParentEntry)
Create or return existing type entry body for the specified Entry.
Definition TypePool.h:152
TypeEntry * getRoot() const
Return root for all type entries.
Definition TypePool.h:179
Type Unit is used to represent an artificial compilation unit which keeps all type information.
TypePool & getTypePool()
Returns global type pool.
uint64_t tell() const
tell - Return the current offset with the file.
void rememberDieOutOffset(uint32_t Idx, uint64_t Offset)
Idx index of the DIE.
TypeEntry * getDieTypeEntry(uint32_t Idx)
Idx index of the DIE.
DIEInfo & getDIEInfo(unsigned Idx)
Idx index of the DIE.
const DWARFDebugInfoEntry * getSiblingEntry(const DWARFDebugInfoEntry *Die) const
const DWARFDebugInfoEntry * getFirstChildEntry(const DWARFDebugInfoEntry *Die) const
std::optional< uint32_t > getDIEIndexForOffset(uint64_t Offset)
DWARFDie getDIE(const DWARFDebugInfoEntry *Die)
const DWARFDebugInfoEntry * getDebugInfoEntry(unsigned Index) const
DWARFUnit & getOrigUnit() const
Returns paired compile unit from input DWARF.
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const
std::optional< DWARFFormValue > find(uint32_t DieIdx, ArrayRef< dwarf::Attribute > Attrs) const
Error emitDebugInfo(const Triple &TargetTriple)
Emit .debug_info section for unit DIEs.
Error emitDebugLine(const Triple &TargetTriple, const DWARFDebugLine::LineTable &OutLineTable, ArrayRef< uint64_t > OrigRowIndices={}, DenseMap< uint64_t, uint64_t > *RowIndexToSeqStartOffset=nullptr)
Emit .debug_line section.
Error emitDebugStringOffsetSection()
Emit the .debug_str_offsets section for current unit.
void emitPubAccelerators()
Emit .debug_pubnames and .debug_pubtypes for Unit.
void warn(const Twine &Warning, const DWARFDie *DIE=nullptr)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ HeaderSize
Definition BTF.h:61
@ Entry
Definition COFF.h:862
bool isODRLanguage(uint16_t Language)
function_ref< CompileUnit *(uint64_t Offset)> OffsetToUnitTy
SmallVector< uint64_t * > OffsetsPtrVector
Type for list of pointers to patches offsets.
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:28
ArrayRef< dwarf::Attribute > getODRAttributes()
StringRef guessDeveloperDir(StringRef SysRoot)
Make a best effort to guess the Xcode.app/Contents/Developer path from an SDK path.
Definition Utils.h:59
DebugSectionKind
List of tracked debug tables.
LLVM_ABI void buildStmtSeqOffsetToFirstRowIndex(const DWARFDebugLine::LineTable &LT, ArrayRef< uint64_t > SortedStmtSeqOffsets, DenseMap< uint64_t, uint64_t > &SeqOffToFirstRow)
Build a map from an input DW_AT_LLVM_stmt_sequence byte offset to the first-row index (in LT....
Definition Utils.cpp:17
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 isInToolchainDir(StringRef Path)
Make a best effort to determine whether Path is inside a toolchain.
Definition Utils.h:95
bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path)
Definition Utils.h:116
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.
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
Definition Dwarf.h:66
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:478
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:573
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2129
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
Op::Description Desc
static void insertLineSequence(std::vector< TrackedRow > &Seq, std::vector< TrackedRow > &Rows)
Insert the new line info sequence Seq into the current set of already linked line info Rows.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
@ Dwarf
DWARF v5 .debug_names.
Definition DwarfDebug.h:348
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:186
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
bool isCompileUnit(const std::unique_ptr< DWARFUnit > &U)
Definition DWARFUnit.h:602
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
endianness
Definition bit.h:71
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
dwarf::FormParams FormParams
Version, address size (starting in v5), and DWARF32/64 format; these parameters affect interpretation...
Standard .debug_line state machine structure.
object::SectionedAddress Address
The program-counter value corresponding to a machine instruction generated by the compiler and sectio...
Represents a single DWARF expression, whose value is location-dependent.
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1122
DwarfFormat Format
Definition Dwarf.h:1125
uint64_t getDwarfMaxOffset() const
Definition Dwarf.h:1143
uint8_t getDwarfOffsetByteSize() const
The size of a reference is determined by the DWARF 32/64-bit format.
Definition Dwarf.h:1140
This structure is used to update reference to the DIE.
PointerIntPair< CompileUnit *, 1 > RefCU
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.
bool IsCompileUnitRanges
Indicates patch which points to immediate compile unit's attribute.
This structure is used to update reference to the DIE of ULEB128 form.
dwarf::FormParams getFormParams() const
Returns FormParams used by section.
This structure is used to keep data of the concrete section.
raw_svector_ostream OS
Stream which stores data to the Contents.
void emitUnitLength(uint64_t Length)
Emit unit length into the current section contents.
void emitOffset(uint64_t Val)
Emit specified offset value into the current section contents.
void emitIntVal(uint64_t Val, unsigned Size)
Emit specified integer value into the current section contents.
void apply(uint64_t PatchOffset, dwarf::Form AttrForm, uint64_t Val)
Write specified Value of AttrForm to the PatchOffset.
uint64_t getIntVal(uint64_t PatchOffset, unsigned Size)
Returns integer value of Size located by specified PatchOffset.
This is a helper structure which keeps a debug info entry with it's containing compilation unit.