1 //===- bolt/Utils/NameResolver.h - Names deduplication helper ---*- 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 // Helper class for names deduplication.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef BOLT_UTILS_NAME_RESOLVER_H
14 #define BOLT_UTILS_NAME_RESOLVER_H
15 
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 
19 namespace llvm {
20 namespace bolt {
21 
22 class NameResolver {
23   /// Track the number of duplicate names.
24   StringMap<uint64_t> Counters;
25 
26   /// Character guaranteed not to be used by any "native" name passed to
27   /// uniquify() function.
28   static constexpr char Sep = '/';
29 
30 public:
31   /// Return unique version of the \p Name in the form "Name<Sep><Number>".
uniquify(StringRef Name)32   std::string uniquify(StringRef Name) {
33     const uint64_t ID = ++Counters[Name];
34     return (Name + Twine(Sep) + Twine(ID)).str();
35   }
36 
37   /// For uniquified \p Name, return the original form (that may no longer be
38   /// unique).
restore(StringRef Name)39   static StringRef restore(StringRef Name) {
40     return Name.substr(0, Name.find_first_of(Sep));
41   }
42 
43   /// Append \p Suffix to the original string in \p UniqueName  preserving the
44   /// deduplication form. E.g. append("Name<Sep>42", "Suffix") will return
45   /// "NameSuffix<Sep>42".
append(StringRef UniqueName,StringRef Suffix)46   static std::string append(StringRef UniqueName, StringRef Suffix) {
47     StringRef LHS, RHS;
48     std::tie(LHS, RHS) = UniqueName.split(Sep);
49     return (LHS + Suffix + Twine(Sep) + RHS).str();
50   }
51 };
52 
53 } // namespace bolt
54 } // namespace llvm
55 
56 #endif
57