Bug Summary

File:llvm/lib/DWARFLinker/DWARFLinker.cpp
Warning:line 1882, column 19
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DWARFLinker.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/DWARFLinker -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/DWARFLinker -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp
1//=== DWARFLinker.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 "llvm/DWARFLinker/DWARFLinker.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/BitVector.h"
12#include "llvm/ADT/Triple.h"
13#include "llvm/CodeGen/NonRelocatableStringpool.h"
14#include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
15#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16#include "llvm/DebugInfo/DWARF/DWARFContext.h"
17#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
18#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
20#include "llvm/DebugInfo/DWARF/DWARFDie.h"
21#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
22#include "llvm/DebugInfo/DWARF/DWARFSection.h"
23#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
24#include "llvm/Support/DataExtractor.h"
25#include "llvm/Support/Error.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/ErrorOr.h"
28#include "llvm/Support/LEB128.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/ThreadPool.h"
31#include <vector>
32
33namespace llvm {
34
35/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
36/// CompileUnit object instead.
37static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
38 auto CU = std::upper_bound(
39 Units.begin(), Units.end(), Offset,
40 [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
41 return LHS < RHS->getOrigUnit().getNextUnitOffset();
42 });
43 return CU != Units.end() ? CU->get() : nullptr;
44}
45
46/// Resolve the DIE attribute reference that has been extracted in \p RefValue.
47/// The resulting DIE might be in another CompileUnit which is stored into \p
48/// ReferencedCU. \returns null if resolving fails for any reason.
49DWARFDie DWARFLinker::resolveDIEReference(const DwarfFile &File,
50 const UnitListTy &Units,
51 const DWARFFormValue &RefValue,
52 const DWARFDie &DIE,
53 CompileUnit *&RefCU) {
54 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference))((RefValue.isFormClass(DWARFFormValue::FC_Reference)) ? static_cast
<void> (0) : __assert_fail ("RefValue.isFormClass(DWARFFormValue::FC_Reference)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 54, __PRETTY_FUNCTION__))
;
11
Assuming the condition is true
12
'?' condition is true
55 uint64_t RefOffset = *RefValue.getAsReference();
56 if ((RefCU = getUnitForOffset(Units, RefOffset)))
13
Assuming 'RefCU' is null
14
Taking false branch
57 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
58 // In a file with broken references, an attribute might point to a NULL
59 // DIE.
60 if (!RefDie.isNULL())
61 return RefDie;
62 }
63
64 reportWarning("could not find referenced DIE", File, &DIE);
65 return DWARFDie();
66}
67
68/// \returns whether the passed \a Attr type might contain a DIE reference
69/// suitable for ODR uniquing.
70static bool isODRAttribute(uint16_t Attr) {
71 switch (Attr) {
72 default:
73 return false;
74 case dwarf::DW_AT_type:
75 case dwarf::DW_AT_containing_type:
76 case dwarf::DW_AT_specification:
77 case dwarf::DW_AT_abstract_origin:
78 case dwarf::DW_AT_import:
79 return true;
80 }
81 llvm_unreachable("Improper attribute.")::llvm::llvm_unreachable_internal("Improper attribute.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 81)
;
82}
83
84static bool isTypeTag(uint16_t Tag) {
85 switch (Tag) {
86 case dwarf::DW_TAG_array_type:
87 case dwarf::DW_TAG_class_type:
88 case dwarf::DW_TAG_enumeration_type:
89 case dwarf::DW_TAG_pointer_type:
90 case dwarf::DW_TAG_reference_type:
91 case dwarf::DW_TAG_string_type:
92 case dwarf::DW_TAG_structure_type:
93 case dwarf::DW_TAG_subroutine_type:
94 case dwarf::DW_TAG_typedef:
95 case dwarf::DW_TAG_union_type:
96 case dwarf::DW_TAG_ptr_to_member_type:
97 case dwarf::DW_TAG_set_type:
98 case dwarf::DW_TAG_subrange_type:
99 case dwarf::DW_TAG_base_type:
100 case dwarf::DW_TAG_const_type:
101 case dwarf::DW_TAG_constant:
102 case dwarf::DW_TAG_file_type:
103 case dwarf::DW_TAG_namelist:
104 case dwarf::DW_TAG_packed_type:
105 case dwarf::DW_TAG_volatile_type:
106 case dwarf::DW_TAG_restrict_type:
107 case dwarf::DW_TAG_atomic_type:
108 case dwarf::DW_TAG_interface_type:
109 case dwarf::DW_TAG_unspecified_type:
110 case dwarf::DW_TAG_shared_type:
111 return true;
112 default:
113 break;
114 }
115 return false;
116}
117
118AddressesMap::~AddressesMap() {}
119
120DwarfEmitter::~DwarfEmitter() {}
121
122static Optional<StringRef> StripTemplateParameters(StringRef Name) {
123 // We are looking for template parameters to strip from Name. e.g.
124 //
125 // operator<<B>
126 //
127 // We look for > at the end but if it does not contain any < then we
128 // have something like operator>>. We check for the operator<=> case.
129 if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
130 return {};
131
132 // How many < until we have the start of the template parameters.
133 size_t NumLeftAnglesToSkip = 1;
134
135 // If we have operator<=> then we need to skip its < as well.
136 NumLeftAnglesToSkip += Name.count("<=>");
137
138 size_t RightAngleCount = Name.count('>');
139 size_t LeftAngleCount = Name.count('<');
140
141 // If we have more < than > we have operator< or operator<<
142 // we to account for their < as well.
143 if (LeftAngleCount > RightAngleCount)
144 NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
145
146 size_t StartOfTemplate = 0;
147 while (NumLeftAnglesToSkip--)
148 StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
149
150 return Name.substr(0, StartOfTemplate - 1);
151}
152
153bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
154 AttributesInfo &Info,
155 OffsetsStringPool &StringPool,
156 bool StripTemplate) {
157 // This function will be called on DIEs having low_pcs and
158 // ranges. As getting the name might be more expansive, filter out
159 // blocks directly.
160 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
161 return false;
162
163 // FIXME: a bit wasteful as the first getName might return the
164 // short name.
165 if (!Info.MangledName)
166 if (const char *MangledName = Die.getName(DINameKind::LinkageName))
167 Info.MangledName = StringPool.getEntry(MangledName);
168
169 if (!Info.Name)
170 if (const char *Name = Die.getName(DINameKind::ShortName))
171 Info.Name = StringPool.getEntry(Name);
172
173 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
174 StringRef Name = Info.Name.getString();
175 if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
176 Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
177 }
178
179 return Info.Name || Info.MangledName;
180}
181
182/// Resolve the relative path to a build artifact referenced by DWARF by
183/// applying DW_AT_comp_dir.
184static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
185 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
186}
187
188/// Collect references to parseable Swift interfaces in imported
189/// DW_TAG_module blocks.
190static void analyzeImportedModule(
191 const DWARFDie &DIE, CompileUnit &CU,
192 swiftInterfacesMap *ParseableSwiftInterfaces,
193 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
194 if (CU.getLanguage() != dwarf::DW_LANG_Swift)
195 return;
196
197 if (!ParseableSwiftInterfaces)
198 return;
199
200 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
201 if (!Path.endswith(".swiftinterface"))
202 return;
203 // Don't track interfaces that are part of the SDK.
204 StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
205 if (SysRoot.empty())
206 SysRoot = CU.getSysRoot();
207 if (!SysRoot.empty() && Path.startswith(SysRoot))
208 return;
209 if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name))
210 if (Optional<const char *> Name = Val->getAsCString()) {
211 auto &Entry = (*ParseableSwiftInterfaces)[*Name];
212 // The prepend path is applied later when copying.
213 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
214 SmallString<128> ResolvedPath;
215 if (sys::path::is_relative(Path))
216 resolveRelativeObjectPath(ResolvedPath, CUDie);
217 sys::path::append(ResolvedPath, Path);
218 if (!Entry.empty() && Entry != ResolvedPath)
219 ReportWarning(
220 Twine("Conflicting parseable interfaces for Swift Module ") +
221 *Name + ": " + Entry + " and " + Path,
222 DIE);
223 Entry = std::string(ResolvedPath.str());
224 }
225}
226
227/// Recursive helper to build the global DeclContext information and
228/// gather the child->parent relationships in the original compile unit.
229///
230/// \return true when this DIE and all of its children are only
231/// forward declarations to types defined in external clang modules
232/// (i.e., forward declarations that are children of a DW_TAG_module).
233static bool analyzeContextInfo(
234 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
235 DeclContext *CurrentDeclContext, UniquingStringPool &StringPool,
236 DeclContextTree &Contexts, uint64_t ModulesEndOffset,
237 swiftInterfacesMap *ParseableSwiftInterfaces,
238 std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
239 bool InImportedModule = false) {
240 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
241 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
242
243 // Clang imposes an ODR on modules(!) regardless of the language:
244 // "The module-id should consist of only a single identifier,
245 // which provides the name of the module being defined. Each
246 // module shall have a single definition."
247 //
248 // This does not extend to the types inside the modules:
249 // "[I]n C, this implies that if two structs are defined in
250 // different submodules with the same name, those two types are
251 // distinct types (but may be compatible types if their
252 // definitions match)."
253 //
254 // We treat non-C++ modules like namespaces for this reason.
255 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
256 dwarf::toString(DIE.find(dwarf::DW_AT_name), "") !=
257 CU.getClangModuleName()) {
258 InImportedModule = true;
259 analyzeImportedModule(DIE, CU, ParseableSwiftInterfaces, ReportWarning);
260 }
261
262 Info.ParentIdx = ParentIdx;
263 bool InClangModule = CU.isClangModule() || InImportedModule;
264 if (CU.hasODR() || InClangModule) {
265 if (CurrentDeclContext) {
266 auto PtrInvalidPair = Contexts.getChildDeclContext(
267 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
268 CurrentDeclContext = PtrInvalidPair.getPointer();
269 Info.Ctxt =
270 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
271 if (Info.Ctxt)
272 Info.Ctxt->setDefinedInClangModule(InClangModule);
273 } else
274 Info.Ctxt = CurrentDeclContext = nullptr;
275 }
276
277 Info.Prune = InImportedModule;
278 if (DIE.hasChildren())
279 for (auto Child : DIE.children())
280 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
281 StringPool, Contexts, ModulesEndOffset,
282 ParseableSwiftInterfaces, ReportWarning,
283 InImportedModule);
284
285 // Prune this DIE if it is either a forward declaration inside a
286 // DW_TAG_module or a DW_TAG_module that contains nothing but
287 // forward declarations.
288 Info.Prune &= (DIE.getTag() == dwarf::DW_TAG_module) ||
289 (isTypeTag(DIE.getTag()) &&
290 dwarf::toUnsigned(DIE.find(dwarf::DW_AT_declaration), 0));
291
292 // Only prune forward declarations inside a DW_TAG_module for which a
293 // definition exists elsewhere.
294 if (ModulesEndOffset == 0)
295 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
296 else
297 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
298 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
299
300 return Info.Prune;
301}
302
303static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
304 switch (Tag) {
305 default:
306 return false;
307 case dwarf::DW_TAG_class_type:
308 case dwarf::DW_TAG_common_block:
309 case dwarf::DW_TAG_lexical_block:
310 case dwarf::DW_TAG_structure_type:
311 case dwarf::DW_TAG_subprogram:
312 case dwarf::DW_TAG_subroutine_type:
313 case dwarf::DW_TAG_union_type:
314 return true;
315 }
316 llvm_unreachable("Invalid Tag")::llvm::llvm_unreachable_internal("Invalid Tag", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 316)
;
317}
318
319void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
320 Context.clear();
321
322 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
323 (*I)->~DIEBlock();
324 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
325 (*I)->~DIELoc();
326
327 DIEBlocks.clear();
328 DIELocs.clear();
329 DIEAlloc.Reset();
330}
331
332/// Get the starting and ending (exclusive) offset for the
333/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
334/// supposed to point to the position of the first attribute described
335/// by \p Abbrev.
336/// \return [StartOffset, EndOffset) as a pair.
337static std::pair<uint64_t, uint64_t>
338getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
339 uint64_t Offset, const DWARFUnit &Unit) {
340 DataExtractor Data = Unit.getDebugInfoExtractor();
341
342 for (unsigned I = 0; I < Idx; ++I)
343 DWARFFormValue::skipValue(Abbrev->getFormByIndex(I), Data, &Offset,
344 Unit.getFormParams());
345
346 uint64_t End = Offset;
347 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End,
348 Unit.getFormParams());
349
350 return std::make_pair(Offset, End);
351}
352
353/// Check if a variable describing DIE should be kept.
354/// \returns updated TraversalFlags.
355unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
356 const DWARFDie &DIE,
357 CompileUnit &Unit,
358 CompileUnit::DIEInfo &MyInfo,
359 unsigned Flags) {
360 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
361
362 // Global variables with constant value can always be kept.
363 if (!(Flags & TF_InFunctionScope) &&
364 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
365 MyInfo.InDebugMap = true;
366 return Flags | TF_Keep;
367 }
368
369 Optional<uint32_t> LocationIdx =
370 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
371 if (!LocationIdx)
372 return Flags;
373
374 uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
375 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
376 uint64_t LocationOffset, LocationEndOffset;
377 std::tie(LocationOffset, LocationEndOffset) =
378 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
379
380 // See if there is a relocation to a valid debug map entry inside
381 // this variable's location. The order is important here. We want to
382 // always check if the variable has a valid relocation, so that the
383 // DIEInfo is filled. However, we don't want a static variable in a
384 // function to force us to keep the enclosing function.
385 if (!RelocMgr.hasValidRelocationAt(LocationOffset, LocationEndOffset,
386 MyInfo) ||
387 (Flags & TF_InFunctionScope))
388 return Flags;
389
390 if (Options.Verbose) {
391 outs() << "Keeping variable DIE:";
392 DIDumpOptions DumpOpts;
393 DumpOpts.ChildRecurseDepth = 0;
394 DumpOpts.Verbose = Options.Verbose;
395 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
396 }
397
398 return Flags | TF_Keep;
399}
400
401/// Check if a function describing DIE should be kept.
402/// \returns updated TraversalFlags.
403unsigned DWARFLinker::shouldKeepSubprogramDIE(
404 AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
405 const DwarfFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
406 unsigned Flags) {
407 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
408
409 Flags |= TF_InFunctionScope;
410
411 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
412 if (!LowPcIdx)
413 return Flags;
414
415 uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
416 DWARFUnit &OrigUnit = Unit.getOrigUnit();
417 uint64_t LowPcOffset, LowPcEndOffset;
418 std::tie(LowPcOffset, LowPcEndOffset) =
419 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
420
421 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
422 assert(LowPc.hasValue() && "low_pc attribute is not an address.")((LowPc.hasValue() && "low_pc attribute is not an address."
) ? static_cast<void> (0) : __assert_fail ("LowPc.hasValue() && \"low_pc attribute is not an address.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 if (!LowPc ||
424 !RelocMgr.hasValidRelocationAt(LowPcOffset, LowPcEndOffset, MyInfo))
425 return Flags;
426
427 if (Options.Verbose) {
428 outs() << "Keeping subprogram DIE:";
429 DIDumpOptions DumpOpts;
430 DumpOpts.ChildRecurseDepth = 0;
431 DumpOpts.Verbose = Options.Verbose;
432 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
433 }
434
435 if (DIE.getTag() == dwarf::DW_TAG_label) {
436 if (Unit.hasLabelAt(*LowPc))
437 return Flags;
438 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
439 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
440 // generation bugs aside, this is really wrong in the case of labels, where
441 // a label marking the end of a function will have a PC == CU's high_pc.
442 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
443 .getValueOr(UINT64_MAX(18446744073709551615UL)) <= LowPc)
444 return Flags;
445 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
446 return Flags | TF_Keep;
447 }
448
449 Flags |= TF_Keep;
450
451 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
452 if (!HighPc) {
453 reportWarning("Function without high_pc. Range will be discarded.\n", File,
454 &DIE);
455 return Flags;
456 }
457
458 // Replace the debug map range with a more accurate one.
459 Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
460 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
461 return Flags;
462}
463
464/// Check if a DIE should be kept.
465/// \returns updated TraversalFlags.
466unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
467 const DWARFDie &DIE, const DwarfFile &File,
468 CompileUnit &Unit,
469 CompileUnit::DIEInfo &MyInfo,
470 unsigned Flags) {
471 switch (DIE.getTag()) {
472 case dwarf::DW_TAG_constant:
473 case dwarf::DW_TAG_variable:
474 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
475 case dwarf::DW_TAG_subprogram:
476 case dwarf::DW_TAG_label:
477 return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
478 Flags);
479 case dwarf::DW_TAG_base_type:
480 // DWARF Expressions may reference basic types, but scanning them
481 // is expensive. Basic types are tiny, so just keep all of them.
482 case dwarf::DW_TAG_imported_module:
483 case dwarf::DW_TAG_imported_declaration:
484 case dwarf::DW_TAG_imported_unit:
485 // We always want to keep these.
486 return Flags | TF_Keep;
487 default:
488 break;
489 }
490
491 return Flags;
492}
493
494/// Helper that updates the completeness of the current DIE based on the
495/// completeness of one of its children. It depends on the incompleteness of
496/// the children already being computed.
497static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
498 CompileUnit::DIEInfo &ChildInfo) {
499 switch (Die.getTag()) {
500 case dwarf::DW_TAG_structure_type:
501 case dwarf::DW_TAG_class_type:
502 break;
503 default:
504 return;
505 }
506
507 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
508 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
509
510 if (ChildInfo.Incomplete || ChildInfo.Prune)
511 MyInfo.Incomplete = true;
512}
513
514/// Helper that updates the completeness of the current DIE based on the
515/// completeness of the DIEs it references. It depends on the incompleteness of
516/// the referenced DIE already being computed.
517static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
518 CompileUnit::DIEInfo &RefInfo) {
519 switch (Die.getTag()) {
520 case dwarf::DW_TAG_typedef:
521 case dwarf::DW_TAG_member:
522 case dwarf::DW_TAG_reference_type:
523 case dwarf::DW_TAG_ptr_to_member_type:
524 case dwarf::DW_TAG_pointer_type:
525 break;
526 default:
527 return;
528 }
529
530 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
531 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
532
533 if (MyInfo.Incomplete)
534 return;
535
536 if (RefInfo.Incomplete)
537 MyInfo.Incomplete = true;
538}
539
540/// Look at the children of the given DIE and decide whether they should be
541/// kept.
542void DWARFLinker::lookForChildDIEsToKeep(
543 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
544 SmallVectorImpl<WorklistItem> &Worklist) {
545 // The TF_ParentWalk flag tells us that we are currently walking up the
546 // parent chain of a required DIE, and we don't want to mark all the children
547 // of the parents as kept (consider for example a DW_TAG_namespace node in
548 // the parent chain). There are however a set of DIE types for which we want
549 // to ignore that directive and still walk their children.
550 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
551 Flags &= ~DWARFLinker::TF_ParentWalk;
552
553 // We're finished if this DIE has no children or we're walking the parent
554 // chain.
555 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
556 return;
557
558 // Add children in reverse order to the worklist to effectively process them
559 // in order.
560 for (auto Child : reverse(Die.children())) {
561 // Add a worklist item before every child to calculate incompleteness right
562 // after the current child is processed.
563 unsigned Idx = CU.getOrigUnit().getDIEIndex(Child);
564 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Idx);
565 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
566 &ChildInfo);
567 Worklist.emplace_back(Child, CU, Flags);
568 }
569}
570
571/// Look at DIEs referenced by the given DIE and decide whether they should be
572/// kept. All DIEs referenced though attributes should be kept.
573void DWARFLinker::lookForRefDIEsToKeep(
574 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
575 const UnitListTy &Units, const DwarfFile &File,
576 SmallVectorImpl<WorklistItem> &Worklist) {
577 bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
578 ? (Flags & DWARFLinker::TF_ODR)
579 : CU.hasODR();
580 DWARFUnit &Unit = CU.getOrigUnit();
581 DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
582 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
583 uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
584
585 SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
586 for (const auto &AttrSpec : Abbrev->attributes()) {
587 DWARFFormValue Val(AttrSpec.Form);
588 if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
589 AttrSpec.Attr == dwarf::DW_AT_sibling) {
590 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
591 Unit.getFormParams());
592 continue;
593 }
594
595 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
596 CompileUnit *ReferencedCU;
597 if (auto RefDie =
598 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
599 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDie);
600 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
601 bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
602 Info.Ctxt->isDefinedInClangModule();
603 // If the referenced DIE has a DeclContext that has already been
604 // emitted, then do not keep the one in this CU. We'll link to
605 // the canonical DIE in cloneDieReferenceAttribute.
606 //
607 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
608 // be necessary and could be advantageously replaced by
609 // ReferencedCU->hasODR() && CU.hasODR().
610 //
611 // FIXME: compatibility with dsymutil-classic. There is no
612 // reason not to unique ref_addr references.
613 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
614 Info.Ctxt &&
615 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
616 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
617 continue;
618
619 // Keep a module forward declaration if there is no definition.
620 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
621 Info.Ctxt->getCanonicalDIEOffset()))
622 Info.Prune = false;
623 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
624 }
625 }
626
627 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
628
629 // Add referenced DIEs in reverse order to the worklist to effectively
630 // process them in order.
631 for (auto &P : reverse(ReferencedDIEs)) {
632 // Add a worklist item before every child to calculate incompleteness right
633 // after the current child is processed.
634 uint32_t RefIdx = P.second.getOrigUnit().getDIEIndex(P.first);
635 CompileUnit::DIEInfo &Info = P.second.getInfo(RefIdx);
636 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
637 &Info);
638 Worklist.emplace_back(P.first, P.second,
639 DWARFLinker::TF_Keep |
640 DWARFLinker::TF_DependencyWalk | ODRFlag);
641 }
642}
643
644/// Look at the parent of the given DIE and decide whether they should be kept.
645void DWARFLinker::lookForParentDIEsToKeep(
646 unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
647 SmallVectorImpl<WorklistItem> &Worklist) {
648 // Stop if we encounter an ancestor that's already marked as kept.
649 if (CU.getInfo(AncestorIdx).Keep)
650 return;
651
652 DWARFUnit &Unit = CU.getOrigUnit();
653 DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
654 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
655 Worklist.emplace_back(ParentDIE, CU, Flags);
656}
657
658/// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
659/// information in \p CU's DIEInfo.
660///
661/// This function is the entry point of the DIE selection algorithm. It is
662/// expected to walk the DIE tree in file order and (though the mediation of
663/// its helper) call hasValidRelocation() on each DIE that might be a 'root
664/// DIE' (See DwarfLinker class comment).
665///
666/// While walking the dependencies of root DIEs, this function is also called,
667/// but during these dependency walks the file order is not respected. The
668/// TF_DependencyWalk flag tells us which kind of traversal we are currently
669/// doing.
670///
671/// The recursive algorithm is implemented iteratively as a work list because
672/// very deep recursion could exhaust the stack for large projects. The work
673/// list acts as a scheduler for different types of work that need to be
674/// performed.
675///
676/// The recursive nature of the algorithm is simulated by running the "main"
677/// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
678/// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
679/// fixing up a computed property (UpdateChildIncompleteness,
680/// UpdateRefIncompleteness).
681///
682/// The return value indicates whether the DIE is incomplete.
683void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
684 RangesTy &Ranges, const UnitListTy &Units,
685 const DWARFDie &Die, const DwarfFile &File,
686 CompileUnit &Cu, unsigned Flags) {
687 // LIFO work list.
688 SmallVector<WorklistItem, 4> Worklist;
689 Worklist.emplace_back(Die, Cu, Flags);
690
691 while (!Worklist.empty()) {
692 WorklistItem Current = Worklist.back();
693 Worklist.pop_back();
694
695 // Look at the worklist type to decide what kind of work to perform.
696 switch (Current.Type) {
697 case WorklistItemType::UpdateChildIncompleteness:
698 updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
699 continue;
700 case WorklistItemType::UpdateRefIncompleteness:
701 updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
702 continue;
703 case WorklistItemType::LookForChildDIEsToKeep:
704 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
705 continue;
706 case WorklistItemType::LookForRefDIEsToKeep:
707 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
708 Worklist);
709 continue;
710 case WorklistItemType::LookForParentDIEsToKeep:
711 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
712 Worklist);
713 continue;
714 case WorklistItemType::LookForDIEsToKeep:
715 break;
716 }
717
718 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
719 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
720
721 if (MyInfo.Prune)
722 continue;
723
724 // If the Keep flag is set, we are marking a required DIE's dependencies.
725 // If our target is already marked as kept, we're all set.
726 bool AlreadyKept = MyInfo.Keep;
727 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
728 continue;
729
730 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
731 // because it would screw up the relocation finding logic.
732 if (!(Current.Flags & TF_DependencyWalk))
733 Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
734 Current.CU, MyInfo, Current.Flags);
735
736 // Finish by looking for child DIEs. Because of the LIFO worklist we need
737 // to schedule that work before any subsequent items are added to the
738 // worklist.
739 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
740 WorklistItemType::LookForChildDIEsToKeep);
741
742 if (AlreadyKept || !(Current.Flags & TF_Keep))
743 continue;
744
745 // If it is a newly kept DIE mark it as well as all its dependencies as
746 // kept.
747 MyInfo.Keep = true;
748
749 // We're looking for incomplete types.
750 MyInfo.Incomplete =
751 Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
752 Current.Die.getTag() != dwarf::DW_TAG_member &&
753 dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
754
755 // After looking at the parent chain, look for referenced DIEs. Because of
756 // the LIFO worklist we need to schedule that work before any subsequent
757 // items are added to the worklist.
758 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
759 WorklistItemType::LookForRefDIEsToKeep);
760
761 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
762 : Current.CU.hasODR();
763 unsigned ODRFlag = UseOdr ? TF_ODR : 0;
764 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
765
766 // Now schedule the parent walk.
767 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
768 }
769}
770
771/// Assign an abbreviation number to \p Abbrev.
772///
773/// Our DIEs get freed after every DebugMapObject has been processed,
774/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
775/// the instances hold by the DIEs. When we encounter an abbreviation
776/// that we don't know, we create a permanent copy of it.
777void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
778 // Check the set for priors.
779 FoldingSetNodeID ID;
780 Abbrev.Profile(ID);
781 void *InsertToken;
782 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
783
784 // If it's newly added.
785 if (InSet) {
786 // Assign existing abbreviation number.
787 Abbrev.setNumber(InSet->getNumber());
788 } else {
789 // Add to abbreviation list.
790 Abbreviations.push_back(
791 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
792 for (const auto &Attr : Abbrev.getData())
793 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
794 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
795 // Assign the unique abbreviation number.
796 Abbrev.setNumber(Abbreviations.size());
797 Abbreviations.back()->setNumber(Abbreviations.size());
798 }
799}
800
801unsigned DWARFLinker::DIECloner::cloneStringAttribute(
802 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
803 const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
804 // Switch everything to out of line strings.
805 const char *String = *Val.getAsCString();
806 auto StringEntry = StringPool.getEntry(String);
807
808 // Update attributes info.
809 if (AttrSpec.Attr == dwarf::DW_AT_name)
810 Info.Name = StringEntry;
811 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
812 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
813 Info.MangledName = StringEntry;
814
815 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
816 DIEInteger(StringEntry.getOffset()));
817
818 return 4;
819}
820
821unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
822 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
823 unsigned AttrSize, const DWARFFormValue &Val, const DwarfFile &File,
824 CompileUnit &Unit) {
825 const DWARFUnit &U = Unit.getOrigUnit();
826 uint64_t Ref = *Val.getAsReference();
827
828 DIE *NewRefDie = nullptr;
829 CompileUnit *RefUnit = nullptr;
830 DeclContext *Ctxt = nullptr;
831
832 DWARFDie RefDie =
833 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
834
835 // If the referenced DIE is not found, drop the attribute.
836 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
837 return 0;
838
839 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
840 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
841
842 // If we already have emitted an equivalent DeclContext, just point
843 // at it.
844 if (isODRAttribute(AttrSpec.Attr)) {
845 Ctxt = RefInfo.Ctxt;
846 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
847 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
848 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
849 dwarf::DW_FORM_ref_addr, Attr);
850 return U.getRefAddrByteSize();
851 }
852 }
853
854 if (!RefInfo.Clone) {
855 assert(Ref > InputDIE.getOffset())((Ref > InputDIE.getOffset()) ? static_cast<void> (0
) : __assert_fail ("Ref > InputDIE.getOffset()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 855, __PRETTY_FUNCTION__))
;
856 // We haven't cloned this DIE yet. Just create an empty one and
857 // store it. It'll get really cloned when we process it.
858 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
859 }
860 NewRefDie = RefInfo.Clone;
861
862 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
863 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
864 // We cannot currently rely on a DIEEntry to emit ref_addr
865 // references, because the implementation calls back to DwarfDebug
866 // to find the unit offset. (We don't have a DwarfDebug)
867 // FIXME: we should be able to design DIEEntry reliance on
868 // DwarfDebug away.
869 uint64_t Attr;
870 if (Ref < InputDIE.getOffset()) {
871 // We must have already cloned that DIE.
872 uint32_t NewRefOffset =
873 RefUnit->getStartOffset() + NewRefDie->getOffset();
874 Attr = NewRefOffset;
875 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
876 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
877 } else {
878 // A forward reference. Note and fixup later.
879 Attr = 0xBADDEF;
880 Unit.noteForwardReference(
881 NewRefDie, RefUnit, Ctxt,
882 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
883 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
884 }
885 return U.getRefAddrByteSize();
886 }
887
888 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
889 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
890
891 return AttrSize;
892}
893
894void DWARFLinker::DIECloner::cloneExpression(
895 DataExtractor &Data, DWARFExpression Expression, const DwarfFile &File,
896 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
897 using Encoding = DWARFExpression::Operation::Encoding;
898
899 uint64_t OpOffset = 0;
900 for (auto &Op : Expression) {
901 auto Description = Op.getDescription();
902 // DW_OP_const_type is variable-length and has 3
903 // operands. DWARFExpression thus far only supports 2.
904 auto Op0 = Description.Op[0];
905 auto Op1 = Description.Op[1];
906 if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
907 (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
908 Linker.reportWarning("Unsupported DW_OP encoding.", File);
909
910 if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
911 (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
912 // This code assumes that the other non-typeref operand fits into 1 byte.
913 assert(OpOffset < Op.getEndOffset())((OpOffset < Op.getEndOffset()) ? static_cast<void> (
0) : __assert_fail ("OpOffset < Op.getEndOffset()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 913, __PRETTY_FUNCTION__))
;
914 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
915 assert(ULEBsize <= 16)((ULEBsize <= 16) ? static_cast<void> (0) : __assert_fail
("ULEBsize <= 16", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 915, __PRETTY_FUNCTION__))
;
916
917 // Copy over the operation.
918 OutputBuffer.push_back(Op.getCode());
919 uint64_t RefOffset;
920 if (Op1 == Encoding::SizeNA) {
921 RefOffset = Op.getRawOperand(0);
922 } else {
923 OutputBuffer.push_back(Op.getRawOperand(0));
924 RefOffset = Op.getRawOperand(1);
925 }
926 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
927 uint32_t RefIdx = Unit.getOrigUnit().getDIEIndex(RefDie);
928 CompileUnit::DIEInfo &Info = Unit.getInfo(RefIdx);
929 uint32_t Offset = 0;
930 if (DIE *Clone = Info.Clone)
931 Offset = Clone->getOffset();
932 else
933 Linker.reportWarning("base type ref doesn't point to DW_TAG_base_type.",
934 File);
935 uint8_t ULEB[16];
936 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
937 if (RealSize > ULEBsize) {
938 // Emit the generic type as a fallback.
939 RealSize = encodeULEB128(0, ULEB, ULEBsize);
940 Linker.reportWarning("base type ref doesn't fit.", File);
941 }
942 assert(RealSize == ULEBsize && "padding failed")((RealSize == ULEBsize && "padding failed") ? static_cast
<void> (0) : __assert_fail ("RealSize == ULEBsize && \"padding failed\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 942, __PRETTY_FUNCTION__))
;
943 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
944 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
945 } else {
946 // Copy over everything else unmodified.
947 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
948 OutputBuffer.append(Bytes.begin(), Bytes.end());
949 }
950 OpOffset = Op.getEndOffset();
951 }
952}
953
954unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
955 DIE &Die, const DwarfFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
956 const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
957 DIEValueList *Attr;
958 DIEValue Value;
959 DIELoc *Loc = nullptr;
960 DIEBlock *Block = nullptr;
961 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
962 Loc = new (DIEAlloc) DIELoc;
963 Linker.DIELocs.push_back(Loc);
964 } else {
965 Block = new (DIEAlloc) DIEBlock;
966 Linker.DIEBlocks.push_back(Block);
967 }
968 Attr = Loc ? static_cast<DIEValueList *>(Loc)
969 : static_cast<DIEValueList *>(Block);
970
971 if (Loc)
972 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
973 dwarf::Form(AttrSpec.Form), Loc);
974 else
975 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
976 dwarf::Form(AttrSpec.Form), Block);
977
978 // If the block is a DWARF Expression, clone it into the temporary
979 // buffer using cloneExpression(), otherwise copy the data directly.
980 SmallVector<uint8_t, 32> Buffer;
981 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
982 if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) &&
983 (Val.isFormClass(DWARFFormValue::FC_Block) ||
984 Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
985 DWARFUnit &OrigUnit = Unit.getOrigUnit();
986 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
987 IsLittleEndian, OrigUnit.getAddressByteSize());
988 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize());
989 cloneExpression(Data, Expr, File, Unit, Buffer);
990 Bytes = Buffer;
991 }
992 for (auto Byte : Bytes)
993 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
994 dwarf::DW_FORM_data1, DIEInteger(Byte));
995
996 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
997 // the DIE class, this "if" could be replaced by
998 // Attr->setSize(Bytes.size()).
999 if (Loc)
1000 Loc->setSize(Bytes.size());
1001 else
1002 Block->setSize(Bytes.size());
1003
1004 Die.addValue(DIEAlloc, Value);
1005 return AttrSize;
1006}
1007
1008unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1009 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1010 const CompileUnit &Unit, AttributesInfo &Info) {
1011 uint64_t Addr = *Val.getAsAddress();
1012
1013 if (LLVM_UNLIKELY(Linker.Options.Update)__builtin_expect((bool)(Linker.Options.Update), false)) {
1014 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1015 Info.HasLowPc = true;
1016 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1017 dwarf::Form(AttrSpec.Form), DIEInteger(Addr));
1018 return Unit.getOrigUnit().getAddressByteSize();
1019 }
1020
1021 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1022 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1023 Die.getTag() == dwarf::DW_TAG_lexical_block)
1024 // The low_pc of a block or inline subroutine might get
1025 // relocated because it happens to match the low_pc of the
1026 // enclosing subprogram. To prevent issues with that, always use
1027 // the low_pc from the input DIE if relocations have been applied.
1028 Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1029 ? Info.OrigLowPc
1030 : Addr) +
1031 Info.PCOffset;
1032 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1033 Addr = Unit.getLowPc();
1034 if (Addr == std::numeric_limits<uint64_t>::max())
1035 return 0;
1036 }
1037 Info.HasLowPc = true;
1038 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1039 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1040 if (uint64_t HighPc = Unit.getHighPc())
1041 Addr = HighPc;
1042 else
1043 return 0;
1044 } else
1045 // If we have a high_pc recorded for the input DIE, use
1046 // it. Otherwise (when no relocations where applied) just use the
1047 // one we just decoded.
1048 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1049 } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
1050 // Relocate a return PC address within a call site entry.
1051 if (Die.getTag() == dwarf::DW_TAG_call_site)
1052 Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
1053 Info.PCOffset;
1054 }
1055
1056 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1057 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1058 return Unit.getOrigUnit().getAddressByteSize();
1059}
1060
1061unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1062 DIE &Die, const DWARFDie &InputDIE, const DwarfFile &File,
1063 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1064 unsigned AttrSize, AttributesInfo &Info) {
1065 uint64_t Value;
1066
1067 if (LLVM_UNLIKELY(Linker.Options.Update)__builtin_expect((bool)(Linker.Options.Update), false)) {
1068 if (auto OptionalValue = Val.getAsUnsignedConstant())
1069 Value = *OptionalValue;
1070 else if (auto OptionalValue = Val.getAsSignedConstant())
1071 Value = *OptionalValue;
1072 else if (auto OptionalValue = Val.getAsSectionOffset())
1073 Value = *OptionalValue;
1074 else {
1075 Linker.reportWarning(
1076 "Unsupported scalar attribute form. Dropping attribute.", File,
1077 &InputDIE);
1078 return 0;
1079 }
1080 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1081 Info.IsDeclaration = true;
1082 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1083 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1084 return AttrSize;
1085 }
1086
1087 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1088 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1089 if (Unit.getLowPc() == -1ULL)
1090 return 0;
1091 // Dwarf >= 4 high_pc is an size, not an address.
1092 Value = Unit.getHighPc() - Unit.getLowPc();
1093 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1094 Value = *Val.getAsSectionOffset();
1095 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1096 Value = *Val.getAsSignedConstant();
1097 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1098 Value = *OptionalValue;
1099 else {
1100 Linker.reportWarning(
1101 "Unsupported scalar attribute form. Dropping attribute.", File,
1102 &InputDIE);
1103 return 0;
1104 }
1105 PatchLocation Patch =
1106 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1107 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1108 if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1109 Unit.noteRangeAttribute(Die, Patch);
1110 Info.HasRanges = true;
1111 }
1112
1113 // A more generic way to check for location attributes would be
1114 // nice, but it's very unlikely that any other attribute needs a
1115 // location list.
1116 // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1117 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1118 AttrSpec.Attr == dwarf::DW_AT_frame_base) {
1119 Unit.noteLocationAttribute(Patch, Info.PCOffset);
1120 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1121 Info.IsDeclaration = true;
1122
1123 return AttrSize;
1124}
1125
1126/// Clone \p InputDIE's attribute described by \p AttrSpec with
1127/// value \p Val, and add it to \p Die.
1128/// \returns the size of the cloned attribute.
1129unsigned DWARFLinker::DIECloner::cloneAttribute(
1130 DIE &Die, const DWARFDie &InputDIE, const DwarfFile &File,
1131 CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1132 const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1133 bool IsLittleEndian) {
1134 const DWARFUnit &U = Unit.getOrigUnit();
1135
1136 switch (AttrSpec.Form) {
1137 case dwarf::DW_FORM_strp:
1138 case dwarf::DW_FORM_string:
1139 return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1140 case dwarf::DW_FORM_ref_addr:
1141 case dwarf::DW_FORM_ref1:
1142 case dwarf::DW_FORM_ref2:
1143 case dwarf::DW_FORM_ref4:
1144 case dwarf::DW_FORM_ref8:
1145 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1146 File, Unit);
1147 case dwarf::DW_FORM_block:
1148 case dwarf::DW_FORM_block1:
1149 case dwarf::DW_FORM_block2:
1150 case dwarf::DW_FORM_block4:
1151 case dwarf::DW_FORM_exprloc:
1152 return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
1153 IsLittleEndian);
1154 case dwarf::DW_FORM_addr:
1155 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1156 case dwarf::DW_FORM_data1:
1157 case dwarf::DW_FORM_data2:
1158 case dwarf::DW_FORM_data4:
1159 case dwarf::DW_FORM_data8:
1160 case dwarf::DW_FORM_udata:
1161 case dwarf::DW_FORM_sdata:
1162 case dwarf::DW_FORM_sec_offset:
1163 case dwarf::DW_FORM_flag:
1164 case dwarf::DW_FORM_flag_present:
1165 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1166 AttrSize, Info);
1167 default:
1168 Linker.reportWarning(
1169 "Unsupported attribute form in cloneAttribute. Dropping.", File,
1170 &InputDIE);
1171 }
1172
1173 return 0;
1174}
1175
1176static bool isObjCSelector(StringRef Name) {
1177 return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1178 (Name[1] == '[');
1179}
1180
1181void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1182 const DIE *Die,
1183 DwarfStringPoolEntryRef Name,
1184 OffsetsStringPool &StringPool,
1185 bool SkipPubSection) {
1186 assert(isObjCSelector(Name.getString()) && "not an objc selector")((isObjCSelector(Name.getString()) && "not an objc selector"
) ? static_cast<void> (0) : __assert_fail ("isObjCSelector(Name.getString()) && \"not an objc selector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 1186, __PRETTY_FUNCTION__))
;
1187 // Objective C method or class function.
1188 // "- [Class(Category) selector :withArg ...]"
1189 StringRef ClassNameStart(Name.getString().drop_front(2));
1190 size_t FirstSpace = ClassNameStart.find(' ');
1191 if (FirstSpace == StringRef::npos)
1192 return;
1193
1194 StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1195 if (!SelectorStart.size())
1196 return;
1197
1198 StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1199 Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1200
1201 // Add an entry for the class name that points to this
1202 // method/class function.
1203 StringRef ClassName(ClassNameStart.data(), FirstSpace);
1204 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1205
1206 if (ClassName[ClassName.size() - 1] == ')') {
1207 size_t OpenParens = ClassName.find('(');
1208 if (OpenParens != StringRef::npos) {
1209 StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1210 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1211 SkipPubSection);
1212
1213 std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1214 // FIXME: The missing space here may be a bug, but
1215 // dsymutil-classic also does it this way.
1216 MethodNameNoCategory.append(std::string(SelectorStart));
1217 Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1218 SkipPubSection);
1219 }
1220 }
1221}
1222
1223static bool
1224shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1225 uint16_t Tag, bool InDebugMap, bool SkipPC,
1226 bool InFunctionScope) {
1227 switch (AttrSpec.Attr) {
1228 default:
1229 return false;
1230 case dwarf::DW_AT_low_pc:
1231 case dwarf::DW_AT_high_pc:
1232 case dwarf::DW_AT_ranges:
1233 return SkipPC;
1234 case dwarf::DW_AT_location:
1235 case dwarf::DW_AT_frame_base:
1236 // FIXME: for some reason dsymutil-classic keeps the location attributes
1237 // when they are of block type (i.e. not location lists). This is totally
1238 // wrong for globals where we will keep a wrong address. It is mostly
1239 // harmless for locals, but there is no point in keeping these anyway when
1240 // the function wasn't linked.
1241 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1242 !InDebugMap)) &&
1243 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1244 }
1245}
1246
1247DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1248 const DwarfFile &File, CompileUnit &Unit,
1249 OffsetsStringPool &StringPool,
1250 int64_t PCOffset, uint32_t OutOffset,
1251 unsigned Flags, bool IsLittleEndian,
1252 DIE *Die) {
1253 DWARFUnit &U = Unit.getOrigUnit();
1254 unsigned Idx = U.getDIEIndex(InputDIE);
1255 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1256
1257 // Should the DIE appear in the output?
1258 if (!Unit.getInfo(Idx).Keep)
1259 return nullptr;
1260
1261 uint64_t Offset = InputDIE.getOffset();
1262 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE")((!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE"
) ? static_cast<void> (0) : __assert_fail ("!(Die && Info.Clone) && \"Can't supply a DIE and a cloned DIE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 1262, __PRETTY_FUNCTION__))
;
1263 if (!Die) {
1264 // The DIE might have been already created by a forward reference
1265 // (see cloneDieReferenceAttribute()).
1266 if (!Info.Clone)
1267 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1268 Die = Info.Clone;
1269 }
1270
1271 assert(Die->getTag() == InputDIE.getTag())((Die->getTag() == InputDIE.getTag()) ? static_cast<void
> (0) : __assert_fail ("Die->getTag() == InputDIE.getTag()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 1271, __PRETTY_FUNCTION__))
;
1272 Die->setOffset(OutOffset);
1273 if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
1274 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
1275 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
1276 !Info.Ctxt->getCanonicalDIEOffset()) {
1277 // We are about to emit a DIE that is the root of its own valid
1278 // DeclContext tree. Make the current offset the canonical offset
1279 // for this context.
1280 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1281 }
1282
1283 // Extract and clone every attribute.
1284 DWARFDataExtractor Data = U.getDebugInfoExtractor();
1285 // Point to the next DIE (generally there is always at least a NULL
1286 // entry after the current one). If this is a lone
1287 // DW_TAG_compile_unit without any children, point to the next unit.
1288 uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1289 ? U.getDIEAtIndex(Idx + 1).getOffset()
1290 : U.getNextUnitOffset();
1291 AttributesInfo AttrInfo;
1292
1293 // We could copy the data only if we need to apply a relocation to it. After
1294 // testing, it seems there is no performance downside to doing the copy
1295 // unconditionally, and it makes the code simpler.
1296 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1297 Data =
1298 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1299
1300 // Modify the copy with relocated addresses.
1301 if (ObjFile.Addresses->areRelocationsResolved() &&
1302 ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
1303 Data.isLittleEndian())) {
1304 // If we applied relocations, we store the value of high_pc that was
1305 // potentially stored in the input DIE. If high_pc is an address
1306 // (Dwarf version == 2), then it might have been relocated to a
1307 // totally unrelated value (because the end address in the object
1308 // file might be start address of another function which got moved
1309 // independently by the linker). The computation of the actual
1310 // high_pc value is done in cloneAddressAttribute().
1311 AttrInfo.OrigHighPc =
1312 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1313 // Also store the low_pc. It might get relocated in an
1314 // inline_subprogram that happens at the beginning of its
1315 // inlining function.
1316 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1317 std::numeric_limits<uint64_t>::max());
1318 AttrInfo.OrigCallReturnPc =
1319 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
1320 }
1321
1322 // Reset the Offset to 0 as we will be working on the local copy of
1323 // the data.
1324 Offset = 0;
1325
1326 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1327 Offset += getULEB128Size(Abbrev->getCode());
1328
1329 // We are entering a subprogram. Get and propagate the PCOffset.
1330 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1331 PCOffset = Info.AddrAdjust;
1332 AttrInfo.PCOffset = PCOffset;
1333
1334 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1335 Flags |= TF_InFunctionScope;
1336 if (!Info.InDebugMap && LLVM_LIKELY(!Update)__builtin_expect((bool)(!Update), true))
1337 Flags |= TF_SkipPC;
1338 }
1339
1340 bool Copied = false;
1341 for (const auto &AttrSpec : Abbrev->attributes()) {
1342 if (LLVM_LIKELY(!Update)__builtin_expect((bool)(!Update), true) &&
1343 shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1344 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1345 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1346 U.getFormParams());
1347 // FIXME: dsymutil-classic keeps the old abbreviation around
1348 // even if it's not used. We can remove this (and the copyAbbrev
1349 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1350 if (!Copied) {
1351 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
1352 Copied = true;
1353 }
1354 continue;
1355 }
1356
1357 DWARFFormValue Val(AttrSpec.Form);
1358 uint64_t AttrSize = Offset;
1359 Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1360 AttrSize = Offset - AttrSize;
1361
1362 OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
1363 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1364 }
1365
1366 // Look for accelerator entries.
1367 uint16_t Tag = InputDIE.getTag();
1368 // FIXME: This is slightly wrong. An inline_subroutine without a
1369 // low_pc, but with AT_ranges might be interesting to get into the
1370 // accelerator tables too. For now stick with dsymutil's behavior.
1371 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1372 Tag != dwarf::DW_TAG_compile_unit &&
1373 getDIENames(InputDIE, AttrInfo, StringPool,
1374 Tag != dwarf::DW_TAG_inlined_subroutine)) {
1375 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1376 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1377 Tag == dwarf::DW_TAG_inlined_subroutine);
1378 if (AttrInfo.Name) {
1379 if (AttrInfo.NameWithoutTemplate)
1380 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1381 /* SkipPubSection */ true);
1382 Unit.addNameAccelerator(Die, AttrInfo.Name,
1383 Tag == dwarf::DW_TAG_inlined_subroutine);
1384 }
1385 if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1386 addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1387 /* SkipPubSection =*/true);
1388
1389 } else if (Tag == dwarf::DW_TAG_namespace) {
1390 if (!AttrInfo.Name)
1391 AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1392 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1393 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1394 getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1395 AttrInfo.Name.getString()[0]) {
1396 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
1397 uint64_t RuntimeLang =
1398 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1399 .getValueOr(0);
1400 bool ObjCClassIsImplementation =
1401 (RuntimeLang == dwarf::DW_LANG_ObjC ||
1402 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1403 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1404 .getValueOr(0);
1405 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1406 Hash);
1407 }
1408
1409 // Determine whether there are any children that we want to keep.
1410 bool HasChildren = false;
1411 for (auto Child : InputDIE.children()) {
1412 unsigned Idx = U.getDIEIndex(Child);
1413 if (Unit.getInfo(Idx).Keep) {
1414 HasChildren = true;
1415 break;
1416 }
1417 }
1418
1419 DIEAbbrev NewAbbrev = Die->generateAbbrev();
1420 if (HasChildren)
1421 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1422 // Assign a permanent abbrev number
1423 Linker.assignAbbrev(NewAbbrev);
1424 Die->setAbbrevNumber(NewAbbrev.getNumber());
1425
1426 // Add the size of the abbreviation number to the output offset.
1427 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1428
1429 if (!HasChildren) {
1430 // Update our size.
1431 Die->setSize(OutOffset - Die->getOffset());
1432 return Die;
1433 }
1434
1435 // Recursively clone children.
1436 for (auto Child : InputDIE.children()) {
1437 if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
1438 OutOffset, Flags, IsLittleEndian)) {
1439 Die->addChild(Clone);
1440 OutOffset = Clone->getOffset() + Clone->getSize();
1441 }
1442 }
1443
1444 // Account for the end of children marker.
1445 OutOffset += sizeof(int8_t);
1446 // Update our size.
1447 Die->setSize(OutOffset - Die->getOffset());
1448 return Die;
1449}
1450
1451/// Patch the input object file relevant debug_ranges entries
1452/// and emit them in the output file. Update the relevant attributes
1453/// to point at the new entries.
1454void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
1455 DWARFContext &OrigDwarf,
1456 const DwarfFile &File) const {
1457 DWARFDebugRangeList RangeList;
1458 const auto &FunctionRanges = Unit.getFunctionRanges();
1459 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1460 DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1461 OrigDwarf.getDWARFObj().getRangesSection(),
1462 OrigDwarf.isLittleEndian(), AddressSize);
1463 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1464 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1465 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1466 uint64_t OrigLowPc =
1467 dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1468 // Ranges addresses are based on the unit's low_pc. Compute the
1469 // offset we need to apply to adapt to the new unit's low_pc.
1470 int64_t UnitPcOffset = 0;
1471 if (OrigLowPc != -1ULL)
1472 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1473
1474 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1475 uint64_t Offset = RangeAttribute.get();
1476 RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
1477 if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1478 llvm::consumeError(std::move(E));
1479 reportWarning("invalid range list ignored.", File);
1480 RangeList.clear();
1481 }
1482 const auto &Entries = RangeList.getEntries();
1483 if (!Entries.empty()) {
1484 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1485
1486 if (CurrRange == InvalidRange ||
1487 First.StartAddress + OrigLowPc < CurrRange.start() ||
1488 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
1489 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1490 if (CurrRange == InvalidRange ||
1491 CurrRange.start() > First.StartAddress + OrigLowPc) {
1492 reportWarning("no mapping for range.", File);
1493 continue;
1494 }
1495 }
1496 }
1497
1498 TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
1499 Entries, AddressSize);
1500 }
1501}
1502
1503/// Generate the debug_aranges entries for \p Unit and if the
1504/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1505/// contribution for this attribute.
1506/// FIXME: this could actually be done right in patchRangesForUnit,
1507/// but for the sake of initial bit-for-bit compatibility with legacy
1508/// dsymutil, we have to do it in a delayed pass.
1509void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
1510 auto Attr = Unit.getUnitRangesAttribute();
1511 if (Attr)
1512 Attr->set(TheDwarfEmitter->getRangesSectionSize());
1513 TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1514}
1515
1516/// Insert the new line info sequence \p Seq into the current
1517/// set of already linked line info \p Rows.
1518static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1519 std::vector<DWARFDebugLine::Row> &Rows) {
1520 if (Seq.empty())
1521 return;
1522
1523 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1524 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
1525 Seq.clear();
1526 return;
1527 }
1528
1529 object::SectionedAddress Front = Seq.front().Address;
1530 auto InsertPoint = partition_point(
1531 Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1532
1533 // FIXME: this only removes the unneeded end_sequence if the
1534 // sequences have been inserted in order. Using a global sort like
1535 // described in patchLineTableForUnit() and delaying the end_sequene
1536 // elimination to emitLineTableForUnit() we can get rid of all of them.
1537 if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1538 InsertPoint->EndSequence) {
1539 *InsertPoint = Seq.front();
1540 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1541 } else {
1542 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1543 }
1544
1545 Seq.clear();
1546}
1547
1548static void patchStmtList(DIE &Die, DIEInteger Offset) {
1549 for (auto &V : Die.values())
1550 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1551 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1552 return;
1553 }
1554
1555 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!")::llvm::llvm_unreachable_internal("Didn't find DW_AT_stmt_list in cloned DIE!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 1555)
;
1556}
1557
1558/// Extract the line table for \p Unit from \p OrigDwarf, and
1559/// recreate a relocated version of these for the address ranges that
1560/// are present in the binary.
1561void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
1562 DWARFContext &OrigDwarf,
1563 const DwarfFile &File) {
1564 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1565 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1566 if (!StmtList)
1567 return;
1568
1569 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1570 if (auto *OutputDIE = Unit.getOutputUnitDIE())
1571 patchStmtList(*OutputDIE,
1572 DIEInteger(TheDwarfEmitter->getLineSectionSize()));
1573
1574 RangesTy &Ranges = File.Addresses->getValidAddressRanges();
1575
1576 // Parse the original line info for the unit.
1577 DWARFDebugLine::LineTable LineTable;
1578 uint64_t StmtOffset = *StmtList;
1579 DWARFDataExtractor LineExtractor(
1580 OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1581 OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1582 if (needToTranslateStrings())
1583 return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
1584
1585 if (Error Err =
1586 LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1587 &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
1588 OrigDwarf.getWarningHandler()(std::move(Err));
1589
1590 // This vector is the output line table.
1591 std::vector<DWARFDebugLine::Row> NewRows;
1592 NewRows.reserve(LineTable.Rows.size());
1593
1594 // Current sequence of rows being extracted, before being inserted
1595 // in NewRows.
1596 std::vector<DWARFDebugLine::Row> Seq;
1597 const auto &FunctionRanges = Unit.getFunctionRanges();
1598 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1599
1600 // FIXME: This logic is meant to generate exactly the same output as
1601 // Darwin's classic dsymutil. There is a nicer way to implement this
1602 // by simply putting all the relocated line info in NewRows and simply
1603 // sorting NewRows before passing it to emitLineTableForUnit. This
1604 // should be correct as sequences for a function should stay
1605 // together in the sorted output. There are a few corner cases that
1606 // look suspicious though, and that required to implement the logic
1607 // this way. Revisit that once initial validation is finished.
1608
1609 // Iterate over the object file line info and extract the sequences
1610 // that correspond to linked functions.
1611 for (auto &Row : LineTable.Rows) {
1612 // Check whether we stepped out of the range. The range is
1613 // half-open, but consider accept the end address of the range if
1614 // it is marked as end_sequence in the input (because in that
1615 // case, the relocation offset is accurate and that entry won't
1616 // serve as the start of another function).
1617 if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
1618 Row.Address.Address > CurrRange.stop() ||
1619 (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
1620 // We just stepped out of a known range. Insert a end_sequence
1621 // corresponding to the end of the range.
1622 uint64_t StopAddress = CurrRange != InvalidRange
1623 ? CurrRange.stop() + CurrRange.value()
1624 : -1ULL;
1625 CurrRange = FunctionRanges.find(Row.Address.Address);
1626 bool CurrRangeValid =
1627 CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
1628 if (!CurrRangeValid) {
1629 CurrRange = InvalidRange;
1630 if (StopAddress != -1ULL) {
1631 // Try harder by looking in the Address ranges map.
1632 // There are corner cases where this finds a
1633 // valid entry. It's unclear if this is right or wrong, but
1634 // for now do as dsymutil.
1635 // FIXME: Understand exactly what cases this addresses and
1636 // potentially remove it along with the Ranges map.
1637 auto Range = Ranges.lower_bound(Row.Address.Address);
1638 if (Range != Ranges.begin() && Range != Ranges.end())
1639 --Range;
1640
1641 if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
1642 Range->second.HighPC >= Row.Address.Address) {
1643 StopAddress = Row.Address.Address + Range->second.Offset;
1644 }
1645 }
1646 }
1647 if (StopAddress != -1ULL && !Seq.empty()) {
1648 // Insert end sequence row with the computed end address, but
1649 // the same line as the previous one.
1650 auto NextLine = Seq.back();
1651 NextLine.Address.Address = StopAddress;
1652 NextLine.EndSequence = 1;
1653 NextLine.PrologueEnd = 0;
1654 NextLine.BasicBlock = 0;
1655 NextLine.EpilogueBegin = 0;
1656 Seq.push_back(NextLine);
1657 insertLineSequence(Seq, NewRows);
1658 }
1659
1660 if (!CurrRangeValid)
1661 continue;
1662 }
1663
1664 // Ignore empty sequences.
1665 if (Row.EndSequence && Seq.empty())
1666 continue;
1667
1668 // Relocate row address and add it to the current sequence.
1669 Row.Address.Address += CurrRange.value();
1670 Seq.emplace_back(Row);
1671
1672 if (Row.EndSequence)
1673 insertLineSequence(Seq, NewRows);
1674 }
1675
1676 // Finished extracting, now emit the line tables.
1677 // FIXME: LLVM hard-codes its prologue values. We just copy the
1678 // prologue over and that works because we act as both producer and
1679 // consumer. It would be nicer to have a real configurable line
1680 // table emitter.
1681 if (LineTable.Prologue.getVersion() < 2 ||
1682 LineTable.Prologue.getVersion() > 5 ||
1683 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT1 ||
1684 LineTable.Prologue.OpcodeBase > 13)
1685 reportWarning("line table parameters mismatch. Cannot emit.", File);
1686 else {
1687 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1688 // DWARF v5 has an extra 2 bytes of information before the header_length
1689 // field.
1690 if (LineTable.Prologue.getVersion() == 5)
1691 PrologueEnd += 2;
1692 StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1693 MCDwarfLineTableParams Params;
1694 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1695 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1696 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1697 TheDwarfEmitter->emitLineTableForUnit(
1698 Params, LineData.slice(*StmtList + 4, PrologueEnd),
1699 LineTable.Prologue.MinInstLength, NewRows,
1700 Unit.getOrigUnit().getAddressByteSize());
1701 }
1702}
1703
1704void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1705 switch (Options.TheAccelTableKind) {
1706 case AccelTableKind::Apple:
1707 emitAppleAcceleratorEntriesForUnit(Unit);
1708 break;
1709 case AccelTableKind::Dwarf:
1710 emitDwarfAcceleratorEntriesForUnit(Unit);
1711 break;
1712 case AccelTableKind::Default:
1713 llvm_unreachable("The default must be updated to a concrete value.")::llvm::llvm_unreachable_internal("The default must be updated to a concrete value."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 1713)
;
1714 break;
1715 }
1716}
1717
1718void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1719 // Add namespaces.
1720 for (const auto &Namespace : Unit.getNamespaces())
1721 AppleNamespaces.addName(Namespace.Name,
1722 Namespace.Die->getOffset() + Unit.getStartOffset());
1723
1724 /// Add names.
1725 TheDwarfEmitter->emitPubNamesForUnit(Unit);
1726 for (const auto &Pubname : Unit.getPubnames())
1727 AppleNames.addName(Pubname.Name,
1728 Pubname.Die->getOffset() + Unit.getStartOffset());
1729
1730 /// Add types.
1731 TheDwarfEmitter->emitPubTypesForUnit(Unit);
1732 for (const auto &Pubtype : Unit.getPubtypes())
1733 AppleTypes.addName(
1734 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1735 Pubtype.Die->getTag(),
1736 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1737 : 0,
1738 Pubtype.QualifiedNameHash);
1739
1740 /// Add ObjC names.
1741 for (const auto &ObjC : Unit.getObjC())
1742 AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1743}
1744
1745void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1746 for (const auto &Namespace : Unit.getNamespaces())
1747 DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1748 Namespace.Die->getTag(), Unit.getUniqueID());
1749 for (const auto &Pubname : Unit.getPubnames())
1750 DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1751 Pubname.Die->getTag(), Unit.getUniqueID());
1752 for (const auto &Pubtype : Unit.getPubtypes())
1753 DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1754 Pubtype.Die->getTag(), Unit.getUniqueID());
1755}
1756
1757/// Read the frame info stored in the object, and emit the
1758/// patched frame descriptions for the resulting file.
1759///
1760/// This is actually pretty easy as the data of the CIEs and FDEs can
1761/// be considered as black boxes and moved as is. The only thing to do
1762/// is to patch the addresses in the headers.
1763void DWARFLinker::patchFrameInfoForObject(const DwarfFile &File,
1764 RangesTy &Ranges,
1765 DWARFContext &OrigDwarf,
1766 unsigned AddrSize) {
1767 StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
1768 if (FrameData.empty())
1769 return;
1770
1771 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
1772 uint64_t InputOffset = 0;
1773
1774 // Store the data of the CIEs defined in this object, keyed by their
1775 // offsets.
1776 DenseMap<uint64_t, StringRef> LocalCIES;
1777
1778 while (Data.isValidOffset(InputOffset)) {
1779 uint64_t EntryOffset = InputOffset;
1780 uint32_t InitialLength = Data.getU32(&InputOffset);
1781 if (InitialLength == 0xFFFFFFFF)
1782 return reportWarning("Dwarf64 bits no supported", File);
1783
1784 uint32_t CIEId = Data.getU32(&InputOffset);
1785 if (CIEId == 0xFFFFFFFF) {
1786 // This is a CIE, store it.
1787 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
1788 LocalCIES[EntryOffset] = CIEData;
1789 // The -4 is to account for the CIEId we just read.
1790 InputOffset += InitialLength - 4;
1791 continue;
1792 }
1793
1794 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
1795
1796 // Some compilers seem to emit frame info that doesn't start at
1797 // the function entry point, thus we can't just lookup the address
1798 // in the debug map. Use the AddressInfo's range map to see if the FDE
1799 // describes something that we can relocate.
1800 auto Range = Ranges.upper_bound(Loc);
1801 if (Range != Ranges.begin())
1802 --Range;
1803 if (Range == Ranges.end() || Range->first > Loc ||
1804 Range->second.HighPC <= Loc) {
1805 // The +4 is to account for the size of the InitialLength field itself.
1806 InputOffset = EntryOffset + InitialLength + 4;
1807 continue;
1808 }
1809
1810 // This is an FDE, and we have a mapping.
1811 // Have we already emitted a corresponding CIE?
1812 StringRef CIEData = LocalCIES[CIEId];
1813 if (CIEData.empty())
1814 return reportWarning("Inconsistent debug_frame content. Dropping.", File);
1815
1816 // Look if we already emitted a CIE that corresponds to the
1817 // referenced one (the CIE data is the key of that lookup).
1818 auto IteratorInserted = EmittedCIEs.insert(
1819 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
1820 // If there is no CIE yet for this ID, emit it.
1821 if (IteratorInserted.second ||
1822 // FIXME: dsymutil-classic only caches the last used CIE for
1823 // reuse. Mimic that behavior for now. Just removing that
1824 // second half of the condition and the LastCIEOffset variable
1825 // makes the code DTRT.
1826 LastCIEOffset != IteratorInserted.first->getValue()) {
1827 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
1828 IteratorInserted.first->getValue() = LastCIEOffset;
1829 TheDwarfEmitter->emitCIE(CIEData);
1830 }
1831
1832 // Emit the FDE with updated address and CIE pointer.
1833 // (4 + AddrSize) is the size of the CIEId + initial_location
1834 // fields that will get reconstructed by emitFDE().
1835 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
1836 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
1837 Loc + Range->second.Offset,
1838 FrameData.substr(InputOffset, FDERemainingBytes));
1839 InputOffset += FDERemainingBytes;
1840 }
1841}
1842
1843void DWARFLinker::DIECloner::copyAbbrev(
1844 const DWARFAbbreviationDeclaration &Abbrev, bool HasODR) {
1845 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
1846 dwarf::Form(Abbrev.hasChildren()));
1847
1848 for (const auto &Attr : Abbrev.attributes()) {
1849 uint16_t Form = Attr.Form;
1850 if (HasODR && isODRAttribute(Attr.Attr))
1851 Form = dwarf::DW_FORM_ref_addr;
1852 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
1853 }
1854
1855 Linker.assignAbbrev(Copy);
1856}
1857
1858uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
1859 CompileUnit &U,
1860 const DwarfFile &File,
1861 int ChildRecurseDepth) {
1862 const char *Name = nullptr;
1863 DWARFUnit *OrigUnit = &U.getOrigUnit();
1864 CompileUnit *CU = &U;
1865 Optional<DWARFFormValue> Ref;
1866
1867 while (1) {
1
Loop condition is true. Entering loop body
1868 if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
2
Assuming 'CurrentName' is null
3
Taking false branch
1869 Name = CurrentName;
1870
1871 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
4
Assuming the condition is true
6
Taking false branch
1872 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
5
Assuming the condition is false
1873 break;
1874
1875 if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
7
Assuming the condition is false
8
Taking false branch
1876 break;
1877
1878 CompileUnit *RefCU;
9
'RefCU' initialized here
1879 if (auto RefDIE =
16
Assuming the condition is true
17
Taking true branch
1880 Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
10
Calling 'DWARFLinker::resolveDIEReference'
15
Returning from 'DWARFLinker::resolveDIEReference'
1881 CU = RefCU;
1882 OrigUnit = &RefCU->getOrigUnit();
18
Called C++ object pointer is null
1883 DIE = RefDIE;
1884 }
1885 }
1886
1887 unsigned Idx = OrigUnit->getDIEIndex(DIE);
1888 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
1889 Name = "(anonymous namespace)";
1890
1891 if (CU->getInfo(Idx).ParentIdx == 0 ||
1892 // FIXME: dsymutil-classic compatibility. Ignore modules.
1893 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
1894 dwarf::DW_TAG_module)
1895 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
1896
1897 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
1898 return djbHash(
1899 (Name ? Name : ""),
1900 djbHash((Name ? "::" : ""),
1901 hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
1902}
1903
1904static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
1905 auto DwoId = dwarf::toUnsigned(
1906 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
1907 if (DwoId)
1908 return *DwoId;
1909 return 0;
1910}
1911
1912bool DWARFLinker::registerModuleReference(
1913 DWARFDie CUDie, const DWARFUnit &Unit, const DwarfFile &File,
1914 OffsetsStringPool &StringPool, UniquingStringPool &UniquingStringPool,
1915 DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
1916 bool IsLittleEndian, unsigned Indent, bool Quiet) {
1917 std::string PCMfile = dwarf::toString(
1918 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
1919 if (PCMfile.empty())
1920 return false;
1921
1922 // Clang module DWARF skeleton CUs abuse this for the path to the module.
1923 uint64_t DwoId = getDwoId(CUDie, Unit);
1924
1925 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
1926 if (Name.empty()) {
1927 if (!Quiet)
1928 reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
1929 return true;
1930 }
1931
1932 if (!Quiet && Options.Verbose) {
1933 outs().indent(Indent);
1934 outs() << "Found clang module reference " << PCMfile;
1935 }
1936
1937 auto Cached = ClangModules.find(PCMfile);
1938 if (Cached != ClangModules.end()) {
1939 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
1940 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
1941 // ASTFileSignatures will change randomly when a module is rebuilt.
1942 if (!Quiet && Options.Verbose && (Cached->second != DwoId))
1943 reportWarning(Twine("hash mismatch: this object file was built against a "
1944 "different version of the module ") +
1945 PCMfile,
1946 File);
1947 if (!Quiet && Options.Verbose)
1948 outs() << " [cached].\n";
1949 return true;
1950 }
1951 if (!Quiet && Options.Verbose)
1952 outs() << " ...\n";
1953
1954 // Cyclic dependencies are disallowed by Clang, but we still
1955 // shouldn't run into an infinite loop, so mark it as processed now.
1956 ClangModules.insert({PCMfile, DwoId});
1957
1958 if (Error E =
1959 loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
1960 UniquingStringPool, ODRContexts, ModulesEndOffset,
1961 UnitID, IsLittleEndian, Indent + 2, Quiet)) {
1962 consumeError(std::move(E));
1963 return false;
1964 }
1965 return true;
1966}
1967
1968Error DWARFLinker::loadClangModule(
1969 DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
1970 const DwarfFile &File, OffsetsStringPool &StringPool,
1971 UniquingStringPool &UniquingStringPool, DeclContextTree &ODRContexts,
1972 uint64_t ModulesEndOffset, unsigned &UnitID, bool IsLittleEndian,
1973 unsigned Indent, bool Quiet) {
1974 /// Using a SmallString<0> because loadClangModule() is recursive.
1975 SmallString<0> Path(Options.PrependPath);
1976 if (sys::path::is_relative(Filename))
1977 resolveRelativeObjectPath(Path, CUDie);
1978 sys::path::append(Path, Filename);
1979 // Don't use the cached binary holder because we have no thread-safety
1980 // guarantee and the lifetime is limited.
1981
1982 if (Options.ObjFileLoader == nullptr)
1983 return Error::success();
1984
1985 auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
1986 if (!ErrOrObj)
1987 return Error::success();
1988
1989 std::unique_ptr<CompileUnit> Unit;
1990
1991 for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
1992 updateDwarfVersion(CU->getVersion());
1993 // Recursively get all modules imported by this one.
1994 auto CUDie = CU->getUnitDIE(false);
1995 if (!CUDie)
1996 continue;
1997 if (!registerModuleReference(
1998 CUDie, *CU, File, StringPool, UniquingStringPool, ODRContexts,
1999 ModulesEndOffset, UnitID, IsLittleEndian, Indent, Quiet)) {
2000 if (Unit) {
2001 std::string Err =
2002 (Filename +
2003 ": Clang modules are expected to have exactly 1 compile unit.\n")
2004 .str();
2005 reportError(Err, File);
2006 return make_error<StringError>(Err, inconvertibleErrorCode());
2007 }
2008 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2009 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2010 // ASTFileSignatures will change randomly when a module is rebuilt.
2011 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2012 if (PCMDwoId != DwoId) {
2013 if (!Quiet && Options.Verbose)
2014 reportWarning(
2015 Twine("hash mismatch: this object file was built against a "
2016 "different version of the module ") +
2017 Filename,
2018 File);
2019 // Update the cache entry with the DwoId of the module loaded from disk.
2020 ClangModules[Filename] = PCMDwoId;
2021 }
2022
2023 // Add this module.
2024 Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2025 ModuleName);
2026 Unit->setHasInterestingContent();
2027 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(),
2028 UniquingStringPool, ODRContexts, ModulesEndOffset,
2029 Options.ParseableSwiftInterfaces,
2030 [&](const Twine &Warning, const DWARFDie &DIE) {
2031 reportWarning(Warning, File, &DIE);
2032 });
2033 // Keep everything.
2034 Unit->markEverythingAsKept();
2035 }
2036 }
2037 if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2038 return Error::success();
2039 if (!Quiet && Options.Verbose) {
2040 outs().indent(Indent);
2041 outs() << "cloning .debug_info from " << Filename << "\n";
2042 }
2043
2044 UnitListTy CompileUnits;
2045 CompileUnits.push_back(std::move(Unit));
2046 assert(TheDwarfEmitter)((TheDwarfEmitter) ? static_cast<void> (0) : __assert_fail
("TheDwarfEmitter", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2046, __PRETTY_FUNCTION__))
;
2047 DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
2048 Options.Update)
2049 .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
2050 IsLittleEndian);
2051 return Error::success();
2052}
2053
2054void DWARFLinker::DIECloner::cloneAllCompileUnits(DWARFContext &DwarfContext,
2055 const DwarfFile &File,
2056 OffsetsStringPool &StringPool,
2057 bool IsLittleEndian) {
2058 uint64_t OutputDebugInfoSize =
2059 Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
2060 for (auto &CurrentUnit : CompileUnits) {
2061 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2062 CurrentUnit->setStartOffset(OutputDebugInfoSize);
2063 if (!InputDIE) {
2064 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2065 continue;
2066 }
2067 if (CurrentUnit->getInfo(0).Keep) {
2068 // Clone the InputDIE into your Unit DIE in our compile unit since it
2069 // already has a DIE inside of it.
2070 CurrentUnit->createOutputDIE();
2071 cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
2072 11 /* Unit Header size */, 0, IsLittleEndian,
2073 CurrentUnit->getOutputUnitDIE());
2074 }
2075
2076 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2077
2078 if (!Linker.Options.NoOutput) {
2079 assert(Emitter)((Emitter) ? static_cast<void> (0) : __assert_fail ("Emitter"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2079, __PRETTY_FUNCTION__))
;
2080
2081 if (LLVM_LIKELY(!Linker.Options.Update)__builtin_expect((bool)(!Linker.Options.Update), true) ||
2082 Linker.needToTranslateStrings())
2083 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
2084
2085 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2086
2087 if (LLVM_UNLIKELY(Linker.Options.Update)__builtin_expect((bool)(Linker.Options.Update), false))
2088 continue;
2089
2090 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
2091 auto ProcessExpr = [&](StringRef Bytes,
2092 SmallVectorImpl<uint8_t> &Buffer) {
2093 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2094 DataExtractor Data(Bytes, IsLittleEndian,
2095 OrigUnit.getAddressByteSize());
2096 cloneExpression(Data,
2097 DWARFExpression(Data, OrigUnit.getAddressByteSize()),
2098 File, *CurrentUnit, Buffer);
2099 };
2100 Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
2101 }
2102 }
2103
2104 if (!Linker.Options.NoOutput) {
2105 assert(Emitter)((Emitter) ? static_cast<void> (0) : __assert_fail ("Emitter"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2105, __PRETTY_FUNCTION__))
;
2106 // Emit all the compile unit's debug information.
2107 for (auto &CurrentUnit : CompileUnits) {
2108 if (LLVM_LIKELY(!Linker.Options.Update)__builtin_expect((bool)(!Linker.Options.Update), true))
2109 Linker.generateUnitRanges(*CurrentUnit);
2110
2111 CurrentUnit->fixupForwardReferences();
2112
2113 if (!CurrentUnit->getOutputUnitDIE())
2114 continue;
2115
2116 assert(Emitter->getDebugInfoSectionSize() ==((Emitter->getDebugInfoSectionSize() == CurrentUnit->getStartOffset
()) ? static_cast<void> (0) : __assert_fail ("Emitter->getDebugInfoSectionSize() == CurrentUnit->getStartOffset()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2117, __PRETTY_FUNCTION__))
2117 CurrentUnit->getStartOffset())((Emitter->getDebugInfoSectionSize() == CurrentUnit->getStartOffset
()) ? static_cast<void> (0) : __assert_fail ("Emitter->getDebugInfoSectionSize() == CurrentUnit->getStartOffset()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2117, __PRETTY_FUNCTION__))
;
2118 Emitter->emitCompileUnitHeader(*CurrentUnit);
2119 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2120 assert(Emitter->getDebugInfoSectionSize() ==((Emitter->getDebugInfoSectionSize() == CurrentUnit->computeNextUnitOffset
()) ? static_cast<void> (0) : __assert_fail ("Emitter->getDebugInfoSectionSize() == CurrentUnit->computeNextUnitOffset()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2121, __PRETTY_FUNCTION__))
2121 CurrentUnit->computeNextUnitOffset())((Emitter->getDebugInfoSectionSize() == CurrentUnit->computeNextUnitOffset
()) ? static_cast<void> (0) : __assert_fail ("Emitter->getDebugInfoSectionSize() == CurrentUnit->computeNextUnitOffset()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2121, __PRETTY_FUNCTION__))
;
2122 }
2123 }
2124}
2125
2126void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
2127 if (Options.TheAccelTableKind != AccelTableKind::Default)
2128 return;
2129
2130 auto &DwarfObj = Dwarf.getDWARFObj();
2131
2132 if (!AtLeastOneDwarfAccelTable &&
2133 (!DwarfObj.getAppleNamesSection().Data.empty() ||
2134 !DwarfObj.getAppleTypesSection().Data.empty() ||
2135 !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2136 !DwarfObj.getAppleObjCSection().Data.empty())) {
2137 AtLeastOneAppleAccelTable = true;
2138 }
2139
2140 if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
2141 AtLeastOneDwarfAccelTable = true;
2142 }
2143}
2144
2145bool DWARFLinker::emitPaperTrailWarnings(const DwarfFile &File,
2146 OffsetsStringPool &StringPool) {
2147
2148 if (File.Warnings.empty())
2149 return false;
2150
2151 DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2152 CUDie->setOffset(11);
2153 StringRef Producer;
2154 StringRef WarningHeader;
2155
2156 switch (DwarfLinkerClientID) {
2157 case DwarfLinkerClient::Dsymutil:
2158 Producer = StringPool.internString("dsymutil");
2159 WarningHeader = "dsymutil_warning";
2160 break;
2161
2162 default:
2163 Producer = StringPool.internString("dwarfopt");
2164 WarningHeader = "dwarfopt_warning";
2165 break;
2166 }
2167
2168 StringRef FileName = StringPool.internString(File.FileName);
2169 CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2170 DIEInteger(StringPool.getStringOffset(Producer)));
2171 DIEBlock *String = new (DIEAlloc) DIEBlock();
2172 DIEBlocks.push_back(String);
2173 for (auto &C : FileName)
2174 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2175 DIEInteger(C));
2176 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2177 DIEInteger(0));
2178
2179 CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2180 for (const auto &Warning : File.Warnings) {
2181 DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2182 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2183 DIEInteger(StringPool.getStringOffset(WarningHeader)));
2184 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2185 DIEInteger(1));
2186 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2187 DIEInteger(StringPool.getStringOffset(Warning)));
2188 }
2189 unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
2190 File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
2191 DIEAbbrev Abbrev = CUDie->generateAbbrev();
2192 assignAbbrev(Abbrev);
2193 CUDie->setAbbrevNumber(Abbrev.getNumber());
2194 Size += getULEB128Size(Abbrev.getNumber());
2195 // Abbreviation ordering needed for classic compatibility.
2196 for (auto &Child : CUDie->children()) {
2197 Abbrev = Child.generateAbbrev();
2198 assignAbbrev(Abbrev);
2199 Child.setAbbrevNumber(Abbrev.getNumber());
2200 Size += getULEB128Size(Abbrev.getNumber());
2201 }
2202 CUDie->setSize(Size);
2203 TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
2204
2205 return true;
2206}
2207
2208void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2209 if (!needToTranslateStrings())
2210 TheDwarfEmitter->emitSectionContents(
2211 Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
2212 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2213 "debug_loc");
2214 TheDwarfEmitter->emitSectionContents(
2215 Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
2216 TheDwarfEmitter->emitSectionContents(
2217 Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
2218 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2219 "debug_aranges");
2220}
2221
2222void DWARFLinker::addObjectFile(DwarfFile &File) {
2223 ObjectContexts.emplace_back(LinkContext(File));
2224
2225 if (ObjectContexts.back().File.Dwarf)
2226 updateAccelKind(*ObjectContexts.back().File.Dwarf);
2227}
2228
2229bool DWARFLinker::link() {
2230 assert(Options.NoOutput || TheDwarfEmitter)((Options.NoOutput || TheDwarfEmitter) ? static_cast<void>
(0) : __assert_fail ("Options.NoOutput || TheDwarfEmitter", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2230, __PRETTY_FUNCTION__))
;
2231
2232 // A unique ID that identifies each compile unit.
2233 unsigned UnitID = 0;
2234
2235 // First populate the data structure we need for each iteration of the
2236 // parallel loop.
2237 unsigned NumObjects = ObjectContexts.size();
2238
2239 // This Dwarf string pool which is only used for uniquing. This one should
2240 // never be used for offsets as its not thread-safe or predictable.
2241 UniquingStringPool UniquingStringPool(nullptr, true);
2242
2243 // This Dwarf string pool which is used for emission. It must be used
2244 // serially as the order of calling getStringOffset matters for
2245 // reproducibility.
2246 OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
2247
2248 // ODR Contexts for the optimize.
2249 DeclContextTree ODRContexts;
2250
2251 // If we haven't decided on an accelerator table kind yet, we base ourselves
2252 // on the DWARF we have seen so far. At this point we haven't pulled in debug
2253 // information from modules yet, so it is technically possible that they
2254 // would affect the decision. However, as they're built with the same
2255 // compiler and flags, it is safe to assume that they will follow the
2256 // decision made here.
2257 if (Options.TheAccelTableKind == AccelTableKind::Default) {
2258 if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2259 Options.TheAccelTableKind = AccelTableKind::Dwarf;
2260 else
2261 Options.TheAccelTableKind = AccelTableKind::Apple;
2262 }
2263
2264 for (LinkContext &OptContext : ObjectContexts) {
2265 if (Options.Verbose) {
2266 if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
2267 outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2268 else
2269 outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
2270 }
2271
2272 if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
2273 continue;
2274
2275 if (!OptContext.File.Dwarf)
2276 continue;
2277 // Look for relocations that correspond to address map entries.
2278
2279 // there was findvalidrelocations previously ... probably we need to gather
2280 // info here
2281 if (LLVM_LIKELY(!Options.Update)__builtin_expect((bool)(!Options.Update), true) &&
2282 !OptContext.File.Addresses->hasValidRelocs()) {
2283 if (Options.Verbose)
2284 outs() << "No valid relocations found. Skipping.\n";
2285
2286 // Set "Skip" flag as a signal to other loops that we should not
2287 // process this iteration.
2288 OptContext.Skip = true;
2289 continue;
2290 }
2291
2292 // Setup access to the debug info.
2293 if (!OptContext.File.Dwarf)
2294 continue;
2295
2296 // In a first phase, just read in the debug info and load all clang modules.
2297 OptContext.CompileUnits.reserve(
2298 OptContext.File.Dwarf->getNumCompileUnits());
2299
2300 for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
2301 updateDwarfVersion(CU->getVersion());
2302 auto CUDie = CU->getUnitDIE(false);
2303 if (Options.Verbose) {
2304 outs() << "Input compilation unit:";
2305 DIDumpOptions DumpOpts;
2306 DumpOpts.ChildRecurseDepth = 0;
2307 DumpOpts.Verbose = Options.Verbose;
2308 CUDie.dump(outs(), 0, DumpOpts);
2309 }
2310 if (CUDie && !LLVM_UNLIKELY(Options.Update)__builtin_expect((bool)(Options.Update), false))
2311 registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
2312 UniquingStringPool, ODRContexts, 0, UnitID,
2313 OptContext.File.Dwarf->isLittleEndian());
2314 }
2315 }
2316
2317 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2318 if (MaxDwarfVersion == 0)
2319 MaxDwarfVersion = 3;
2320
2321 // At this point we know how much data we have emitted. We use this value to
2322 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2323 // is already emitted, without being affected by canonical die offsets set
2324 // later. This prevents undeterminism when analyze and clone execute
2325 // concurrently, as clone set the canonical DIE offset and analyze reads it.
2326 const uint64_t ModulesEndOffset =
2327 Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
2328
2329 // These variables manage the list of processed object files.
2330 // The mutex and condition variable are to ensure that this is thread safe.
2331 std::mutex ProcessedFilesMutex;
2332 std::condition_variable ProcessedFilesConditionVariable;
2333 BitVector ProcessedFiles(NumObjects, false);
2334
2335 // Analyzing the context info is particularly expensive so it is executed in
2336 // parallel with emitting the previous compile unit.
2337 auto AnalyzeLambda = [&](size_t I) {
2338 auto &Context = ObjectContexts[I];
2339
2340 if (Context.Skip || !Context.File.Dwarf)
2341 return;
2342
2343 for (const auto &CU : Context.File.Dwarf->compile_units()) {
2344 updateDwarfVersion(CU->getVersion());
2345 // The !registerModuleReference() condition effectively skips
2346 // over fully resolved skeleton units. This second pass of
2347 // registerModuleReferences doesn't do any new work, but it
2348 // will collect top-level errors, which are suppressed. Module
2349 // warnings were already displayed in the first iteration.
2350 bool Quiet = true;
2351 auto CUDie = CU->getUnitDIE(false);
2352 if (!CUDie || LLVM_UNLIKELY(Options.Update)__builtin_expect((bool)(Options.Update), false) ||
2353 !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
2354 UniquingStringPool, ODRContexts,
2355 ModulesEndOffset, UnitID, Quiet)) {
2356 Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
2357 *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2358 }
2359 }
2360
2361 // Now build the DIE parent links that we will use during the next phase.
2362 for (auto &CurrentUnit : Context.CompileUnits) {
2363 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2364 if (!CUDie)
2365 continue;
2366 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2367 *CurrentUnit, &ODRContexts.getRoot(),
2368 UniquingStringPool, ODRContexts, ModulesEndOffset,
2369 Options.ParseableSwiftInterfaces,
2370 [&](const Twine &Warning, const DWARFDie &DIE) {
2371 reportWarning(Warning, Context.File, &DIE);
2372 });
2373 }
2374 };
2375
2376 // And then the remaining work in serial again.
2377 // Note, although this loop runs in serial, it can run in parallel with
2378 // the analyzeContextInfo loop so long as we process files with indices >=
2379 // than those processed by analyzeContextInfo.
2380 auto CloneLambda = [&](size_t I) {
2381 auto &OptContext = ObjectContexts[I];
2382 if (OptContext.Skip || !OptContext.File.Dwarf)
2383 return;
2384
2385 // Then mark all the DIEs that need to be present in the generated output
2386 // and collect some information about them.
2387 // Note that this loop can not be merged with the previous one because
2388 // cross-cu references require the ParentIdx to be setup for every CU in
2389 // the object file before calling this.
2390 if (LLVM_UNLIKELY(Options.Update)__builtin_expect((bool)(Options.Update), false)) {
2391 for (auto &CurrentUnit : OptContext.CompileUnits)
2392 CurrentUnit->markEverythingAsKept();
2393 copyInvariantDebugSection(*OptContext.File.Dwarf);
2394 } else {
2395 for (auto &CurrentUnit : OptContext.CompileUnits)
2396 lookForDIEsToKeep(*OptContext.File.Addresses,
2397 OptContext.File.Addresses->getValidAddressRanges(),
2398 OptContext.CompileUnits,
2399 CurrentUnit->getOrigUnit().getUnitDIE(),
2400 OptContext.File, *CurrentUnit, 0);
2401 }
2402
2403 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2404 // array again (in the same way findValidRelocsInDebugInfo() did). We
2405 // need to reset the NextValidReloc index to the beginning.
2406 if (OptContext.File.Addresses->hasValidRelocs() ||
2407 LLVM_UNLIKELY(Options.Update)__builtin_expect((bool)(Options.Update), false)) {
2408 DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
2409 OptContext.CompileUnits, Options.Update)
2410 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
2411 OffsetsStringPool,
2412 OptContext.File.Dwarf->isLittleEndian());
2413 }
2414 if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
2415 LLVM_LIKELY(!Options.Update)__builtin_expect((bool)(!Options.Update), true))
2416 patchFrameInfoForObject(
2417 OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
2418 *OptContext.File.Dwarf,
2419 OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2420
2421 // Clean-up before starting working on the next object.
2422 cleanupAuxiliarryData(OptContext);
2423 };
2424
2425 auto EmitLambda = [&]() {
2426 // Emit everything that's global.
2427 if (!Options.NoOutput) {
2428 TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2429 TheDwarfEmitter->emitStrings(OffsetsStringPool);
2430 switch (Options.TheAccelTableKind) {
2431 case AccelTableKind::Apple:
2432 TheDwarfEmitter->emitAppleNames(AppleNames);
2433 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
2434 TheDwarfEmitter->emitAppleTypes(AppleTypes);
2435 TheDwarfEmitter->emitAppleObjc(AppleObjc);
2436 break;
2437 case AccelTableKind::Dwarf:
2438 TheDwarfEmitter->emitDebugNames(DebugNames);
2439 break;
2440 case AccelTableKind::Default:
2441 llvm_unreachable("Default should have already been resolved.")::llvm::llvm_unreachable_internal("Default should have already been resolved."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/DWARFLinker/DWARFLinker.cpp"
, 2441)
;
2442 break;
2443 }
2444 }
2445 };
2446
2447 auto AnalyzeAll = [&]() {
2448 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2449 AnalyzeLambda(I);
2450
2451 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2452 ProcessedFiles.set(I);
2453 ProcessedFilesConditionVariable.notify_one();
2454 }
2455 };
2456
2457 auto CloneAll = [&]() {
2458 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2459 {
2460 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2461 if (!ProcessedFiles[I]) {
2462 ProcessedFilesConditionVariable.wait(
2463 LockGuard, [&]() { return ProcessedFiles[I]; });
2464 }
2465 }
2466
2467 CloneLambda(I);
2468 }
2469 EmitLambda();
2470 };
2471
2472 // To limit memory usage in the single threaded case, analyze and clone are
2473 // run sequentially so the OptContext is freed after processing each object
2474 // in endDebugObject.
2475 if (Options.Threads == 1) {
2476 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2477 AnalyzeLambda(I);
2478 CloneLambda(I);
2479 }
2480 EmitLambda();
2481 } else {
2482 ThreadPool Pool(hardware_concurrency(2));
2483 Pool.async(AnalyzeAll);
2484 Pool.async(CloneAll);
2485 Pool.wait();
2486 }
2487
2488 return true;
2489}
2490
2491} // namespace llvm