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