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::EntryRef DwarfStringPool::getEntry(AsmPrinter &Asm,
16                                                     StringRef Str) {
17   auto I = Pool.insert(std::make_pair(Str, EntryTy()));
18   if (I.second) {
19     auto &Entry = I.first->second;
20     Entry.Index = Pool.size() - 1;
21     Entry.Offset = NumBytes;
22     Entry.Symbol = Asm.createTempSymbol(Prefix);
23 
24     NumBytes += Str.size() + 1;
25     assert(NumBytes > Entry.Offset && "Unexpected overflow");
26   }
27   return EntryRef(*I.first);
28 }
29 
30 void DwarfStringPool::emit(AsmPrinter &Asm, MCSection *StrSection,
31                            MCSection *OffsetSection) {
32   if (Pool.empty())
33     return;
34 
35   // Start the dwarf str section.
36   Asm.OutStreamer->SwitchSection(StrSection);
37 
38   // Get all of the string pool entries and put them in an array by their ID so
39   // we can sort them.
40   SmallVector<const StringMapEntry<EntryTy> *, 64> Entries(Pool.size());
41 
42   for (const auto &E : Pool)
43     Entries[E.getValue().Index] = &E;
44 
45   for (const auto &Entry : Entries) {
46     // Emit a label for reference from debug information entries.
47     Asm.OutStreamer->EmitLabel(Entry->getValue().Symbol);
48 
49     // Emit the string itself with a terminating null byte.
50     Asm.OutStreamer->AddComment("string offset=" +
51                                 Twine(Entry->getValue().Offset));
52     Asm.OutStreamer->EmitBytes(
53         StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1));
54   }
55 
56   // If we've got an offset section go ahead and emit that now as well.
57   if (OffsetSection) {
58     Asm.OutStreamer->SwitchSection(OffsetSection);
59     unsigned size = 4; // FIXME: DWARF64 is 8.
60     for (const auto &Entry : Entries)
61       Asm.OutStreamer->EmitIntValue(Entry->getValue().Offset, size);
62   }
63 }
64