1//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
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// This program takes in a list of bitcode files, links them and performs
10// link-time optimization according to the provided symbol resolutions using the
11// resolution-based LTO interface, and outputs one or more object files.
12//
13// This program is intended to eventually replace llvm-lto which uses the legacy
14// LTO interface.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/Bitcode/BitcodeReader.h"
20#include "llvm/CodeGen/CommandFlags.h"
21#include "llvm/DTLTO/DTLTO.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/ModuleSummaryIndex.h"
24#include "llvm/LTO/LTO.h"
25#include "llvm/Remarks/HotnessThresholdParser.h"
26#include "llvm/Support/Caching.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/InitLLVM.h"
30#include "llvm/Support/PluginLoader.h"
31#include "llvm/Support/TargetSelect.h"
32#include "llvm/Support/Threading.h"
33#include "llvm/Support/TimeProfiler.h"
34#include <atomic>
35#include <list>
36
37using namespace llvm;
38using namespace lto;
39
40static cl::opt<char>
41 OptLevel("O",
42 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
43 "(default = '-O2')"),
44 cl::Prefix, cl::init(Val: '2'));
45
46static cl::opt<char> CGOptLevel(
47 "cg-opt-level",
48 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
49 cl::init(Val: '2'));
50
51static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
52 cl::desc("<input bitcode files>"));
53
54static cl::opt<std::string> OutputFilename("o", cl::Required,
55 cl::desc("Output filename"),
56 cl::value_desc("filename"));
57
58static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
59 cl::value_desc("directory"));
60
61static cl::opt<std::string> OptPipeline("opt-pipeline",
62 cl::desc("Optimizer Pipeline"),
63 cl::value_desc("pipeline"));
64
65static cl::opt<std::string> AAPipeline("aa-pipeline",
66 cl::desc("Alias Analysis Pipeline"),
67 cl::value_desc("aapipeline"));
68
69static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
70
71static cl::list<std::string> SelectSaveTemps(
72 "select-save-temps",
73 cl::value_desc("One, or multiple of: "
74 "resolution,preopt,promote,internalize,import,opt,precodegen"
75 ",combinedindex"),
76 cl::desc("Save selected temporary files. Cannot be specified together with "
77 "-save-temps"),
78 cl::CommaSeparated);
79
80constexpr const char *SaveTempsValues[] = {
81 "resolution", "preopt", "promote", "internalize",
82 "import", "opt", "precodegen", "combinedindex"};
83
84static cl::opt<bool>
85 ThinLTODistributedIndexes("thinlto-distributed-indexes",
86 cl::desc("Write out individual index and "
87 "import files for the "
88 "distributed backend case"));
89
90static cl::opt<bool>
91 ThinLTOEmitIndexes("thinlto-emit-indexes",
92 cl::desc("Write out individual index files via "
93 "InProcessThinLTO"));
94
95static cl::opt<bool>
96 ThinLTOEmitImports("thinlto-emit-imports",
97 cl::desc("Write out individual imports files via "
98 "InProcessThinLTO. Has no effect unless "
99 "specified with -thinlto-emit-indexes or "
100 "-thinlto-distributed-indexes"));
101
102static cl::opt<std::string> DTLTODistributor(
103 "dtlto-distributor",
104 cl::desc("Distributor to use for ThinLTO backend compilations. Specifying "
105 "this enables DTLTO."));
106
107static cl::list<std::string> DTLTODistributorArgs(
108 "dtlto-distributor-arg", cl::CommaSeparated,
109 cl::desc("Arguments to pass to the DTLTO distributor process."),
110 cl::value_desc("arg"));
111
112static cl::opt<std::string> DTLTOCompiler(
113 "dtlto-compiler",
114 cl::desc("Compiler to use for DTLTO ThinLTO backend compilations."));
115
116static cl::list<std::string> DTLTOCompilerPrependArgs(
117 "dtlto-compiler-prepend-arg", cl::CommaSeparated,
118 cl::desc("Prepend arguments to pass to the remote compiler for backend "
119 "compilations."),
120 cl::value_desc("arg"));
121
122static cl::list<std::string> DTLTOCompilerArgs(
123 "dtlto-compiler-arg", cl::CommaSeparated,
124 cl::desc("Arguments to pass to the remote compiler for backend "
125 "compilations."),
126 cl::value_desc("arg"));
127
128// Default to using all available threads in the system, but using only one
129// thread per core (no SMT).
130// Use -thinlto-threads=all to use hardware_concurrency() instead, which means
131// to use all hardware threads or cores in the system.
132static cl::opt<std::string> Threads("thinlto-threads");
133
134static cl::list<std::string> SymbolResolutions(
135 "r",
136 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
137 "where \"resolution\" is a sequence (which may be empty) of the\n"
138 "following characters:\n"
139 " p - prevailing: the linker has chosen this definition of the\n"
140 " symbol\n"
141 " l - local: the definition of this symbol is unpreemptable at\n"
142 " runtime and is known to be in this linkage unit\n"
143 " x - externally visible: the definition of this symbol is\n"
144 " visible outside of the LTO unit\n"
145 "A resolution for each symbol must be specified"));
146
147static cl::opt<std::string> OverrideTriple(
148 "override-triple",
149 cl::desc("Replace target triples in input files with this triple"));
150
151static cl::opt<std::string> DefaultTriple(
152 "default-triple",
153 cl::desc(
154 "Replace unspecified target triples in input files with this triple"));
155
156static cl::opt<bool> RemarksWithHotness(
157 "pass-remarks-with-hotness",
158 cl::desc("With PGO, include profile count in optimization remarks"),
159 cl::Hidden);
160
161static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
162 RemarksHotnessThreshold(
163 "pass-remarks-hotness-threshold",
164 cl::desc("Minimum profile count required for an "
165 "optimization remark to be output."
166 " Use 'auto' to apply the threshold from profile summary."),
167 cl::value_desc("uint or 'auto'"), cl::init(Val: 0), cl::Hidden);
168
169static cl::opt<std::string>
170 RemarksFilename("pass-remarks-output",
171 cl::desc("Output filename for pass remarks"),
172 cl::value_desc("filename"));
173
174static cl::opt<std::string>
175 RemarksPasses("pass-remarks-filter",
176 cl::desc("Only record optimization remarks from passes whose "
177 "names match the given regular expression"),
178 cl::value_desc("regex"));
179
180static cl::opt<std::string> RemarksFormat(
181 "pass-remarks-format",
182 cl::desc("The format used for serializing remarks (default: YAML)"),
183 cl::value_desc("format"), cl::init(Val: "yaml"));
184
185static cl::opt<std::string>
186 SamplePGOFile("lto-sample-profile-file",
187 cl::desc("Specify a SamplePGO profile file"));
188
189static cl::opt<std::string>
190 CSPGOFile("lto-cspgo-profile-file",
191 cl::desc("Specify a context sensitive PGO profile file"));
192
193static cl::opt<bool>
194 RunCSIRInstr("lto-cspgo-gen",
195 cl::desc("Run PGO context sensitive IR instrumentation"),
196 cl::Hidden);
197
198static cl::opt<bool>
199 DebugPassManager("debug-pass-manager", cl::Hidden,
200 cl::desc("Print pass management debugging information"));
201
202static cl::opt<std::string>
203 StatsFile("stats-file", cl::desc("Filename to write statistics to"));
204
205static cl::list<std::string>
206 PassPlugins("load-pass-plugin",
207 cl::desc("Load passes from plugin library"));
208
209static cl::opt<LTO::LTOKind> UnifiedLTOMode(
210 "unified-lto", cl::desc("Set LTO mode with the following options:"),
211 cl::values(clEnumValN(LTO::LTOK_UnifiedThin, "thin",
212 "ThinLTO with Unified LTO enabled"),
213 clEnumValN(LTO::LTOK_UnifiedRegular, "full",
214 "Regular LTO with Unified LTO enabled"),
215 clEnumValN(LTO::LTOK_Default, "default",
216 "Any LTO mode without Unified LTO")),
217 cl::value_desc("mode"), cl::init(Val: LTO::LTOK_Default));
218
219static cl::opt<bool> EnableFreestanding(
220 "lto-freestanding",
221 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
222 cl::Hidden);
223
224static cl::opt<bool> WholeProgramVisibilityEnabledInLTO(
225 "whole-program-visibility-enabled-in-lto",
226 cl::desc("Enable whole program visibility during LTO"), cl::Hidden);
227
228static cl::opt<bool> ValidateAllVtablesHaveTypeInfos(
229 "validate-all-vtables-have-type-infos",
230 cl::desc("Validate that all vtables have type infos in LTO"), cl::Hidden);
231
232static cl::opt<bool>
233 AllVtablesHaveTypeInfos("all-vtables-have-type-infos", cl::Hidden,
234 cl::desc("All vtables have type infos"));
235
236// Specifying a symbol here states that it is a library symbol that had a
237// definition in bitcode, but was not extracted. Such symbols cannot safely
238// be referenced, since they have already lost their opportunity to be defined.
239//
240// FIXME: Listing all bitcode libfunc symbols here is clunky. A higher-level way
241// to indicate which TUs made it into the link might be better, but this would
242// require more detailed tracking of the sources of constructs in the IR.
243// Alternatively, there may be some other data structure that could hold this
244// information.
245static cl::list<std::string> BitcodeLibFuncs(
246 "bitcode-libfuncs", cl::Hidden,
247 cl::desc("set of unextracted libfuncs implemented in bitcode"));
248
249static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
250
251static cl::opt<unsigned> TimeTraceGranularity(
252 "time-trace-granularity",
253 cl::desc(
254 "Minimum time granularity (in microseconds) traced by time profiler"),
255 cl::init(Val: 500), cl::Hidden);
256
257static cl::opt<std::string>
258 TimeTraceFile("time-trace-file",
259 cl::desc("Specify time trace file destination"),
260 cl::value_desc("filename"));
261
262static void check(Error E, std::string Msg) {
263 if (!E)
264 return;
265 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
266 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
267 });
268 exit(status: 1);
269}
270
271template <typename T> static T check(Expected<T> E, std::string Msg) {
272 if (E)
273 return std::move(*E);
274 check(E.takeError(), Msg);
275 return T();
276}
277
278static void check(std::error_code EC, std::string Msg) {
279 check(E: errorCodeToError(EC), Msg);
280}
281
282template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
283 if (E)
284 return std::move(*E);
285 check(E.getError(), Msg);
286 return T();
287}
288
289static int usage() {
290 errs() << "Available subcommands: dump-symtab run print-guid\n";
291 return 1;
292}
293
294static int run(int argc, char **argv) {
295 cl::LibraryOptionsContext LibraryOptions;
296 cl::parseCommandLineOptions(Context&: LibraryOptions, ToolOptions: codegen::getToolOptions(),
297 Args: ArrayRef(argv, argc),
298 Overview: "Resolution-based LTO test harness");
299
300 if (TimeTrace)
301 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
302 llvm::scope_exit TimeTraceScopeExit([]() {
303 if (TimeTrace) {
304 check(E: timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename),
305 Msg: "timeTraceProfilerWrite failed");
306 timeTraceProfilerCleanup();
307 }
308 });
309
310 // FIXME: Workaround PR30396 which means that a symbol can appear
311 // more than once if it is defined in module-level assembly and
312 // has a GV declaration. We allow (file, symbol) pairs to have multiple
313 // resolutions and apply them in the order observed.
314 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
315 CommandLineResolutions;
316 for (StringRef R : SymbolResolutions) {
317 StringRef Rest, FileName, SymbolName;
318 std::tie(args&: FileName, args&: Rest) = R.split(Separator: ',');
319 if (Rest.empty()) {
320 llvm::errs() << "invalid resolution: " << R << '\n';
321 return 1;
322 }
323 std::tie(args&: SymbolName, args&: Rest) = Rest.split(Separator: ',');
324 SymbolResolution Res;
325 for (char C : Rest) {
326 if (C == 'p')
327 Res.Prevailing = true;
328 else if (C == 'l')
329 Res.FinalDefinitionInLinkageUnit = true;
330 else if (C == 'x')
331 Res.VisibleToRegularObj = true;
332 else if (C == 'r')
333 Res.LinkerRedefined = true;
334 else {
335 llvm::errs() << "invalid character " << C << " in resolution: " << R
336 << '\n';
337 return 1;
338 }
339 }
340 CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}]
341 .push_back(x: Res);
342 }
343
344 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
345
346 Config Conf;
347 Conf.LibraryOptions = &LibraryOptions;
348 if (TimeTrace) {
349 Conf.TimeTraceEnabled = TimeTrace;
350 Conf.TimeTraceGranularity = TimeTraceGranularity;
351 }
352 Conf.CPU = codegen::getMCPU(C: LibraryOptions);
353 Conf.Options = codegen::getTargetOptions(LibraryOptions, TheTriple: Triple());
354 Conf.MAttrs = codegen::getMAttrs(C: LibraryOptions);
355 if (auto RM = codegen::getExplicitRelocModel(C: LibraryOptions))
356 Conf.RelocModel = *RM;
357 Conf.CodeModel = codegen::getExplicitCodeModel(C: LibraryOptions);
358
359 Conf.DebugPassManager = DebugPassManager;
360
361 if (SaveTemps && !SelectSaveTemps.empty()) {
362 llvm::errs() << "-save-temps cannot be specified with -select-save-temps\n";
363 return 1;
364 }
365 if (SaveTemps || !SelectSaveTemps.empty()) {
366 DenseSet<StringRef> SaveTempsArgs;
367 for (auto &S : SelectSaveTemps)
368 if (is_contained(Range: SaveTempsValues, Element: S))
369 SaveTempsArgs.insert(V: S);
370 else {
371 llvm::errs() << ("invalid -select-save-temps argument: " + S) << '\n';
372 return 1;
373 }
374 check(E: Conf.addSaveTemps(OutputFileName: OutputFilename + ".", UseInputModulePath: false, SaveTempsArgs),
375 Msg: "Config::addSaveTemps failed");
376 }
377
378 // Optimization remarks.
379 Conf.RemarksFilename = RemarksFilename;
380 Conf.RemarksPasses = RemarksPasses;
381 Conf.RemarksWithHotness = RemarksWithHotness;
382 Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
383 Conf.RemarksFormat = RemarksFormat;
384
385 Conf.SampleProfile = SamplePGOFile;
386 Conf.CSIRProfile = CSPGOFile;
387 Conf.RunCSIRInstr = RunCSIRInstr;
388
389 // Run a custom pipeline, if asked for.
390 Conf.OptPipeline = OptPipeline;
391 Conf.AAPipeline = AAPipeline;
392
393 Conf.OptLevel = OptLevel - '0';
394 Conf.Freestanding = EnableFreestanding;
395 llvm::append_range(C&: Conf.PassPluginFilenames, R&: PassPlugins);
396 if (auto Level = CodeGenOpt::parseLevel(C: CGOptLevel)) {
397 Conf.CGOptLevel = *Level;
398 } else {
399 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
400 return 1;
401 }
402
403 if (auto FT = codegen::getExplicitFileType(C: LibraryOptions))
404 Conf.CGFileType = *FT;
405
406 Conf.OverrideTriple = OverrideTriple;
407 Conf.DefaultTriple = DefaultTriple;
408 Conf.StatsFile = StatsFile;
409 Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
410 Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
411
412 if (WholeProgramVisibilityEnabledInLTO.getNumOccurrences() > 0)
413 Conf.HasWholeProgramVisibility = WholeProgramVisibilityEnabledInLTO;
414 if (ValidateAllVtablesHaveTypeInfos.getNumOccurrences() > 0)
415 Conf.ValidateAllVtablesHaveTypeInfos = ValidateAllVtablesHaveTypeInfos;
416 if (AllVtablesHaveTypeInfos.getNumOccurrences() > 0)
417 Conf.AllVtablesHaveTypeInfos = AllVtablesHaveTypeInfos;
418
419 if (ThinLTODistributedIndexes && !DTLTODistributor.empty())
420 llvm::errs() << "-thinlto-distributed-indexes cannot be specfied together "
421 "with -dtlto-distributor\n";
422 auto DTLTODistributorArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
423 C&: DTLTODistributorArgs, F: [](const std::string &S) { return StringRef(S); }));
424 auto DTLTOCompilerPrependArgsSV = llvm::to_vector<0>(
425 Range: llvm::map_range(C&: DTLTOCompilerPrependArgs,
426 F: [](const std::string &S) { return StringRef(S); }));
427 auto DTLTOCompilerArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
428 C&: DTLTOCompilerArgs, F: [](const std::string &S) { return StringRef(S); }));
429
430 auto AddStream =
431 [&](size_t Task,
432 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
433 std::string Path = OutputFilename + "." + utostr(X: Task);
434
435 std::error_code EC;
436 auto S = std::make_unique<raw_fd_ostream>(args&: Path, args&: EC, args: sys::fs::OF_None);
437 check(EC, Msg: Path);
438 return std::make_unique<CachedFileStream>(args: std::move(S), args&: Path);
439 };
440
441 auto AddBuffer = [&](size_t Task, const Twine &ModuleName,
442 std::unique_ptr<MemoryBuffer> MB) {
443 auto Stream = AddStream(Task, ModuleName);
444 *Stream->OS << MB->getBuffer();
445 check(E: Stream->commit(), Msg: "Failed to commit cache");
446 };
447
448 ThinBackend Backend;
449 if (ThinLTODistributedIndexes)
450 Backend = createWriteIndexesThinBackend(Parallelism: llvm::hardware_concurrency(Num: Threads),
451 /*OldPrefix=*/"",
452 /*NewPrefix=*/"",
453 /*NativeObjectPrefix=*/"",
454 ShouldEmitImportsFiles: ThinLTOEmitImports,
455 /*LinkedObjectsFile=*/nullptr,
456 /*OnWrite=*/{});
457 else
458 Backend = createInProcessThinBackend(
459 Parallelism: llvm::heavyweight_hardware_concurrency(Num: Threads),
460 /* OnWrite */ {}, ShouldEmitIndexFiles: ThinLTOEmitIndexes, ShouldEmitImportsFiles: ThinLTOEmitImports);
461
462 // Track whether we hit an error; in particular, in the multi-threaded case,
463 // we can't exit() early because the rest of the threads wouldn't have had a
464 // change to be join-ed, and that would result in a "terminate called without
465 // an active exception". Altogether, this results in nondeterministic
466 // behavior. Instead, we don't exit in the multi-threaded case, but we make
467 // sure to report the error and then at the end (after joining cleanly)
468 // exit(1).
469 std::atomic<bool> HasErrors{false};
470 Conf.DiagHandler = [&](const DiagnosticInfo &DI) {
471 DiagnosticPrinterRawOStream DP(errs());
472 DI.print(DP);
473 errs() << '\n';
474 if (DI.getSeverity() == DS_Error)
475 HasErrors = true;
476 };
477
478 LTO::LTOKind LTOMode = UnifiedLTOMode;
479
480 std::unique_ptr<LTO> Lto;
481 if (!DTLTODistributor.empty()) {
482 Lto = std::make_unique<DTLTO>(
483 args: std::move(Conf), args: 1, args&: LTOMode, args: nullptr, args&: ThinLTOEmitIndexes,
484 args&: ThinLTOEmitImports, args&: OutputFilename, args&: DTLTODistributor,
485 args&: DTLTODistributorArgsSV, args&: DTLTOCompiler, args&: DTLTOCompilerPrependArgsSV,
486 args&: DTLTOCompilerArgsSV, args&: AddBuffer, args&: SaveTemps);
487 } else {
488 Lto =
489 std::make_unique<LTO>(args: std::move(Conf), args: std::move(Backend), args: 1, args&: LTOMode);
490 }
491
492 for (std::string F : InputFilenames) {
493 std::unique_ptr<MemoryBuffer> MB = check(E: MemoryBuffer::getFile(Filename: F), Msg: F);
494 std::unique_ptr<InputFile> Input =
495 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: F);
496
497 std::vector<SymbolResolution> Res;
498 for (const InputFile::Symbol &Sym : Input->symbols()) {
499 auto I = CommandLineResolutions.find(x: {F, std::string(Sym.getName())});
500 // If it isn't found, look for ".llvm." (or legacy "."), which would have
501 // been added (followed by a hash) when the symbol was promoted during
502 // module splitting if it was defined in one part and used in the other.
503 // Try looking up the symbol name before the suffix.
504 if (I == CommandLineResolutions.end()) {
505 StringRef OrigName =
506 ModuleSummaryIndex::getOriginalNameBeforePromote(Name: Sym.getName());
507 if (OrigName != Sym.getName())
508 I = CommandLineResolutions.find(x: {F, std::string(OrigName)});
509 if (I == CommandLineResolutions.end()) {
510 auto SplitName = Sym.getName().rsplit(Separator: ".");
511 I = CommandLineResolutions.find(x: {F, std::string(SplitName.first)});
512 }
513 }
514 if (I == CommandLineResolutions.end()) {
515 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
516 << ',' << Sym.getName() << '\n';
517 HasErrors = true;
518 } else {
519 Res.push_back(x: I->second.front());
520 I->second.pop_front();
521 if (I->second.empty())
522 CommandLineResolutions.erase(position: I);
523 }
524 }
525
526 if (HasErrors)
527 continue;
528
529 MBs.push_back(x: std::move(MB));
530 check(E: Lto->add(Obj: std::move(Input), Res), Msg: F);
531 }
532
533 if (!CommandLineResolutions.empty()) {
534 HasErrors = true;
535 for (auto UnusedRes : CommandLineResolutions)
536 llvm::errs() << argv[0] << ": unused symbol resolution for "
537 << UnusedRes.first.first << ',' << UnusedRes.first.second
538 << '\n';
539 }
540 if (HasErrors)
541 return 1;
542
543 Lto->setBitcodeLibFuncs(
544 SmallVector<StringRef>(BitcodeLibFuncs.begin(), BitcodeLibFuncs.end()));
545
546 FileCache Cache;
547 if (!CacheDir.empty())
548 Cache = check(E: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: CacheDir, AddBuffer,
549 CacheFileRename: !DTLTODistributor.empty()),
550 Msg: "failed to create cache");
551
552 check(E: Lto->run(AddStream, Cache), Msg: "LTO::run failed");
553 Lto->waitForCleanup();
554 return static_cast<int>(HasErrors);
555}
556
557static int dumpSymtab(int argc, char **argv) {
558 for (StringRef F : make_range(x: argv + 1, y: argv + argc)) {
559 std::unique_ptr<MemoryBuffer> MB =
560 check(E: MemoryBuffer::getFile(Filename: F), Msg: std::string(F));
561 BitcodeFileContents BFC =
562 check(E: getBitcodeFileContents(Buffer: *MB), Msg: std::string(F));
563
564 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
565 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
566 BFC.Symtab.data());
567 outs() << "version: " << Hdr->Version << '\n';
568 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
569 outs() << "producer: " << Hdr->Producer.get(Strtab: BFC.StrtabForSymtab)
570 << '\n';
571 }
572
573 std::unique_ptr<InputFile> Input =
574 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: std::string(F));
575
576 outs() << "target triple: " << Input->getTargetTriple() << '\n';
577 Triple TT(Input->getTargetTriple());
578
579 outs() << "source filename: " << Input->getSourceFileName() << '\n';
580
581 if (TT.isOSBinFormatCOFF())
582 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
583
584 if (TT.isOSBinFormatELF()) {
585 outs() << "dependent libraries:";
586 for (auto L : Input->getDependentLibraries())
587 outs() << " \"" << L << "\"";
588 outs() << '\n';
589 }
590
591 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable =
592 Input->getComdatTable();
593 for (const InputFile::Symbol &Sym : Input->symbols()) {
594 switch (Sym.getVisibility()) {
595 case GlobalValue::HiddenVisibility:
596 outs() << 'H';
597 break;
598 case GlobalValue::ProtectedVisibility:
599 outs() << 'P';
600 break;
601 case GlobalValue::DefaultVisibility:
602 outs() << 'D';
603 break;
604 }
605
606 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
607 PrintBool('U', Sym.isUndefined());
608 PrintBool('C', Sym.isCommon());
609 PrintBool('W', Sym.isWeak());
610 PrintBool('I', Sym.isIndirect());
611 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
612 PrintBool('T', Sym.isTLS());
613 PrintBool('X', Sym.isExecutable());
614 outs() << ' ' << Sym.getName() << '\n';
615
616 if (Sym.isCommon())
617 outs() << " size " << Sym.getCommonSize() << " align "
618 << Sym.getCommonAlignment() << '\n';
619
620 int Comdat = Sym.getComdatIndex();
621 if (Comdat != -1) {
622 outs() << " comdat ";
623 switch (ComdatTable[Comdat].second) {
624 case Comdat::Any:
625 outs() << "any";
626 break;
627 case Comdat::ExactMatch:
628 outs() << "exactmatch";
629 break;
630 case Comdat::Largest:
631 outs() << "largest";
632 break;
633 case Comdat::NoDeduplicate:
634 outs() << "nodeduplicate";
635 break;
636 case Comdat::SameSize:
637 outs() << "samesize";
638 break;
639 }
640 outs() << ' ' << ComdatTable[Comdat].first << '\n';
641 }
642
643 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
644 outs() << " fallback " << Sym.getCOFFWeakExternalFallback()
645 << '\n';
646
647 if (!Sym.getSectionName().empty())
648 outs() << " section " << Sym.getSectionName() << "\n";
649 }
650
651 outs() << '\n';
652 }
653
654 return 0;
655}
656
657int main(int argc, char **argv) {
658 InitLLVM X(argc, argv);
659 InitializeAllTargets();
660 InitializeAllTargetMCs();
661 InitializeAllAsmPrinters();
662 InitializeAllAsmParsers();
663
664 // FIXME: This should use llvm::cl subcommands, but it isn't currently
665 // possible to pass an argument not associated with a subcommand to a
666 // subcommand (e.g. -use-new-pm).
667 if (argc < 2)
668 return usage();
669
670 StringRef Subcommand = argv[1];
671 // Ensure that argv[0] is correct after adjusting argv/argc.
672 argv[1] = argv[0];
673 if (Subcommand == "dump-symtab")
674 return dumpSymtab(argc: argc - 1, argv: argv + 1);
675 if (Subcommand == "run")
676 return run(argc: argc - 1, argv: argv + 1);
677 if (Subcommand == "print-guid" && argc > 2) {
678 // Note the name of the function we're calling: this won't return the right
679 // answer for internal linkage symbols.
680 outs() << GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: argv[2]) << '\n';
681 return 0;
682 }
683 if (Subcommand == "--version") {
684 cl::PrintVersionMessage();
685 return 0;
686 }
687 return usage();
688}
689