1//===-- llvm-tli-checker.cpp - Compare TargetLibraryInfo to SDK libraries -===//
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#include "llvm/ADT/SmallString.h"
10#include "llvm/ADT/StringMap.h"
11#include "llvm/Analysis/TargetLibraryInfo.h"
12#include "llvm/Config/llvm-config.h"
13#include "llvm/Demangle/Demangle.h"
14#include "llvm/Object/Archive.h"
15#include "llvm/Object/ELFObjectFile.h"
16#include "llvm/Option/ArgList.h"
17#include "llvm/Option/Option.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/InitLLVM.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/WithColor.h"
22#include "llvm/TargetParser/Triple.h"
23
24using namespace llvm;
25using namespace llvm::object;
26
27// Command-line option boilerplate.
28namespace {
29enum ID {
30 OPT_INVALID = 0, // This is not an option ID.
31#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
32#include "Opts.inc"
33#undef OPTION
34};
35
36using namespace llvm::opt;
37#define OPTTABLE_CODE
38#include "Opts.inc"
39
40class TLICheckerOptTable : public opt::OptTable {
41public:
42 TLICheckerOptTable() : OptTable(optionTables()) {}
43};
44} // end anonymous namespace
45
46// We have three levels of reporting.
47enum class ReportKind {
48 Error, // For argument parsing errors.
49 Summary, // Report counts but not details.
50 Discrepancy, // Report where TLI and the library differ.
51 Full // Report for every known-to-TLI function.
52};
53
54// Most of the ObjectFile interfaces return an Expected<T>, so make it easy
55// to ignore errors.
56template <typename T>
57static T unwrapIgnoreError(Expected<T> E, T Default = T()) {
58 if (E)
59 return std::move(*E);
60 // Sink the error and return a nothing value.
61 consumeError(E.takeError());
62 return Default;
63}
64
65static void fail(const Twine &Message) {
66 WithColor::error() << Message << '\n';
67 exit(EXIT_FAILURE);
68}
69
70// Some problem occurred with an archive member; complain and continue.
71static void reportArchiveChildIssue(const object::Archive::Child &C, int Index,
72 StringRef ArchiveFilename) {
73 // First get the member name.
74 std::string ChildName;
75 Expected<StringRef> NameOrErr = C.getName();
76 if (NameOrErr)
77 ChildName = std::string(NameOrErr.get());
78 else {
79 // Ignore the name-fetch error, just report the index.
80 consumeError(Err: NameOrErr.takeError());
81 ChildName = "<file index: " + std::to_string(val: Index) + ">";
82 }
83
84 WithColor::warning() << ArchiveFilename << "(" << ChildName
85 << "): member is not usable\n";
86}
87
88// Return Name, and if Name is mangled, append "aka" and the demangled name.
89static raw_ostream &printPrintableName(raw_ostream &OS, StringRef Name) {
90 OS << '\'' << Name << '\'';
91
92 std::string DemangledName(demangle(MangledName: Name));
93 if (Name != DemangledName)
94 OS << " aka " << DemangledName;
95 return OS;
96}
97
98static void reportNumberOfEntries(const TargetLibraryInfo &TLI,
99 StringRef TargetTriple) {
100 unsigned NumAvailable = 0;
101
102 // Assume this gets called after initialize(), so we have the above line of
103 // output as a header. So, for example, no need to repeat the triple.
104 for (unsigned FI = LibFunc::Begin_LibFunc; FI != LibFunc::End_LibFunc; ++FI) {
105 if (TLI.has(F: static_cast<LibFunc>(FI)))
106 ++NumAvailable;
107 }
108
109 outs() << "TLI knows " << (LibFunc::End_LibFunc - LibFunc::Begin_LibFunc)
110 << " symbols, " << NumAvailable << " available for '" << TargetTriple
111 << "'\n";
112}
113
114static void dumpTLIEntries(const TargetLibraryInfo &TLI) {
115 // Assume this gets called after initialize(), so we have the above line of
116 // output as a header. So, for example, no need to repeat the triple.
117 for (unsigned FI = LibFunc::Begin_LibFunc; FI != LibFunc::End_LibFunc; ++FI) {
118 LibFunc LF = static_cast<LibFunc>(FI);
119 bool IsAvailable = TLI.has(F: LF);
120
121 outs() << (IsAvailable ? " " : "not ") << "available: ";
122
123 if (IsAvailable) {
124 // Print the (possibly custom) name.
125 // TODO: Should we include the standard name in the printed line?
126 printPrintableName(OS&: outs(), Name: TLI.getName(F: LF));
127 } else {
128 // If it's not available, refer to it by the standard name.
129 printPrintableName(OS&: outs(), Name: TargetLibraryInfo::getStandardName(F: LF));
130 }
131
132 outs() << '\n';
133 }
134}
135
136// Store all the exported symbol names we found in the input libraries.
137// We use a map to get hashed lookup speed; the bool is meaningless.
138class SDKNameMap : public StringMap<bool> {
139 void maybeInsertSymbol(const SymbolRef &S, const ObjectFile &O);
140 void populateFromObject(ObjectFile *O);
141 void populateFromArchive(Archive *A);
142
143public:
144 void populateFromFile(StringRef LibDir, StringRef LibName);
145};
146static SDKNameMap SDKNames;
147
148// Insert defined global function symbols into the map if valid.
149void SDKNameMap::maybeInsertSymbol(const SymbolRef &S, const ObjectFile &O) {
150 SymbolRef::Type Type = unwrapIgnoreError(E: S.getType());
151 uint32_t Flags = unwrapIgnoreError(E: S.getFlags());
152 section_iterator Section = unwrapIgnoreError(E: S.getSection(),
153 /*Default=*/O.section_end());
154 bool IsRegularFunction = Type == SymbolRef::ST_Function &&
155 (Flags & SymbolRef::SF_Global) &&
156 Section != O.section_end();
157 bool IsIFunc =
158 Type == SymbolRef::ST_Other && (Flags & SymbolRef::SF_Indirect);
159 if (IsRegularFunction || IsIFunc) {
160 StringRef Name = unwrapIgnoreError(E: S.getName());
161 insert(KV: { Name, true });
162 }
163}
164
165// Given an ObjectFile, extract the global function symbols.
166void SDKNameMap::populateFromObject(ObjectFile *O) {
167 // FIXME: Support other formats.
168 if (!O->isELF()) {
169 WithColor::warning() << O->getFileName()
170 << ": only ELF-format files are supported\n";
171 return;
172 }
173 const auto *ELF = cast<ELFObjectFileBase>(Val: O);
174
175 if (ELF->getEType() == ELF::ET_REL) {
176 for (const auto &S : ELF->symbols())
177 maybeInsertSymbol(S, O: *O);
178 } else {
179 for (const auto &S : ELF->getDynamicSymbolIterators())
180 maybeInsertSymbol(S, O: *O);
181 }
182}
183
184// Unpack an archive and populate from the component object files.
185// This roughly imitates dumpArchive() from llvm-objdump.cpp.
186void SDKNameMap::populateFromArchive(Archive *A) {
187 Error Err = Error::success();
188 int Index = -1;
189 for (const auto &C : A->children(Err)) {
190 ++Index;
191 Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary();
192 if (!ChildOrErr) {
193 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError())) {
194 // Issue a generic warning.
195 consumeError(Err: std::move(E));
196 reportArchiveChildIssue(C, Index, ArchiveFilename: A->getFileName());
197 }
198 continue;
199 }
200 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get()))
201 populateFromObject(O);
202 // Ignore non-object archive members.
203 }
204 if (Err)
205 WithColor::defaultErrorHandler(Err: std::move(Err));
206}
207
208// Unpack a library file and extract the global function names.
209void SDKNameMap::populateFromFile(StringRef LibDir, StringRef LibName) {
210 // Pick an arbitrary but reasonable default size.
211 SmallString<255> Filepath(LibDir);
212 sys::path::append(path&: Filepath, a: LibName);
213 if (!sys::fs::exists(Path: Filepath)) {
214 WithColor::warning() << StringRef(Filepath) << ": not found\n";
215 return;
216 }
217 outs() << "\nLooking for symbols in '" << StringRef(Filepath) << "'\n";
218 auto ExpectedBinary = createBinary(Path: Filepath);
219 if (!ExpectedBinary) {
220 // FIXME: Report this better.
221 WithColor::defaultWarningHandler(Warning: ExpectedBinary.takeError());
222 return;
223 }
224 OwningBinary<Binary> OBinary = std::move(*ExpectedBinary);
225 Binary &Binary = *OBinary.getBinary();
226 size_t Precount = size();
227 if (Archive *A = dyn_cast<Archive>(Val: &Binary))
228 populateFromArchive(A);
229 else if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Binary))
230 populateFromObject(O);
231 else {
232 WithColor::warning() << StringRef(Filepath)
233 << ": not an archive or object file\n";
234 return;
235 }
236 if (Precount == size())
237 WithColor::warning() << StringRef(Filepath) << ": no symbols found\n";
238 else
239 outs() << "Found " << size() - Precount << " global function symbols in '"
240 << StringRef(Filepath) << "'\n";
241}
242
243int main(int argc, char *argv[]) {
244 InitLLVM X(argc, argv);
245 BumpPtrAllocator A;
246 StringSaver Saver(A);
247 TLICheckerOptTable Tbl;
248 opt::InputArgList Args = Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver,
249 ErrorFn: [&](StringRef Msg) { fail(Message: Msg); });
250
251 if (Args.hasArg(Ids: OPT_help)) {
252 std::string Usage(argv[0]);
253 Usage += " [options] library-file [library-file...]";
254 Tbl.printHelp(OS&: outs(), Usage: Usage.c_str(),
255 Title: "LLVM TargetLibraryInfo versus SDK checker");
256 outs() << "\nPass @FILE as argument to read options or library names from "
257 "FILE.\n";
258 return 0;
259 }
260
261 StringRef TripleStr = Args.getLastArgValue(Id: OPT_triple_EQ);
262 Triple TargetTriple(TripleStr);
263 TargetLibraryInfoImpl TLII(TargetTriple);
264 TargetLibraryInfo TLI(TLII);
265
266 reportNumberOfEntries(TLI, TargetTriple: TripleStr);
267
268 // --dump-tli doesn't require any input files.
269 if (Args.hasArg(Ids: OPT_dump_tli)) {
270 dumpTLIEntries(TLI);
271 return 0;
272 }
273
274 std::vector<std::string> LibList = Args.getAllArgValues(Id: OPT_INPUT);
275 if (LibList.empty())
276 fail(Message: "no input files\n");
277 StringRef LibDir = Args.getLastArgValue(Id: OPT_libdir_EQ);
278 bool SeparateMode = Args.hasArg(Ids: OPT_separate);
279
280 ReportKind ReportLevel =
281 SeparateMode ? ReportKind::Summary : ReportKind::Discrepancy;
282 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_report_EQ)) {
283 ReportLevel = StringSwitch<ReportKind>(A->getValue())
284 .Case(S: "summary", Value: ReportKind::Summary)
285 .Case(S: "discrepancy", Value: ReportKind::Discrepancy)
286 .Case(S: "full", Value: ReportKind::Full)
287 .Default(Value: ReportKind::Error);
288 if (ReportLevel == ReportKind::Error)
289 fail(Message: Twine("invalid option for --report: ", StringRef(A->getValue())));
290 }
291
292 for (size_t I = 0; I < LibList.size(); ++I) {
293 // In SeparateMode we report on input libraries individually; otherwise
294 // we do one big combined search. Reading to the end of LibList here
295 // will cause the outer while loop to terminate cleanly.
296 if (SeparateMode) {
297 SDKNames.clear();
298 SDKNames.populateFromFile(LibDir, LibName: LibList[I]);
299 if (SDKNames.empty())
300 continue;
301 } else {
302 do
303 SDKNames.populateFromFile(LibDir, LibName: LibList[I]);
304 while (++I < LibList.size());
305 if (SDKNames.empty()) {
306 WithColor::error() << "NO symbols found!\n";
307 break;
308 }
309 outs() << "Found a grand total of " << SDKNames.size()
310 << " library symbols\n";
311 }
312 unsigned TLIdoesSDKdoesnt = 0;
313 unsigned TLIdoesntSDKdoes = 0;
314 unsigned TLIandSDKboth = 0;
315 unsigned TLIandSDKneither = 0;
316
317 for (unsigned FI = LibFunc::Begin_LibFunc; FI != LibFunc::End_LibFunc;
318 ++FI) {
319 LibFunc LF = static_cast<LibFunc>(FI);
320
321 StringRef TLIName = TLI.getStandardName(F: LF);
322 bool TLIHas = TLI.has(F: LF);
323 bool SDKHas = SDKNames.count(Key: TLIName) == 1;
324 int Which = int(TLIHas) * 2 + int(SDKHas);
325 switch (Which) {
326 case 0: ++TLIandSDKneither; break;
327 case 1: ++TLIdoesntSDKdoes; break;
328 case 2: ++TLIdoesSDKdoesnt; break;
329 case 3: ++TLIandSDKboth; break;
330 }
331 // If the results match, report only if user requested a full report.
332 ReportKind Threshold =
333 TLIHas == SDKHas ? ReportKind::Full : ReportKind::Discrepancy;
334 if (Threshold <= ReportLevel) {
335 constexpr char YesNo[2][4] = {"no ", "yes"};
336 constexpr char Indicator[4][3] = {"!!", ">>", "<<", "=="};
337 outs() << Indicator[Which] << " TLI " << YesNo[TLIHas] << " SDK "
338 << YesNo[SDKHas] << ": ";
339 printPrintableName(OS&: outs(), Name: TLIName);
340 outs() << '\n';
341 }
342 }
343
344 assert(TLIandSDKboth + TLIandSDKneither + TLIdoesSDKdoesnt +
345 TLIdoesntSDKdoes ==
346 LibFunc::End_LibFunc - LibFunc::Begin_LibFunc);
347 (void) TLIandSDKneither;
348 outs() << "<< Total TLI yes SDK no: " << TLIdoesSDKdoesnt
349 << "\n>> Total TLI no SDK yes: " << TLIdoesntSDKdoes
350 << "\n== Total TLI yes SDK yes: " << TLIandSDKboth;
351 if (TLIandSDKboth == 0) {
352 outs() << " *** NO TLI SYMBOLS FOUND";
353 if (SeparateMode)
354 outs() << " in '" << LibList[I] << "'";
355 }
356 outs() << '\n';
357
358 if (!SeparateMode) {
359 if (TLIdoesSDKdoesnt == 0 && TLIdoesntSDKdoes == 0)
360 outs() << "PASS: LLVM TLI matched SDK libraries successfully.\n";
361 else
362 outs() << "FAIL: LLVM TLI doesn't match SDK libraries.\n";
363 }
364 }
365}
366