ItaniumManglingCanonicalizer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. //===----------------- ItaniumManglingCanonicalizer.cpp -------------------===//
  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. #include "llvm/Support/ItaniumManglingCanonicalizer.h"
  9. #include "llvm/ADT/FoldingSet.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/Demangle/ItaniumDemangle.h"
  12. #include "llvm/Support/Allocator.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/FoldingSet.h"
  15. #include "llvm/ADT/StringRef.h"
  16. using namespace llvm;
  17. using llvm::itanium_demangle::ForwardTemplateReference;
  18. using llvm::itanium_demangle::Node;
  19. using llvm::itanium_demangle::NodeKind;
  20. using llvm::itanium_demangle::StringView;
  21. namespace {
  22. struct FoldingSetNodeIDBuilder {
  23. llvm::FoldingSetNodeID &ID;
  24. void operator()(const Node *P) { ID.AddPointer(P); }
  25. void operator()(StringView Str) {
  26. ID.AddString(llvm::StringRef(Str.begin(), Str.size()));
  27. }
  28. template<typename T>
  29. typename std::enable_if<std::is_integral<T>::value ||
  30. std::is_enum<T>::value>::type
  31. operator()(T V) {
  32. ID.AddInteger((unsigned long long)V);
  33. }
  34. void operator()(itanium_demangle::NodeOrString NS) {
  35. if (NS.isNode()) {
  36. ID.AddInteger(0);
  37. (*this)(NS.asNode());
  38. } else if (NS.isString()) {
  39. ID.AddInteger(1);
  40. (*this)(NS.asString());
  41. } else {
  42. ID.AddInteger(2);
  43. }
  44. }
  45. void operator()(itanium_demangle::NodeArray A) {
  46. ID.AddInteger(A.size());
  47. for (const Node *N : A)
  48. (*this)(N);
  49. }
  50. };
  51. template<typename ...T>
  52. void profileCtor(llvm::FoldingSetNodeID &ID, Node::Kind K, T ...V) {
  53. FoldingSetNodeIDBuilder Builder = {ID};
  54. Builder(K);
  55. int VisitInOrder[] = {
  56. (Builder(V), 0) ...,
  57. 0 // Avoid empty array if there are no arguments.
  58. };
  59. (void)VisitInOrder;
  60. }
  61. // FIXME: Convert this to a generic lambda when possible.
  62. template<typename NodeT> struct ProfileSpecificNode {
  63. FoldingSetNodeID &ID;
  64. template<typename ...T> void operator()(T ...V) {
  65. profileCtor(ID, NodeKind<NodeT>::Kind, V...);
  66. }
  67. };
  68. struct ProfileNode {
  69. FoldingSetNodeID &ID;
  70. template<typename NodeT> void operator()(const NodeT *N) {
  71. N->match(ProfileSpecificNode<NodeT>{ID});
  72. }
  73. };
  74. template<> void ProfileNode::operator()(const ForwardTemplateReference *N) {
  75. llvm_unreachable("should never canonicalize a ForwardTemplateReference");
  76. }
  77. void profileNode(llvm::FoldingSetNodeID &ID, const Node *N) {
  78. N->visit(ProfileNode{ID});
  79. }
  80. class FoldingNodeAllocator {
  81. class alignas(alignof(Node *)) NodeHeader : public llvm::FoldingSetNode {
  82. public:
  83. // 'Node' in this context names the injected-class-name of the base class.
  84. itanium_demangle::Node *getNode() {
  85. return reinterpret_cast<itanium_demangle::Node *>(this + 1);
  86. }
  87. void Profile(llvm::FoldingSetNodeID &ID) { profileNode(ID, getNode()); }
  88. };
  89. BumpPtrAllocator RawAlloc;
  90. llvm::FoldingSet<NodeHeader> Nodes;
  91. public:
  92. void reset() {}
  93. template <typename T, typename... Args>
  94. std::pair<Node *, bool> getOrCreateNode(bool CreateNewNodes, Args &&... As) {
  95. // FIXME: Don't canonicalize forward template references for now, because
  96. // they contain state (the resolved template node) that's not known at their
  97. // point of creation.
  98. if (std::is_same<T, ForwardTemplateReference>::value) {
  99. // Note that we don't use if-constexpr here and so we must still write
  100. // this code in a generic form.
  101. return {new (RawAlloc.Allocate(sizeof(T), alignof(T)))
  102. T(std::forward<Args>(As)...),
  103. true};
  104. }
  105. llvm::FoldingSetNodeID ID;
  106. profileCtor(ID, NodeKind<T>::Kind, As...);
  107. void *InsertPos;
  108. if (NodeHeader *Existing = Nodes.FindNodeOrInsertPos(ID, InsertPos))
  109. return {static_cast<T*>(Existing->getNode()), false};
  110. if (!CreateNewNodes)
  111. return {nullptr, true};
  112. static_assert(alignof(T) <= alignof(NodeHeader),
  113. "underaligned node header for specific node kind");
  114. void *Storage =
  115. RawAlloc.Allocate(sizeof(NodeHeader) + sizeof(T), alignof(NodeHeader));
  116. NodeHeader *New = new (Storage) NodeHeader;
  117. T *Result = new (New->getNode()) T(std::forward<Args>(As)...);
  118. Nodes.InsertNode(New, InsertPos);
  119. return {Result, true};
  120. }
  121. template<typename T, typename... Args>
  122. Node *makeNode(Args &&...As) {
  123. return getOrCreateNode<T>(true, std::forward<Args>(As)...).first;
  124. }
  125. void *allocateNodeArray(size_t sz) {
  126. return RawAlloc.Allocate(sizeof(Node *) * sz, alignof(Node *));
  127. }
  128. };
  129. class CanonicalizerAllocator : public FoldingNodeAllocator {
  130. Node *MostRecentlyCreated = nullptr;
  131. Node *TrackedNode = nullptr;
  132. bool TrackedNodeIsUsed = false;
  133. bool CreateNewNodes = true;
  134. llvm::SmallDenseMap<Node*, Node*, 32> Remappings;
  135. template<typename T, typename ...Args> Node *makeNodeSimple(Args &&...As) {
  136. std::pair<Node *, bool> Result =
  137. getOrCreateNode<T>(CreateNewNodes, std::forward<Args>(As)...);
  138. if (Result.second) {
  139. // Node is new. Make a note of that.
  140. MostRecentlyCreated = Result.first;
  141. } else if (Result.first) {
  142. // Node is pre-existing; check if it's in our remapping table.
  143. if (auto *N = Remappings.lookup(Result.first)) {
  144. Result.first = N;
  145. assert(Remappings.find(Result.first) == Remappings.end() &&
  146. "should never need multiple remap steps");
  147. }
  148. if (Result.first == TrackedNode)
  149. TrackedNodeIsUsed = true;
  150. }
  151. return Result.first;
  152. }
  153. /// Helper to allow makeNode to be partially-specialized on T.
  154. template<typename T> struct MakeNodeImpl {
  155. CanonicalizerAllocator &Self;
  156. template<typename ...Args> Node *make(Args &&...As) {
  157. return Self.makeNodeSimple<T>(std::forward<Args>(As)...);
  158. }
  159. };
  160. public:
  161. template<typename T, typename ...Args> Node *makeNode(Args &&...As) {
  162. return MakeNodeImpl<T>{*this}.make(std::forward<Args>(As)...);
  163. }
  164. void reset() { MostRecentlyCreated = nullptr; }
  165. void setCreateNewNodes(bool CNN) { CreateNewNodes = CNN; }
  166. void addRemapping(Node *A, Node *B) {
  167. // Note, we don't need to check whether B is also remapped, because if it
  168. // was we would have already remapped it when building it.
  169. Remappings.insert(std::make_pair(A, B));
  170. }
  171. bool isMostRecentlyCreated(Node *N) const { return MostRecentlyCreated == N; }
  172. void trackUsesOf(Node *N) {
  173. TrackedNode = N;
  174. TrackedNodeIsUsed = false;
  175. }
  176. bool trackedNodeIsUsed() const { return TrackedNodeIsUsed; }
  177. };
  178. /// Convert St3foo to NSt3fooE so that equivalences naming one also affect the
  179. /// other.
  180. template<>
  181. struct CanonicalizerAllocator::MakeNodeImpl<
  182. itanium_demangle::StdQualifiedName> {
  183. CanonicalizerAllocator &Self;
  184. Node *make(Node *Child) {
  185. Node *StdNamespace = Self.makeNode<itanium_demangle::NameType>("std");
  186. if (!StdNamespace)
  187. return nullptr;
  188. return Self.makeNode<itanium_demangle::NestedName>(StdNamespace, Child);
  189. }
  190. };
  191. // FIXME: Also expand built-in substitutions?
  192. using CanonicalizingDemangler =
  193. itanium_demangle::ManglingParser<CanonicalizerAllocator>;
  194. }
  195. struct ItaniumManglingCanonicalizer::Impl {
  196. CanonicalizingDemangler Demangler = {nullptr, nullptr};
  197. };
  198. ItaniumManglingCanonicalizer::ItaniumManglingCanonicalizer() : P(new Impl) {}
  199. ItaniumManglingCanonicalizer::~ItaniumManglingCanonicalizer() { delete P; }
  200. ItaniumManglingCanonicalizer::EquivalenceError
  201. ItaniumManglingCanonicalizer::addEquivalence(FragmentKind Kind, StringRef First,
  202. StringRef Second) {
  203. auto &Alloc = P->Demangler.ASTAllocator;
  204. Alloc.setCreateNewNodes(true);
  205. auto Parse = [&](StringRef Str) {
  206. P->Demangler.reset(Str.begin(), Str.end());
  207. Node *N = nullptr;
  208. switch (Kind) {
  209. // A <name>, with minor extensions to allow arbitrary namespace and
  210. // template names that can't easily be written as <name>s.
  211. case FragmentKind::Name:
  212. // Very special case: allow "St" as a shorthand for "3std". It's not
  213. // valid as a <name> mangling, but is nonetheless the most natural
  214. // way to name the 'std' namespace.
  215. if (Str.size() == 2 && P->Demangler.consumeIf("St"))
  216. N = P->Demangler.make<itanium_demangle::NameType>("std");
  217. // We permit substitutions to name templates without their template
  218. // arguments. This mostly just falls out, as almost all template names
  219. // are valid as <name>s, but we also want to parse <substitution>s as
  220. // <name>s, even though they're not.
  221. else if (Str.startswith("S"))
  222. // Parse the substitution and optional following template arguments.
  223. N = P->Demangler.parseType();
  224. else
  225. N = P->Demangler.parseName();
  226. break;
  227. // A <type>.
  228. case FragmentKind::Type:
  229. N = P->Demangler.parseType();
  230. break;
  231. // An <encoding>.
  232. case FragmentKind::Encoding:
  233. N = P->Demangler.parseEncoding();
  234. break;
  235. }
  236. // If we have trailing junk, the mangling is invalid.
  237. if (P->Demangler.numLeft() != 0)
  238. N = nullptr;
  239. // If any node was created after N, then we cannot safely remap it because
  240. // it might already be in use by another node.
  241. return std::make_pair(N, Alloc.isMostRecentlyCreated(N));
  242. };
  243. Node *FirstNode, *SecondNode;
  244. bool FirstIsNew, SecondIsNew;
  245. std::tie(FirstNode, FirstIsNew) = Parse(First);
  246. if (!FirstNode)
  247. return EquivalenceError::InvalidFirstMangling;
  248. Alloc.trackUsesOf(FirstNode);
  249. std::tie(SecondNode, SecondIsNew) = Parse(Second);
  250. if (!SecondNode)
  251. return EquivalenceError::InvalidSecondMangling;
  252. // If they're already equivalent, there's nothing to do.
  253. if (FirstNode == SecondNode)
  254. return EquivalenceError::Success;
  255. if (FirstIsNew && !Alloc.trackedNodeIsUsed())
  256. Alloc.addRemapping(FirstNode, SecondNode);
  257. else if (SecondIsNew)
  258. Alloc.addRemapping(SecondNode, FirstNode);
  259. else
  260. return EquivalenceError::ManglingAlreadyUsed;
  261. return EquivalenceError::Success;
  262. }
  263. ItaniumManglingCanonicalizer::Key
  264. ItaniumManglingCanonicalizer::canonicalize(StringRef Mangling) {
  265. P->Demangler.ASTAllocator.setCreateNewNodes(true);
  266. P->Demangler.reset(Mangling.begin(), Mangling.end());
  267. return reinterpret_cast<Key>(P->Demangler.parse());
  268. }
  269. ItaniumManglingCanonicalizer::Key
  270. ItaniumManglingCanonicalizer::lookup(StringRef Mangling) {
  271. P->Demangler.ASTAllocator.setCreateNewNodes(false);
  272. P->Demangler.reset(Mangling.begin(), Mangling.end());
  273. return reinterpret_cast<Key>(P->Demangler.parse());
  274. }