LLVM 24.0.0git
DWARFLinker.h
Go to the documentation of this file.
1//===- DWARFLinker.h --------------------------------------------*- C++ -*-===//
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#ifndef LLVM_DWARFLINKER_CLASSIC_DWARFLINKER_H
10#define LLVM_DWARFLINKER_CLASSIC_DWARFLINKER_H
11
13#include "llvm/ADT/DenseMap.h"
26#include <map>
27
28namespace llvm {
29class DWARFExpression;
30class DWARFUnit;
31class DataExtractor;
32template <typename T> class SmallVectorImpl;
33
34namespace dwarf_linker {
35namespace classic {
36class DeclContextTree;
37
40
41/// DwarfEmitter presents interface to generate all debug info tables.
43public:
44 virtual ~DwarfEmitter() = default;
45
46 /// Emit section named SecName with data SecData.
47 virtual void emitSectionContents(StringRef SecData,
48 DebugSectionKind SecKind) = 0;
49
50 /// Emit the abbreviation table \p Abbrevs to the .debug_abbrev section.
51 virtual void
52 emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
53 unsigned DwarfVersion) = 0;
54
55 /// Emit the string table described by \p Pool into .debug_str table.
56 virtual void emitStrings(const NonRelocatableStringpool &Pool) = 0;
57
58 /// Emit the debug string offset table described by \p StringOffsets into the
59 /// .debug_str_offsets table.
60 virtual void emitStringOffsets(const SmallVector<uint64_t> &StringOffsets,
61 uint16_t TargetDWARFVersion) = 0;
62
63 /// Emit the string table described by \p Pool into .debug_line_str table.
64 virtual void emitLineStrings(const NonRelocatableStringpool &Pool) = 0;
65
66 /// Emit DWARF debug names.
68
69 /// Emit Apple namespaces accelerator table.
70 virtual void
72
73 /// Emit Apple names accelerator table.
74 virtual void
76
77 /// Emit Apple Objective-C accelerator table.
78 virtual void
80
81 /// Emit Apple type accelerator table.
82 virtual void
84
85 /// Emit debug ranges (.debug_ranges, .debug_rnglists) header.
87
88 /// Emit debug ranges (.debug_ranges, .debug_rnglists) fragment.
90 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
91 PatchLocation Patch, DebugDieValuePool &AddrPool) = 0;
92
93 /// Emit debug ranges (.debug_ranges, .debug_rnglists) footer.
95 MCSymbol *EndLabel) = 0;
96
97 /// Emit debug locations (.debug_loc, .debug_loclists) header.
99
100 /// Emit debug locations (.debug_loc, .debug_loclists) fragment.
102 const CompileUnit &Unit,
103 const DWARFLocationExpressionsVector &LinkedLocationExpression,
104 PatchLocation Patch, DebugDieValuePool &AddrPool) = 0;
105
106 /// Emit debug locations (.debug_loc, .debug_loclists) footer.
107 virtual void emitDwarfDebugLocListFooter(const CompileUnit &Unit,
108 MCSymbol *EndLabel) = 0;
109
110 /// Emit .debug_addr header.
112
113 /// Emit the addresses described by \p Addrs into the .debug_addr section.
115 uint8_t AddrSize) = 0;
116
117 /// Emit .debug_addr footer.
118 virtual void emitDwarfDebugAddrsFooter(const CompileUnit &Unit,
119 MCSymbol *EndLabel) = 0;
120
121 /// Emit .debug_aranges entries for \p Unit
122 virtual void
124 const AddressRanges &LinkedRanges) = 0;
125
126 /// Emit specified \p LineTable into .debug_line table.
127 /// The optional parameter RowOffsets, if provided, will be populated with the
128 /// offsets of each line table row in the output .debug_line section.
129 virtual void
131 const CompileUnit &Unit, OffsetsStringPool &DebugStrPool,
132 OffsetsStringPool &DebugLineStrPool,
133 std::vector<uint64_t> *RowOffsets = nullptr) = 0;
134
135 /// Emit the .debug_pubnames contribution for \p Unit.
136 virtual void emitPubNamesForUnit(const CompileUnit &Unit) = 0;
137
138 /// Emit the .debug_pubtypes contribution for \p Unit.
139 virtual void emitPubTypesForUnit(const CompileUnit &Unit) = 0;
140
141 /// Emit a CIE.
142 virtual void emitCIE(StringRef CIEBytes) = 0;
143
144 /// Emit an FDE with data \p Bytes.
145 virtual void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint64_t Address,
146 StringRef Bytes) = 0;
147
148 /// Emit the compilation unit header for \p Unit in the
149 /// .debug_info section.
150 ///
151 /// As a side effect, this also switches the current Dwarf version
152 /// of the MC layer to the one of U.getOrigUnit().
154 unsigned DwarfVersion) = 0;
155
156 /// Recursively emit the DIE tree rooted at \p Die.
157 virtual void emitDIE(DIE &Die) = 0;
158
159 /// Emit all available macro tables(DWARFv4 and DWARFv5).
160 /// Use \p UnitMacroMap to get compilation unit by macro table offset.
161 /// Side effects: Fill \p StringPool with macro strings, update
162 /// DW_AT_macro_info, DW_AT_macros attributes for corresponding compile
163 /// units.
164 virtual void emitMacroTables(DWARFContext *Context,
165 const Offset2UnitMap &UnitMacroMap,
167
168 /// Returns size of generated .debug_line section.
169 virtual uint64_t getLineSectionSize() const = 0;
170
171 /// Returns size of generated .debug_frame section.
172 virtual uint64_t getFrameSectionSize() const = 0;
173
174 /// Returns size of generated .debug_ranges section.
175 virtual uint64_t getRangesSectionSize() const = 0;
176
177 /// Returns size of generated .debug_rnglists section.
178 virtual uint64_t getRngListsSectionSize() const = 0;
179
180 /// Returns size of generated .debug_info section.
182
183 /// Returns size of generated .debug_macinfo section.
185
186 /// Returns size of generated .debug_macro section.
188
189 /// Returns size of generated .debug_loclists section.
190 virtual uint64_t getLocListsSectionSize() const = 0;
191
192 /// Returns size of generated .debug_addr section.
194
195 /// Dump the file to the disk.
196 virtual void finish() = 0;
197};
198
199class DwarfStreamer;
200using UnitListTy = std::vector<std::unique_ptr<CompileUnit>>;
201
202/// The core of the Dwarf linking logic.
203///
204/// The generation of the dwarf information from the object files will be
205/// driven by the selection of 'root DIEs', which are DIEs that
206/// describe variables or functions that resolves to the corresponding
207/// code section(and thus have entries in the Addresses map). All the debug
208/// information that will be generated(the DIEs, but also the line
209/// tables, ranges, ...) is derived from that set of root DIEs.
210///
211/// The root DIEs are identified because they contain relocations that
212/// points to code section(the low_pc for a function, the location for
213/// a variable). These relocations are called ValidRelocs in the
214/// AddressesInfo and are gathered as a very first step when we start
215/// processing a object file.
217public:
218 DWARFLinker(MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler,
219 std::function<StringRef(StringRef)> StringsTranslator)
220 : StringsTranslator(StringsTranslator), ErrorHandler(ErrorHandler),
221 WarningHandler(WarningHandler) {}
222
223 static std::unique_ptr<DWARFLinker> createLinker(
224 MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler,
225 std::function<StringRef(StringRef)> StringsTranslator = nullptr) {
226 return std::make_unique<DWARFLinker>(ErrorHandler, WarningHandler,
227 StringsTranslator);
228 }
229
230 /// Set output DWARF emitter.
232 TheDwarfEmitter = Emitter;
233 }
234
235 /// Add object file to be linked. Pre-load compile unit die. Call
236 /// \p OnCUDieLoaded for each compile unit die. If specified \p File
237 /// has reference to the Clang module then such module would be
238 /// pre-loaded by \p Loader for !Update case.
239 ///
240 /// \pre NoODR, Update options should be set before call to addObjectFile.
241 void addObjectFile(
242 DWARFFile &File, ObjFileLoaderTy Loader = nullptr,
243 CompileUnitHandlerTy OnCUDieLoaded = [](const DWARFUnit &) {}) override;
244
245 /// Link debug info for added objFiles. Object files are linked all together.
246 Error link() override;
247
248 /// A number of methods setting various linking options:
249
250 /// Allows to generate log of linking process to the standard output.
251 void setVerbosity(bool Verbose) override { Options.Verbose = Verbose; }
252
253 /// Print statistics to standard output.
254 void setStatistics(bool Statistics) override {
255 Options.Statistics = Statistics;
256 }
257
258 /// Verify the input DWARF.
259 void setVerifyInputDWARF(bool Verify) override {
260 Options.VerifyInputDWARF = Verify;
261 }
262
263 /// Do not unique types according to ODR.
264 void setNoODR(bool NoODR) override { Options.NoODR = NoODR; }
265
266 /// Update index tables only(do not modify rest of DWARF).
267 void setUpdateIndexTablesOnly(bool Update) override {
268 Options.Update = Update;
269 }
270
271 /// Set whether to keep the enclosing function for a static variable.
272 void setKeepFunctionForStatic(bool KeepFunctionForStatic) override {
273 Options.KeepFunctionForStatic = KeepFunctionForStatic;
274 }
275
276 /// Use specified number of threads for parallel files linking.
277 void setNumThreads(unsigned NumThreads) override {
278 Options.Threads = NumThreads;
279 }
280
281 /// The classic linker does not use a shared thread pool.
282 void setThreadPool(ThreadPoolInterface *Pool) override {}
283
284 /// Add kind of accelerator tables to be generated.
285 void addAccelTableKind(AccelTableKind Kind) override {
286 assert(!llvm::is_contained(Options.AccelTables, Kind));
287 Options.AccelTables.emplace_back(Kind);
288 }
289
290 /// Set prepend path for clang modules.
291 void setPrependPath(StringRef Ppath) override { Options.PrependPath = Ppath; }
292
293 /// Set estimated objects files amount, for preliminary data allocation.
294 void setEstimatedObjfilesAmount(unsigned ObjFilesNum) override {
295 ObjectContexts.reserve(ObjFilesNum);
296 }
297
298 /// Set verification handler which would be used to report verification
299 /// errors.
300 void
302 Options.InputVerificationHandler = Handler;
303 }
304
305 /// Set map for Swift interfaces.
307 Options.ParseableSwiftInterfaces = Map;
308 }
309
310 /// Set prefix map for objects.
312 Options.ObjectPrefixMap = Map;
313 }
314
315 /// Set target DWARF version.
316 Error setTargetDWARFVersion(uint16_t TargetDWARFVersion) override {
317 if ((TargetDWARFVersion < 1) || (TargetDWARFVersion > 5))
318 return createStringError(std::errc::invalid_argument,
319 "unsupported DWARF version: %d",
320 TargetDWARFVersion);
321
322 Options.TargetDWARFVersion = TargetDWARFVersion;
323 return Error::success();
324 }
325
326private:
327 /// Flags passed to DwarfLinker::lookForDIEsToKeep
328 enum TraversalFlags {
329 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
330 TF_InFunctionScope = 1 << 1, ///< Current scope is a function scope.
331 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
332 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
333 TF_ODR = 1 << 4, ///< Use the ODR while keeping dependents.
334 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
335 };
336
337 /// The distinct types of work performed by the work loop.
338 enum class WorklistItemType {
339 /// Given a DIE, look for DIEs to be kept.
340 LookForDIEsToKeep,
341 /// Given a DIE, look for children of this DIE to be kept.
342 LookForChildDIEsToKeep,
343 /// Given a DIE, look for DIEs referencing this DIE to be kept.
344 LookForRefDIEsToKeep,
345 /// Given a DIE, look for parent DIEs to be kept.
346 LookForParentDIEsToKeep,
347 /// Given a DIE, update its incompleteness based on whether its children are
348 /// incomplete.
349 UpdateChildIncompleteness,
350 /// Given a DIE, update its incompleteness based on whether the DIEs it
351 /// references are incomplete.
352 UpdateRefIncompleteness,
353 /// Given a DIE, mark it as ODR Canonical if applicable.
354 MarkODRCanonicalDie,
355 };
356
357 /// This class represents an item in the work list. The type defines what kind
358 /// of work needs to be performed when processing the current item. The flags
359 /// and info fields are optional based on the type.
360 struct WorklistItem {
361 DWARFDie Die;
362 WorklistItemType Type;
364 unsigned Flags;
365 union {
366 const unsigned AncestorIdx;
367 CompileUnit::DIEInfo *OtherInfo;
368 };
369
370 WorklistItem(DWARFDie Die, CompileUnit &CU, unsigned Flags,
371 WorklistItemType T = WorklistItemType::LookForDIEsToKeep)
372 : Die(Die), Type(T), CU(CU), Flags(Flags), AncestorIdx(0) {}
373
374 WorklistItem(DWARFDie Die, CompileUnit &CU, WorklistItemType T,
375 CompileUnit::DIEInfo *OtherInfo = nullptr)
376 : Die(Die), Type(T), CU(CU), Flags(0), OtherInfo(OtherInfo) {}
377
378 WorklistItem(unsigned AncestorIdx, CompileUnit &CU, unsigned Flags)
379 : Type(WorklistItemType::LookForParentDIEsToKeep), CU(CU), Flags(Flags),
380 AncestorIdx(AncestorIdx) {}
381 };
382
383 /// Verify the given DWARF file.
384 void verifyInput(const DWARFFile &File);
385
386 /// returns true if we need to translate strings.
387 bool needToTranslateStrings() { return StringsTranslator != nullptr; }
388
389 void reportWarning(const Twine &Warning, const DWARFFile &File,
390 const DWARFDie *DIE = nullptr) const {
391 if (WarningHandler != nullptr)
392 WarningHandler(Warning, File.FileName, DIE);
393 }
394
395 void reportError(const Twine &Warning, const DWARFFile &File,
396 const DWARFDie *DIE = nullptr) const {
397 if (ErrorHandler != nullptr)
398 ErrorHandler(Warning, File.FileName, DIE);
399 }
400
401 void copyInvariantDebugSection(DWARFContext &Dwarf);
402
403 /// Keep information for referenced clang module: already loaded DWARF info
404 /// of the clang module and a CompileUnit of the module.
405 struct RefModuleUnit {
406 RefModuleUnit(DWARFFile &File, std::unique_ptr<CompileUnit> Unit)
407 : File(File), Unit(std::move(Unit)) {}
408 RefModuleUnit(RefModuleUnit &&Other)
409 : File(Other.File), Unit(std::move(Other.Unit)) {}
410 RefModuleUnit(const RefModuleUnit &) = delete;
411
412 DWARFFile &File;
413 std::unique_ptr<CompileUnit> Unit;
414 };
415 using ModuleUnitListTy = std::vector<RefModuleUnit>;
416
417 /// Keeps track of data associated with one object during linking.
418 struct LinkContext {
419 DWARFFile &File;
420 UnitListTy CompileUnits;
421 ModuleUnitListTy ModuleUnits;
422 bool Skip = false;
423
424 LinkContext(DWARFFile &File) : File(File) {}
425
426 /// Clear part of the context that's no longer needed when we're done with
427 /// the debug object.
428 void clear() {
429 CompileUnits.clear();
430 ModuleUnits.clear();
431 File.unload();
432 }
433 };
434
435 /// Called before emitting object data
436 void cleanupAuxiliarryData(LinkContext &Context);
437
438 /// Look at the parent of the given DIE and decide whether they should be
439 /// kept.
440 void lookForParentDIEsToKeep(unsigned AncestorIdx, CompileUnit &CU,
441 unsigned Flags,
442 SmallVectorImpl<WorklistItem> &Worklist);
443
444 /// Look at the children of the given DIE and decide whether they should be
445 /// kept.
446 void lookForChildDIEsToKeep(const DWARFDie &Die, CompileUnit &CU,
447 unsigned Flags,
448 SmallVectorImpl<WorklistItem> &Worklist);
449
450 /// Look at DIEs referenced by the given DIE and decide whether they should be
451 /// kept. All DIEs referenced though attributes should be kept.
452 void lookForRefDIEsToKeep(const DWARFDie &Die, CompileUnit &CU,
453 unsigned Flags, const UnitListTy &Units,
454 const DWARFFile &File,
455 SmallVectorImpl<WorklistItem> &Worklist);
456
457 /// Mark context corresponding to the specified \p Die as having canonical
458 /// die, if applicable.
459 void markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU);
460
461 /// \defgroup FindRootDIEs Find DIEs corresponding to Address map entries.
462 ///
463 /// @{
464 /// Recursively walk the \p DIE tree and look for DIEs to
465 /// keep. Store that information in \p CU's DIEInfo.
466 ///
467 /// The return value indicates whether the DIE is incomplete.
468 void lookForDIEsToKeep(AddressesMap &RelocMgr, const UnitListTy &Units,
469 const DWARFDie &DIE, const DWARFFile &File,
470 CompileUnit &CU, unsigned Flags);
471
472 /// Check whether specified \p CUDie is a Clang module reference.
473 /// if \p Quiet is false then display error messages.
474 /// \return first == true if CUDie is a Clang module reference.
475 /// second == true if module is already loaded.
476 std::pair<bool, bool> isClangModuleRef(const DWARFDie &CUDie,
477 std::string &PCMFile,
478 LinkContext &Context, unsigned Indent,
479 bool Quiet);
480
481 /// If this compile unit is really a skeleton CU that points to a
482 /// clang module, register it in ClangModules and return true.
483 ///
484 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
485 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
486 /// hash.
487 bool registerModuleReference(const DWARFDie &CUDie, LinkContext &Context,
488 ObjFileLoaderTy Loader,
489 CompileUnitHandlerTy OnCUDieLoaded,
490 unsigned Indent = 0);
491
492 /// Recursively add the debug info in this clang module .pcm
493 /// file (and all the modules imported by it in a bottom-up fashion)
494 /// to ModuleUnits.
495 Error loadClangModule(ObjFileLoaderTy Loader, const DWARFDie &CUDie,
496 const std::string &PCMFile, LinkContext &Context,
497 CompileUnitHandlerTy OnCUDieLoaded,
498 unsigned Indent = 0);
499
500 /// Clone specified Clang module unit \p Unit.
501 Error cloneModuleUnit(LinkContext &Context, RefModuleUnit &Unit,
502 DeclContextTree &ODRContexts,
503 OffsetsStringPool &DebugStrPool,
504 OffsetsStringPool &DebugLineStrPool,
505 DebugDieValuePool &StringOffsetPool,
506 unsigned Indent = 0);
507
508 unsigned shouldKeepDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
509 const DWARFFile &File, CompileUnit &Unit,
510 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
511
512 /// This function checks whether variable has DWARF expression containing
513 /// operation referencing live address(f.e. DW_OP_addr, DW_OP_addrx...).
514 /// \returns first is true if the expression has an operation referencing an
515 /// address.
516 /// second is the relocation adjustment value if the live address is
517 /// referenced.
518 std::pair<bool, std::optional<int64_t>>
519 getVariableRelocAdjustment(AddressesMap &RelocMgr, const DWARFDie &DIE);
520
521 /// Check if a variable describing DIE should be kept.
522 /// \returns updated TraversalFlags.
523 unsigned shouldKeepVariableDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
524 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
525
526 unsigned shouldKeepSubprogramDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
527 const DWARFFile &File, CompileUnit &Unit,
528 CompileUnit::DIEInfo &MyInfo,
529 unsigned Flags);
530
531 /// Resolve the DIE attribute reference that has been extracted in \p
532 /// RefValue. The resulting DIE might be in another CompileUnit which is
533 /// stored into \p ReferencedCU. \returns null if resolving fails for any
534 /// reason.
535 DWARFDie resolveDIEReference(const DWARFFile &File, const UnitListTy &Units,
536 const DWARFFormValue &RefValue,
537 const DWARFDie &DIE, CompileUnit *&RefCU);
538
539 /// @}
540
541 /// \defgroup Methods used to link the debug information
542 ///
543 /// @{
544
545 struct DWARFLinkerOptions;
546
547 class DIECloner {
548 DWARFLinker &Linker;
549 DwarfEmitter *Emitter;
550 DWARFFile &ObjFile;
551 OffsetsStringPool &DebugStrPool;
552 OffsetsStringPool &DebugLineStrPool;
553 DebugDieValuePool &StringOffsetPool;
554 DebugDieValuePool AddrPool;
555
556 RelocationFixups RelocFixups;
557
558 /// Allocator used for all the DIEValue objects.
559 BumpPtrAllocator &DIEAlloc;
560
561 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
562
563 /// Keeps mapping from offset of the macro table to corresponding
564 /// compile unit.
565 Offset2UnitMap UnitMacroMap;
566
567 bool Update;
568
569 public:
570 DIECloner(DWARFLinker &Linker, DwarfEmitter *Emitter, DWARFFile &ObjFile,
571 BumpPtrAllocator &DIEAlloc,
572 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
573 bool Update, OffsetsStringPool &DebugStrPool,
574 OffsetsStringPool &DebugLineStrPool,
575 DebugDieValuePool &StringOffsetPool)
576 : Linker(Linker), Emitter(Emitter), ObjFile(ObjFile),
577 DebugStrPool(DebugStrPool), DebugLineStrPool(DebugLineStrPool),
578 StringOffsetPool(StringOffsetPool), DIEAlloc(DIEAlloc),
579 CompileUnits(CompileUnits), Update(Update) {}
580
581 /// Recursively clone \p InputDIE into an tree of DIE objects
582 /// where useless (as decided by lookForDIEsToKeep()) bits have been
583 /// stripped out and addresses have been rewritten according to the
584 /// address map.
585 ///
586 /// \param OutOffset is the offset the cloned DIE in the output
587 /// compile unit.
588 /// \param PCOffset (while cloning a function scope) is the offset
589 /// applied to the entry point of the function to get the linked address.
590 /// \param Die the output DIE to use, pass NULL to create one.
591 /// \returns the root of the cloned tree or null if nothing was selected.
592 LLVM_ABI DIE *cloneDIE(const DWARFDie &InputDIE, const DWARFFile &File,
593 CompileUnit &U, int64_t PCOffset, uint32_t OutOffset,
594 unsigned Flags, bool IsLittleEndian,
595 DIE *Die = nullptr);
596
597 /// Construct the output DIE tree by cloning the DIEs we
598 /// chose to keep above. If there are no valid relocs, then there's
599 /// nothing to clone/emit.
600 LLVM_ABI Expected<uint64_t> cloneAllCompileUnits(DWARFContext &DwarfContext,
601 const DWARFFile &File,
602 bool IsLittleEndian);
603
604 /// Emit the .debug_addr section for the \p Unit.
605 LLVM_ABI Error emitDebugAddrSection(CompileUnit &Unit,
606 const uint16_t DwarfVersion);
607
608 using ExpressionHandlerRef = function_ref<void(
609 SmallVectorImpl<uint8_t> &, SmallVectorImpl<uint8_t> &,
610 int64_t AddrRelocAdjustment)>;
611
612 /// Compute and emit debug locations (.debug_loc, .debug_loclists)
613 /// for \p Unit, patch the attributes referencing it.
614 LLVM_ABI Error generateUnitLocations(CompileUnit &Unit,
615 const DWARFFile &File,
616 ExpressionHandlerRef ExprHandler);
617
618 private:
619 using AttributeSpec = DWARFAbbreviationDeclaration::AttributeSpec;
620
621 /// Information gathered and exchanged between the various
622 /// clone*Attributes helpers about the attributes of a particular DIE.
623 struct AttributesInfo {
624 /// Names.
625 DwarfStringPoolEntryRef Name, MangledName, NameWithoutTemplate;
626
627 /// Offset to apply to PC addresses inside a function.
628 int64_t PCOffset = 0;
629
630 /// Does the DIE have a low_pc attribute?
631 bool HasLowPc = false;
632
633 /// Does the DIE have a ranges attribute?
634 bool HasRanges = false;
635
636 /// Is this DIE only a declaration?
637 bool IsDeclaration = false;
638
639 /// Is there a DW_AT_str_offsets_base in the CU?
640 bool AttrStrOffsetBaseSeen = false;
641
642 /// Is there a DW_AT_APPLE_origin in the CU?
643 bool HasAppleOrigin = false;
644
645 RelocationFixups::AttributeSource Source;
646
647 AttributesInfo() = default;
648 };
649
650 /// Helper for cloneDIE.
651 unsigned cloneAttribute(DIE &Die, const DWARFDie &InputDIE,
652 const DWARFFile &File, CompileUnit &U,
653 const DWARFFormValue &Val,
654 const AttributeSpec AttrSpec, unsigned AttrSize,
655 AttributesInfo &AttrInfo, bool IsLittleEndian);
656
657 /// Clone a string attribute described by \p AttrSpec and add
658 /// it to \p Die.
659 /// \returns the size of the new attribute.
660 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
661 const DWARFFormValue &Val, const DWARFUnit &U,
662 AttributesInfo &Info);
663
664 /// Clone an attribute referencing another DIE and add
665 /// it to \p Die.
666 /// \returns the size of the new attribute.
667 unsigned cloneDieReferenceAttribute(DIE &Die, const DWARFDie &InputDIE,
668 AttributeSpec AttrSpec,
669 unsigned AttrSize,
670 const DWARFFormValue &Val,
671 const DWARFFile &File,
672 CompileUnit &Unit);
673
674 /// Clone a DWARF expression that may be referencing another DIE.
675 /// \p Cloned, if set, receives where its operations were cloned to in
676 /// \p OutputBuffer. With \p KeepAddrIndices, DW_OP_addrx and DW_OP_constx
677 /// index the output .debug_addr, whose entries carry their relocations.
678 void cloneExpression(DataExtractor &Data, DWARFExpression Expression,
679 const DWARFFile &File, CompileUnit &Unit,
680 SmallVectorImpl<uint8_t> &OutputBuffer,
681 int64_t AddrRelocAdjustment, bool IsLittleEndian,
682 RelocationFixups::ClonedExpression *Cloned = nullptr,
683 bool KeepAddrIndices = false);
684
685 /// Clone an attribute referencing another DIE and add
686 /// it to \p Die.
687 /// \returns the size of the new attribute.
688 unsigned cloneBlockAttribute(DIE &Die, const DWARFDie &InputDIE,
689 const DWARFFile &File, CompileUnit &Unit,
690 AttributeSpec AttrSpec,
691 const DWARFFormValue &Val,
692 AttributesInfo &Info, bool IsLittleEndian);
693
694 /// Clone an attribute referencing another DIE and add
695 /// it to \p Die.
696 /// \returns the size of the new attribute.
697 unsigned cloneAddressAttribute(DIE &Die, const DWARFDie &InputDIE,
698 AttributeSpec AttrSpec, unsigned AttrSize,
699 const DWARFFormValue &Val,
700 const CompileUnit &Unit,
701 AttributesInfo &Info);
702
703 /// Clone a scalar attribute and add it to \p Die.
704 /// \returns the size of the new attribute.
705 unsigned cloneScalarAttribute(DIE &Die, const DWARFDie &InputDIE,
706 const DWARFFile &File, CompileUnit &U,
707 AttributeSpec AttrSpec,
708 const DWARFFormValue &Val, unsigned AttrSize,
709 AttributesInfo &Info);
710
711 /// Get the potential name and mangled name for the entity
712 /// described by \p Die and store them in \Info if they are not
713 /// already there.
714 /// \returns is a name was found.
715 bool getDIENames(const DWARFDie &Die, AttributesInfo &Info,
716 OffsetsStringPool &StringPool, const DWARFFile &File,
717 CompileUnit &Unit, bool StripTemplate = false);
718
719 llvm::StringRef getCanonicalDIEName(DWARFDie Die, const DWARFFile &File,
720 CompileUnit *Unit);
721
722 /// Helper for cloneDIE.
723 void addObjCAccelerator(CompileUnit &Unit, const DIE *Die,
724 DwarfStringPoolEntryRef Name,
725 OffsetsStringPool &StringPool, bool SkipPubSection);
726
727 void rememberUnitForMacroOffset(CompileUnit &Unit);
728
729 /// Clone and emit the line table for the specified \p Unit.
730 /// Translate directories and file names if necessary.
731 /// Relocate address ranges.
732 Error generateLineTableForUnit(CompileUnit &Unit);
733 };
734
735 /// Assign an abbreviation number to \p Abbrev
736 void assignAbbrev(DIEAbbrev &Abbrev);
737
738 /// Compute and emit debug ranges(.debug_aranges, .debug_ranges,
739 /// .debug_rnglists) for \p Unit, patch the attributes referencing it.
740 Error generateUnitRanges(CompileUnit &Unit, const DWARFFile &File,
741 DebugDieValuePool &AddrPool) const;
742
743 /// Emit the accelerator entries for \p Unit.
744 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
745
746 /// Patch the frame info for an object file and emit it.
747 void patchFrameInfoForObject(LinkContext &Context);
748
749 /// FoldingSet that uniques the abbreviations.
750 FoldingSet<DIEAbbrev> AbbreviationsSet;
751
752 /// Storage for the unique Abbreviations.
753 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot be
754 /// changed to a vector of unique_ptrs.
755 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
756
757 /// DIELoc objects that need to be destructed (but not freed!).
758 std::vector<DIELoc *> DIELocs;
759
760 /// DIEBlock objects that need to be destructed (but not freed!).
761 std::vector<DIEBlock *> DIEBlocks;
762
763 /// Allocator used for all the DIEValue objects.
764 BumpPtrAllocator DIEAlloc;
765 /// @}
766
767 DwarfEmitter *TheDwarfEmitter = nullptr;
768 std::vector<LinkContext> ObjectContexts;
769
770 /// The CIEs that have been emitted in the output section. The actual CIE
771 /// data serves a the key to this StringMap, this takes care of comparing the
772 /// semantics of CIEs defined in different object files.
773 StringMap<uint32_t> EmittedCIEs;
774
775 /// Offset of the last CIE that has been emitted in the output
776 /// .debug_frame section.
777 uint32_t LastCIEOffset = 0;
778
779 /// Apple accelerator tables.
780 DWARF5AccelTable DebugNames;
781 AccelTable<AppleAccelTableStaticOffsetData> AppleNames;
782 AccelTable<AppleAccelTableStaticOffsetData> AppleNamespaces;
783 AccelTable<AppleAccelTableStaticOffsetData> AppleObjc;
784 AccelTable<AppleAccelTableStaticTypeData> AppleTypes;
785
786 /// Mapping the PCM filename to the DwoId.
787 StringMap<uint64_t> ClangModules;
788
789 std::function<StringRef(StringRef)> StringsTranslator = nullptr;
790
791 /// A unique ID that identifies each compile unit.
792 unsigned UniqueUnitID = 0;
793
794 // error handler
796
797 // warning handler
798 MessageHandlerTy WarningHandler = nullptr;
799
800 /// linking options
801 struct DWARFLinkerOptions {
802 /// DWARF version for the output.
803 uint16_t TargetDWARFVersion = 0;
804
805 /// Generate processing log to the standard output.
806 bool Verbose = false;
807
808 /// Print statistics.
809 bool Statistics = false;
810
811 /// Verify the input DWARF.
812 bool VerifyInputDWARF = false;
813
814 /// Do not unique types according to ODR
815 bool NoODR = false;
816
817 /// Update
818 bool Update = false;
819
820 /// Whether we want a static variable to force us to keep its enclosing
821 /// function.
822 bool KeepFunctionForStatic = false;
823
824 /// Number of threads.
825 unsigned Threads = 1;
826
827 /// The accelerator table kinds
828 SmallVector<AccelTableKind, 1> AccelTables;
829
830 /// Prepend path for the clang modules.
831 std::string PrependPath;
832
833 // input verification handler
834 InputVerificationHandlerTy InputVerificationHandler = nullptr;
835
836 /// A list of all .swiftinterface files referenced by the debug
837 /// info, mapping Module name to path on disk. The entries need to
838 /// be uniqued and sorted and there are only few entries expected
839 /// per compile unit, which is why this is a std::map.
840 /// this is dsymutil specific fag.
841 SwiftInterfacesMapTy *ParseableSwiftInterfaces = nullptr;
842
843 /// A list of remappings to apply to file paths.
844 ObjectPrefixMapTy *ObjectPrefixMap = nullptr;
845 } Options;
846};
847
848} // end of namespace classic
849} // end of namespace dwarf_linker
850} // end of namespace llvm
851
852#endif // LLVM_DWARFLINKER_CLASSIC_DWARFLINKER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file contains support for writing accelerator tables.
static Error reportError(StringRef Message)
#define LLVM_ABI
Definition Compiler.h:211
dxil container DXContainer Global Emitter
This file defines the DenseMap class.
static cl::opt< AccelTableKind > AccelTables("accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), cl::values(clEnumValN(AccelTableKind::Default, "Default", "Default for platform"), clEnumValN(AccelTableKind::None, "Disable", "Disabled."), clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), cl::init(AccelTableKind::Default))
static fatal_error_handler_t ErrorHandler
static LVOptions Options
Definition LVOptions.cpp:25
#define T
ppc ctr loops PowerPC CTR Loops Verify
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition AccelTable.h:203
The AddressRanges class helps normalize address range collections.
A structured debug information entry.
Definition DIE.h:835
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
A string table that doesn't need relocations.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This defines the abstract base interface for a ThreadPool allowing asynchronous parallel execution on...
Definition ThreadPool.h:51
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:27
The base interface for DWARFLinker implementations.
std::map< std::string, std::string > ObjectPrefixMapTy
std::function< void( const Twine &Warning, StringRef Context, const DWARFDie *DIE)> MessageHandlerTy
AccelTableKind
The kind of accelerator tables to be emitted.
std::map< std::string, std::string > SwiftInterfacesMapTy
std::function< void(const DWARFFile &File, llvm::StringRef Output)> InputVerificationHandlerTy
This class stores values sequentually and assigns index to the each value.
Stores all information relating to a compile unit, be it in its original instance in the object file ...
void setStatistics(bool Statistics) override
Print statistics to standard output.
void setInputVerificationHandler(InputVerificationHandlerTy Handler) override
Set verification handler which would be used to report verification errors.
void setSwiftInterfacesMap(SwiftInterfacesMapTy *Map) override
Set map for Swift interfaces.
void setNumThreads(unsigned NumThreads) override
Use specified number of threads for parallel files linking.
void setObjectPrefixMap(ObjectPrefixMapTy *Map) override
Set prefix map for objects.
void setKeepFunctionForStatic(bool KeepFunctionForStatic) override
Set whether to keep the enclosing function for a static variable.
DWARFLinker(MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler, std::function< StringRef(StringRef)> StringsTranslator)
void setVerifyInputDWARF(bool Verify) override
Verify the input DWARF.
void addAccelTableKind(AccelTableKind Kind) override
Add kind of accelerator tables to be generated.
static std::unique_ptr< DWARFLinker > createLinker(MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler, std::function< StringRef(StringRef)> StringsTranslator=nullptr)
void setNoODR(bool NoODR) override
Do not unique types according to ODR.
void setPrependPath(StringRef Ppath) override
Set prepend path for clang modules.
void setThreadPool(ThreadPoolInterface *Pool) override
The classic linker does not use a shared thread pool.
Error setTargetDWARFVersion(uint16_t TargetDWARFVersion) override
Set target DWARF version.
void setOutputDWARFEmitter(DwarfEmitter *Emitter)
Set output DWARF emitter.
void setUpdateIndexTablesOnly(bool Update) override
Update index tables only(do not modify rest of DWARF).
void setEstimatedObjfilesAmount(unsigned ObjFilesNum) override
Set estimated objects files amount, for preliminary data allocation.
void setVerbosity(bool Verbose) override
A number of methods setting various linking options:
This class gives a tree-like API to the DenseMap that stores the DeclContext objects.
DwarfEmitter presents interface to generate all debug info tables.
Definition DWARFLinker.h:42
virtual void emitDwarfDebugAddrs(const SmallVector< uint64_t > &Addrs, uint8_t AddrSize)=0
Emit the addresses described by Addrs into the .debug_addr section.
virtual uint64_t getDebugAddrSectionSize() const =0
Returns size of generated .debug_addr section.
virtual void emitPubTypesForUnit(const CompileUnit &Unit)=0
Emit the .debug_pubtypes contribution for Unit.
virtual void emitSectionContents(StringRef SecData, DebugSectionKind SecKind)=0
Emit section named SecName with data SecData.
virtual Error emitDwarfDebugRangeListFragment(const CompileUnit &Unit, const AddressRanges &LinkedRanges, PatchLocation Patch, DebugDieValuePool &AddrPool)=0
Emit debug ranges (.debug_ranges, .debug_rnglists) fragment.
virtual uint64_t getDebugMacroSectionSize() const =0
Returns size of generated .debug_macro section.
virtual void emitDwarfDebugArangesTable(const CompileUnit &Unit, const AddressRanges &LinkedRanges)=0
Emit .debug_aranges entries for Unit.
virtual uint64_t getDebugInfoSectionSize() const =0
Returns size of generated .debug_info section.
virtual void emitCompileUnitHeader(CompileUnit &Unit, unsigned DwarfVersion)=0
Emit the compilation unit header for Unit in the .debug_info section.
virtual void emitCIE(StringRef CIEBytes)=0
Emit a CIE.
virtual uint64_t getFrameSectionSize() const =0
Returns size of generated .debug_frame section.
virtual void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint64_t Address, StringRef Bytes)=0
Emit an FDE with data Bytes.
virtual void emitAppleNamespaces(AccelTable< AppleAccelTableStaticOffsetData > &Table)=0
Emit Apple namespaces accelerator table.
virtual uint64_t getRngListsSectionSize() const =0
Returns size of generated .debug_rnglists section.
virtual void emitAppleObjc(AccelTable< AppleAccelTableStaticOffsetData > &Table)=0
Emit Apple Objective-C accelerator table.
virtual void emitMacroTables(DWARFContext *Context, const Offset2UnitMap &UnitMacroMap, OffsetsStringPool &StringPool)=0
Emit all available macro tables(DWARFv4 and DWARFv5).
virtual Error emitDwarfDebugLocListFragment(const CompileUnit &Unit, const DWARFLocationExpressionsVector &LinkedLocationExpression, PatchLocation Patch, DebugDieValuePool &AddrPool)=0
Emit debug locations (.debug_loc, .debug_loclists) fragment.
virtual void emitDebugNames(DWARF5AccelTable &Table)=0
Emit DWARF debug names.
virtual void emitAppleTypes(AccelTable< AppleAccelTableStaticTypeData > &Table)=0
Emit Apple type accelerator table.
virtual MCSymbol * emitDwarfDebugAddrsHeader(const CompileUnit &Unit)=0
Emit .debug_addr header.
virtual MCSymbol * emitDwarfDebugLocListHeader(const CompileUnit &Unit)=0
Emit debug locations (.debug_loc, .debug_loclists) header.
virtual void emitLineTableForUnit(const DWARFDebugLine::LineTable &LineTable, const CompileUnit &Unit, OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool, std::vector< uint64_t > *RowOffsets=nullptr)=0
Emit specified LineTable into .debug_line table.
virtual void emitDIE(DIE &Die)=0
Recursively emit the DIE tree rooted at Die.
virtual uint64_t getDebugMacInfoSectionSize() const =0
Returns size of generated .debug_macinfo section.
virtual void emitPubNamesForUnit(const CompileUnit &Unit)=0
Emit the .debug_pubnames contribution for Unit.
virtual void emitAppleNames(AccelTable< AppleAccelTableStaticOffsetData > &Table)=0
Emit Apple names accelerator table.
virtual void emitAbbrevs(const std::vector< std::unique_ptr< DIEAbbrev > > &Abbrevs, unsigned DwarfVersion)=0
Emit the abbreviation table Abbrevs to the .debug_abbrev section.
virtual uint64_t getLocListsSectionSize() const =0
Returns size of generated .debug_loclists section.
virtual uint64_t getLineSectionSize() const =0
Returns size of generated .debug_line section.
virtual MCSymbol * emitDwarfDebugRangeListHeader(const CompileUnit &Unit)=0
Emit debug ranges (.debug_ranges, .debug_rnglists) header.
virtual void emitStrings(const NonRelocatableStringpool &Pool)=0
Emit the string table described by Pool into .debug_str table.
virtual void finish()=0
Dump the file to the disk.
virtual void emitDwarfDebugAddrsFooter(const CompileUnit &Unit, MCSymbol *EndLabel)=0
Emit .debug_addr footer.
virtual uint64_t getRangesSectionSize() const =0
Returns size of generated .debug_ranges section.
virtual void emitLineStrings(const NonRelocatableStringpool &Pool)=0
Emit the string table described by Pool into .debug_line_str table.
virtual void emitDwarfDebugLocListFooter(const CompileUnit &Unit, MCSymbol *EndLabel)=0
Emit debug locations (.debug_loc, .debug_loclists) footer.
virtual void emitStringOffsets(const SmallVector< uint64_t > &StringOffsets, uint16_t TargetDWARFVersion)=0
Emit the debug string offset table described by StringOffsets into the .debug_str_offsets table.
virtual void emitDwarfDebugRangeListFooter(const CompileUnit &Unit, MCSymbol *EndLabel)=0
Emit debug ranges (.debug_ranges, .debug_rnglists) footer.
User of DwarfStreamer should call initialization code for AsmPrinter:
std::vector< std::unique_ptr< CompileUnit > > UnitListTy
IndexedValuesMap< uint64_t > DebugDieValuePool
Definition DWARFLinker.h:39
DenseMap< uint64_t, CompileUnit * > Offset2UnitMap
Definition DWARFLinker.h:38
std::function< void( const Twine &Warning, StringRef Context, const DWARFDie *DIE)> MessageHandlerTy
DebugSectionKind
List of tracked debug tables.
DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec
This is an optimization pass for GlobalISel generic memory operations.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
StrongType< NonRelocatableStringpool, OffsetsTag > OffsetsStringPool
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
Information gathered about a DIE in the object file.