Hans Wennborg | 83e6e1e | 2014-04-30 16:25:02 +0000 | [diff] [blame] | 1 | //===-- StringTableBuilder.cpp - String table building utility ------------===// |
| 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 | |
Rafael Espindola | 97de474 | 2014-07-03 02:01:39 +0000 | [diff] [blame] | 10 | #include "llvm/MC/StringTableBuilder.h" |
Hans Wennborg | 83e6e1e | 2014-04-30 16:25:02 +0000 | [diff] [blame] | 11 | #include "llvm/ADT/SmallVector.h" |
Hans Wennborg | 83e6e1e | 2014-04-30 16:25:02 +0000 | [diff] [blame] | 12 | |
| 13 | using namespace llvm; |
| 14 | |
Akira Hatanaka | 8e77dbb | 2014-09-24 20:37:14 +0000 | [diff] [blame^] | 15 | static bool compareBySuffix(StringRef a, StringRef b) { |
| 16 | size_t sizeA = a.size(); |
| 17 | size_t sizeB = b.size(); |
| 18 | size_t len = std::min(sizeA, sizeB); |
| 19 | for (size_t i = 0; i < len; ++i) { |
| 20 | char ca = a[sizeA - i - 1]; |
| 21 | char cb = b[sizeB - i - 1]; |
| 22 | if (ca != cb) |
| 23 | return ca > cb; |
| 24 | } |
| 25 | return sizeA > sizeB; |
| 26 | } |
| 27 | |
Hans Wennborg | 83e6e1e | 2014-04-30 16:25:02 +0000 | [diff] [blame] | 28 | void StringTableBuilder::finalize() { |
| 29 | SmallVector<StringRef, 8> Strings; |
| 30 | for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i) |
| 31 | Strings.push_back(i->getKey()); |
| 32 | |
Akira Hatanaka | 8e77dbb | 2014-09-24 20:37:14 +0000 | [diff] [blame^] | 33 | std::sort(Strings.begin(), Strings.end(), compareBySuffix); |
Hans Wennborg | 83e6e1e | 2014-04-30 16:25:02 +0000 | [diff] [blame] | 34 | |
| 35 | // FIXME: Starting with a null byte is ELF specific. Generalize this so we |
| 36 | // can use the class with other object formats. |
| 37 | StringTable += '\x00'; |
| 38 | |
| 39 | StringRef Previous; |
| 40 | for (StringRef s : Strings) { |
| 41 | if (Previous.endswith(s)) { |
| 42 | StringIndexMap[s] = StringTable.size() - 1 - s.size(); |
| 43 | continue; |
| 44 | } |
| 45 | |
| 46 | StringIndexMap[s] = StringTable.size(); |
| 47 | StringTable += s; |
| 48 | StringTable += '\x00'; |
| 49 | Previous = s; |
| 50 | } |
| 51 | } |