xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp (revision 1a65e4ade4e77ad56a57502dcb0cb21b2850df7a)
1 //===-- llvm/CodeGen/DwarfStringPool.cpp - Dwarf Debug Framework ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "DwarfStringPool.h"
11 #include "llvm/MC/MCStreamer.h"
12 
13 using namespace llvm;
14 
15 DwarfStringPool::EntryTy &DwarfStringPool::getEntry(AsmPrinter &Asm,
16                                                     StringRef Str) {
17   auto &Entry = Pool[Str];
18   if (!Entry.Symbol) {
19     Entry.Index = Pool.size() - 1;
20     Entry.Offset = NumBytes;
21     Entry.Symbol = Asm.createTempSymbol(Prefix);
22 
23     NumBytes += Str.size() + 1;
24     assert(NumBytes > Entry.Offset && "Unexpected overflow");
25   }
26   return Entry;
27 }
28 
29 void DwarfStringPool::emit(AsmPrinter &Asm, MCSection *StrSection,
30                            MCSection *OffsetSection) {
31   if (Pool.empty())
32     return;
33 
34   // Start the dwarf str section.
35   Asm.OutStreamer->SwitchSection(StrSection);
36 
37   // Get all of the string pool entries and put them in an array by their ID so
38   // we can sort them.
39   SmallVector<const StringMapEntry<EntryTy> *, 64> Entries(Pool.size());
40 
41   for (const auto &E : Pool)
42     Entries[E.getValue().Index] = &E;
43 
44   for (const auto &Entry : Entries) {
45     // Emit a label for reference from debug information entries.
46     Asm.OutStreamer->EmitLabel(Entry->getValue().Symbol);
47 
48     // Emit the string itself with a terminating null byte.
49     Asm.OutStreamer->AddComment("string offset=" +
50                                 Twine(Entry->getValue().Offset));
51     Asm.OutStreamer->EmitBytes(
52         StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1));
53   }
54 
55   // If we've got an offset section go ahead and emit that now as well.
56   if (OffsetSection) {
57     Asm.OutStreamer->SwitchSection(OffsetSection);
58     unsigned size = 4; // FIXME: DWARF64 is 8.
59     for (const auto &Entry : Entries)
60       Asm.OutStreamer->EmitIntValue(Entry->getValue().Offset, size);
61   }
62 }
63