xref: /freebsd/contrib/llvm-project/llvm/lib/Demangle/Demangle.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 //===-- Demangle.cpp - Common demangling functions ------------------------===//
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 /// \file This file contains definitions of common demangling functions.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Demangle/Demangle.h"
14 #include "llvm/Demangle/StringViewExtras.h"
15 #include <cstdlib>
16 #include <string_view>
17 
18 using llvm::itanium_demangle::starts_with;
19 
20 std::string llvm::demangle(std::string_view MangledName) {
21   std::string Result;
22 
23   if (nonMicrosoftDemangle(MangledName, Result))
24     return Result;
25 
26   if (starts_with(MangledName, '_') &&
27       nonMicrosoftDemangle(MangledName.substr(1), Result))
28     return Result;
29 
30   if (char *Demangled = microsoftDemangle(MangledName, nullptr, nullptr)) {
31     Result = Demangled;
32     std::free(Demangled);
33   } else {
34     Result = MangledName;
35   }
36   return Result;
37 }
38 
39 static bool isItaniumEncoding(std::string_view S) {
40   // Itanium encoding requires 1 or 3 leading underscores, followed by 'Z'.
41   return starts_with(S, "_Z") || starts_with(S, "___Z");
42 }
43 
44 static bool isRustEncoding(std::string_view S) { return starts_with(S, "_R"); }
45 
46 static bool isDLangEncoding(std::string_view S) { return starts_with(S, "_D"); }
47 
48 bool llvm::nonMicrosoftDemangle(std::string_view MangledName,
49                                 std::string &Result) {
50   char *Demangled = nullptr;
51   if (isItaniumEncoding(MangledName))
52     Demangled = itaniumDemangle(MangledName);
53   else if (isRustEncoding(MangledName))
54     Demangled = rustDemangle(MangledName);
55   else if (isDLangEncoding(MangledName))
56     Demangled = dlangDemangle(MangledName);
57 
58   if (!Demangled)
59     return false;
60 
61   Result = Demangled;
62   std::free(Demangled);
63   return true;
64 }
65