0c58f5c84f6809a488b807e7783bb890a27468ab
[oota-llvm.git] / include / llvm / MC / StringTableBuilder.h
1 //===-- StringTableBuilder.h - String table building utility ------*- C++ -*-=//
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 #ifndef LLVM_MC_STRINGTABLEBUILDER_H
11 #define LLVM_MC_STRINGTABLEBUILDER_H
12
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/StringMap.h"
15 #include <cassert>
16
17 namespace llvm {
18
19 /// \brief Utility for building string tables with deduplicated suffixes.
20 class StringTableBuilder {
21   SmallString<256> StringTable;
22   StringMap<size_t> StringIndexMap;
23
24 public:
25   /// \brief Add a string to the builder. Returns a StringRef to the internal
26   /// copy of s. Can only be used before the table is finalized.
27   StringRef add(StringRef s) {
28     assert(!isFinalized());
29     return StringIndexMap.GetOrCreateValue(s, 0).getKey();
30   }
31
32   enum Kind {
33     ELF,
34     WinCOFF
35   };
36
37   /// \brief Analyze the strings and build the final table. No more strings can
38   /// be added after this point.
39   void finalize(Kind kind);
40
41   /// \brief Retrieve the string table data. Can only be used after the table
42   /// is finalized.
43   StringRef data() {
44     assert(isFinalized());
45     return StringTable;
46   }
47
48   /// \brief Get the offest of a string in the string table. Can only be used
49   /// after the table is finalized.
50   size_t getOffset(StringRef s) {
51     assert(isFinalized());
52     assert(StringIndexMap.count(s) && "String is not in table!");
53     return StringIndexMap[s];
54   }
55
56   void clear();
57
58 private:
59   bool isFinalized() {
60     return !StringTable.empty();
61   }
62 };
63
64 } // end llvm namespace
65
66 #endif