Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / tools / llvm-cxxfilt / llvm-cxxfilt.cpp
blob4b9d88a650666ee5917dacacb661d0eae09708aa
1 //===-- llvm-c++filt.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 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/StringExtras.h"
10 #include "llvm/Demangle/Demangle.h"
11 #include "llvm/Demangle/StringViewExtras.h"
12 #include "llvm/Option/Arg.h"
13 #include "llvm/Option/ArgList.h"
14 #include "llvm/Option/Option.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/InitLLVM.h"
17 #include "llvm/Support/LLVMDriver.h"
18 #include "llvm/Support/WithColor.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/TargetParser/Host.h"
21 #include "llvm/TargetParser/Triple.h"
22 #include <cstdlib>
23 #include <iostream>
25 using namespace llvm;
27 namespace {
28 enum ID {
29 OPT_INVALID = 0, // This is not an option ID.
30 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
31 #include "Opts.inc"
32 #undef OPTION
35 #define PREFIX(NAME, VALUE) \
36 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
37 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
38 NAME##_init, std::size(NAME##_init) - 1);
39 #include "Opts.inc"
40 #undef PREFIX
42 using namespace llvm::opt;
43 static constexpr opt::OptTable::Info InfoTable[] = {
44 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
45 #include "Opts.inc"
46 #undef OPTION
49 class CxxfiltOptTable : public opt::GenericOptTable {
50 public:
51 CxxfiltOptTable() : opt::GenericOptTable(InfoTable) {
52 setGroupedShortOptions(true);
55 } // namespace
57 static bool StripUnderscore;
58 static bool Types;
60 static StringRef ToolName;
62 static void error(const Twine &Message) {
63 WithColor::error(errs(), ToolName) << Message << '\n';
64 exit(1);
67 static std::string demangle(const std::string &Mangled) {
68 using llvm::itanium_demangle::starts_with;
69 std::string_view DecoratedStr = Mangled;
70 bool CanHaveLeadingDot = true;
71 if (StripUnderscore && DecoratedStr[0] == '_') {
72 DecoratedStr.remove_prefix(1);
73 CanHaveLeadingDot = false;
76 std::string Result;
77 if (nonMicrosoftDemangle(DecoratedStr, Result, CanHaveLeadingDot))
78 return Result;
80 std::string Prefix;
81 char *Undecorated = nullptr;
83 if (Types)
84 Undecorated = itaniumDemangle(DecoratedStr);
86 if (!Undecorated && starts_with(DecoratedStr, "__imp_")) {
87 Prefix = "import thunk for ";
88 Undecorated = itaniumDemangle(DecoratedStr.substr(6));
91 Result = Undecorated ? Prefix + Undecorated : Mangled;
92 free(Undecorated);
93 return Result;
96 // Split 'Source' on any character that fails to pass 'IsLegalChar'. The
97 // returned vector consists of pairs where 'first' is the delimited word, and
98 // 'second' are the delimiters following that word.
99 static void SplitStringDelims(
100 StringRef Source,
101 SmallVectorImpl<std::pair<StringRef, StringRef>> &OutFragments,
102 function_ref<bool(char)> IsLegalChar) {
103 // The beginning of the input string.
104 const auto Head = Source.begin();
106 // Obtain any leading delimiters.
107 auto Start = std::find_if(Head, Source.end(), IsLegalChar);
108 if (Start != Head)
109 OutFragments.push_back({"", Source.slice(0, Start - Head)});
111 // Capture each word and the delimiters following that word.
112 while (Start != Source.end()) {
113 Start = std::find_if(Start, Source.end(), IsLegalChar);
114 auto End = std::find_if_not(Start, Source.end(), IsLegalChar);
115 auto DEnd = std::find_if(End, Source.end(), IsLegalChar);
116 OutFragments.push_back({Source.slice(Start - Head, End - Head),
117 Source.slice(End - Head, DEnd - Head)});
118 Start = DEnd;
122 // This returns true if 'C' is a character that can show up in an
123 // Itanium-mangled string.
124 static bool IsLegalItaniumChar(char C) {
125 // Itanium CXX ABI [External Names]p5.1.1:
126 // '$' and '.' in mangled names are reserved for private implementations.
127 return isAlnum(C) || C == '.' || C == '$' || C == '_';
130 // If 'Split' is true, then 'Mangled' is broken into individual words and each
131 // word is demangled. Otherwise, the entire string is treated as a single
132 // mangled item. The result is output to 'OS'.
133 static void demangleLine(llvm::raw_ostream &OS, StringRef Mangled, bool Split) {
134 std::string Result;
135 if (Split) {
136 SmallVector<std::pair<StringRef, StringRef>, 16> Words;
137 SplitStringDelims(Mangled, Words, IsLegalItaniumChar);
138 for (const auto &Word : Words)
139 Result += ::demangle(std::string(Word.first)) + Word.second.str();
140 } else
141 Result = ::demangle(std::string(Mangled));
142 OS << Result << '\n';
143 OS.flush();
146 int llvm_cxxfilt_main(int argc, char **argv, const llvm::ToolContext &) {
147 InitLLVM X(argc, argv);
148 BumpPtrAllocator A;
149 StringSaver Saver(A);
150 CxxfiltOptTable Tbl;
151 ToolName = argv[0];
152 opt::InputArgList Args = Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,
153 [&](StringRef Msg) { error(Msg); });
154 if (Args.hasArg(OPT_help)) {
155 Tbl.printHelp(outs(),
156 (Twine(ToolName) + " [options] <mangled>").str().c_str(),
157 "LLVM symbol undecoration tool");
158 // TODO Replace this with OptTable API once it adds extrahelp support.
159 outs() << "\nPass @FILE as argument to read options from FILE.\n";
160 return 0;
162 if (Args.hasArg(OPT_version)) {
163 outs() << ToolName << '\n';
164 cl::PrintVersionMessage();
165 return 0;
168 // The default value depends on the default triple. Mach-O has symbols
169 // prefixed with "_", so strip by default.
170 if (opt::Arg *A =
171 Args.getLastArg(OPT_strip_underscore, OPT_no_strip_underscore))
172 StripUnderscore = A->getOption().matches(OPT_strip_underscore);
173 else
174 StripUnderscore = Triple(sys::getProcessTriple()).isOSBinFormatMachO();
176 Types = Args.hasArg(OPT_types);
178 std::vector<std::string> Decorated = Args.getAllArgValues(OPT_INPUT);
179 if (Decorated.empty())
180 for (std::string Mangled; std::getline(std::cin, Mangled);)
181 demangleLine(llvm::outs(), Mangled, true);
182 else
183 for (const auto &Symbol : Decorated)
184 demangleLine(llvm::outs(), Symbol, false);
186 return EXIT_SUCCESS;