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/IR/DiagnosticPrinter.h"
22#include "llvm/LTO/LTO.h"
23#include "llvm/Plugins/PassPlugin.h"
24#include "llvm/Remarks/HotnessThresholdParser.h"
25#include "llvm/Support/Caching.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/InitLLVM.h"
29#include "llvm/Support/PluginLoader.h"
30#include "llvm/Support/TargetSelect.h"
31#include "llvm/Support/Threading.h"
32#include "llvm/Support/TimeProfiler.h"
33#include <atomic>
34
35using namespace llvm;
36using namespace lto;
37
38static codegen::RegisterCodeGenFlags CGF;
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::Optional,
211 cl::desc("Set LTO mode with the following options:"),
212 cl::values(clEnumValN(LTO::LTOK_UnifiedThin, "thin",
213 "ThinLTO with Unified LTO enabled"),
214 clEnumValN(LTO::LTOK_UnifiedRegular, "full",
215 "Regular LTO with Unified LTO enabled"),
216 clEnumValN(LTO::LTOK_Default, "default",
217 "Any LTO mode without Unified LTO")),
218 cl::value_desc("mode"), cl::init(Val: LTO::LTOK_Default));
219
220static cl::opt<bool> EnableFreestanding(
221 "lto-freestanding",
222 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
223 cl::Hidden);
224
225static cl::opt<bool> WholeProgramVisibilityEnabledInLTO(
226 "whole-program-visibility-enabled-in-lto",
227 cl::desc("Enable whole program visibility during LTO"), cl::Hidden);
228
229static cl::opt<bool> ValidateAllVtablesHaveTypeInfos(
230 "validate-all-vtables-have-type-infos",
231 cl::desc("Validate that all vtables have type infos in LTO"), cl::Hidden);
232
233static cl::opt<bool>
234 AllVtablesHaveTypeInfos("all-vtables-have-type-infos", cl::Hidden,
235 cl::desc("All vtables have type infos"));
236
237static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
238
239static cl::opt<unsigned> TimeTraceGranularity(
240 "time-trace-granularity",
241 cl::desc(
242 "Minimum time granularity (in microseconds) traced by time profiler"),
243 cl::init(Val: 500), cl::Hidden);
244
245static cl::opt<std::string>
246 TimeTraceFile("time-trace-file",
247 cl::desc("Specify time trace file destination"),
248 cl::value_desc("filename"));
249
250static void check(Error E, std::string Msg) {
251 if (!E)
252 return;
253 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
254 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
255 });
256 exit(status: 1);
257}
258
259template <typename T> static T check(Expected<T> E, std::string Msg) {
260 if (E)
261 return std::move(*E);
262 check(E.takeError(), Msg);
263 return T();
264}
265
266static void check(std::error_code EC, std::string Msg) {
267 check(E: errorCodeToError(EC), Msg);
268}
269
270template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
271 if (E)
272 return std::move(*E);
273 check(E.getError(), Msg);
274 return T();
275}
276
277static int usage() {
278 errs() << "Available subcommands: dump-symtab run print-guid\n";
279 return 1;
280}
281
282static int run(int argc, char **argv) {
283 cl::ParseCommandLineOptions(argc, argv, Overview: "Resolution-based LTO test harness");
284
285 if (TimeTrace)
286 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
287 llvm::scope_exit TimeTraceScopeExit([]() {
288 if (TimeTrace) {
289 check(E: timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename),
290 Msg: "timeTraceProfilerWrite failed");
291 timeTraceProfilerCleanup();
292 }
293 });
294
295 // FIXME: Workaround PR30396 which means that a symbol can appear
296 // more than once if it is defined in module-level assembly and
297 // has a GV declaration. We allow (file, symbol) pairs to have multiple
298 // resolutions and apply them in the order observed.
299 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
300 CommandLineResolutions;
301 for (StringRef R : SymbolResolutions) {
302 StringRef Rest, FileName, SymbolName;
303 std::tie(args&: FileName, args&: Rest) = R.split(Separator: ',');
304 if (Rest.empty()) {
305 llvm::errs() << "invalid resolution: " << R << '\n';
306 return 1;
307 }
308 std::tie(args&: SymbolName, args&: Rest) = Rest.split(Separator: ',');
309 SymbolResolution Res;
310 for (char C : Rest) {
311 if (C == 'p')
312 Res.Prevailing = true;
313 else if (C == 'l')
314 Res.FinalDefinitionInLinkageUnit = true;
315 else if (C == 'x')
316 Res.VisibleToRegularObj = true;
317 else if (C == 'r')
318 Res.LinkerRedefined = true;
319 else {
320 llvm::errs() << "invalid character " << C << " in resolution: " << R
321 << '\n';
322 return 1;
323 }
324 }
325 CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}]
326 .push_back(x: Res);
327 }
328
329 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
330
331 Config Conf;
332 if (TimeTrace) {
333 Conf.TimeTraceEnabled = TimeTrace;
334 Conf.TimeTraceGranularity = TimeTraceGranularity;
335 }
336 Conf.CPU = codegen::getMCPU();
337 Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
338 Conf.MAttrs = codegen::getMAttrs();
339 if (auto RM = codegen::getExplicitRelocModel())
340 Conf.RelocModel = *RM;
341 Conf.CodeModel = codegen::getExplicitCodeModel();
342
343 Conf.DebugPassManager = DebugPassManager;
344
345 if (SaveTemps && !SelectSaveTemps.empty()) {
346 llvm::errs() << "-save-temps cannot be specified with -select-save-temps\n";
347 return 1;
348 }
349 if (SaveTemps || !SelectSaveTemps.empty()) {
350 DenseSet<StringRef> SaveTempsArgs;
351 for (auto &S : SelectSaveTemps)
352 if (is_contained(Range: SaveTempsValues, Element: S))
353 SaveTempsArgs.insert(V: S);
354 else {
355 llvm::errs() << ("invalid -select-save-temps argument: " + S) << '\n';
356 return 1;
357 }
358 check(E: Conf.addSaveTemps(OutputFileName: OutputFilename + ".", UseInputModulePath: false, SaveTempsArgs),
359 Msg: "Config::addSaveTemps failed");
360 }
361
362 // Optimization remarks.
363 Conf.RemarksFilename = RemarksFilename;
364 Conf.RemarksPasses = RemarksPasses;
365 Conf.RemarksWithHotness = RemarksWithHotness;
366 Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
367 Conf.RemarksFormat = RemarksFormat;
368
369 Conf.SampleProfile = SamplePGOFile;
370 Conf.CSIRProfile = CSPGOFile;
371 Conf.RunCSIRInstr = RunCSIRInstr;
372
373 // Run a custom pipeline, if asked for.
374 Conf.OptPipeline = OptPipeline;
375 Conf.AAPipeline = AAPipeline;
376
377 Conf.OptLevel = OptLevel - '0';
378 Conf.Freestanding = EnableFreestanding;
379 llvm::append_range(C&: Conf.PassPlugins, R&: PassPlugins);
380 if (auto Level = CodeGenOpt::parseLevel(C: CGOptLevel)) {
381 Conf.CGOptLevel = *Level;
382 } else {
383 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
384 return 1;
385 }
386
387 if (auto FT = codegen::getExplicitFileType())
388 Conf.CGFileType = *FT;
389
390 Conf.OverrideTriple = OverrideTriple;
391 Conf.DefaultTriple = DefaultTriple;
392 Conf.StatsFile = StatsFile;
393 Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
394 Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
395
396 if (WholeProgramVisibilityEnabledInLTO.getNumOccurrences() > 0)
397 Conf.HasWholeProgramVisibility = WholeProgramVisibilityEnabledInLTO;
398 if (ValidateAllVtablesHaveTypeInfos.getNumOccurrences() > 0)
399 Conf.ValidateAllVtablesHaveTypeInfos = ValidateAllVtablesHaveTypeInfos;
400 if (AllVtablesHaveTypeInfos.getNumOccurrences() > 0)
401 Conf.AllVtablesHaveTypeInfos = AllVtablesHaveTypeInfos;
402
403 if (ThinLTODistributedIndexes && !DTLTODistributor.empty())
404 llvm::errs() << "-thinlto-distributed-indexes cannot be specfied together "
405 "with -dtlto-distributor\n";
406 auto DTLTODistributorArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
407 C&: DTLTODistributorArgs, F: [](const std::string &S) { return StringRef(S); }));
408 auto DTLTOCompilerPrependArgsSV = llvm::to_vector<0>(
409 Range: llvm::map_range(C&: DTLTOCompilerPrependArgs,
410 F: [](const std::string &S) { return StringRef(S); }));
411 auto DTLTOCompilerArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
412 C&: DTLTOCompilerArgs, F: [](const std::string &S) { return StringRef(S); }));
413
414 ThinBackend Backend;
415 if (ThinLTODistributedIndexes)
416 Backend = createWriteIndexesThinBackend(Parallelism: llvm::hardware_concurrency(Num: Threads),
417 /*OldPrefix=*/"",
418 /*NewPrefix=*/"",
419 /*NativeObjectPrefix=*/"",
420 ShouldEmitImportsFiles: ThinLTOEmitImports,
421 /*LinkedObjectsFile=*/nullptr,
422 /*OnWrite=*/{});
423 else if (!DTLTODistributor.empty()) {
424 Backend = createOutOfProcessThinBackend(
425 Parallelism: llvm::heavyweight_hardware_concurrency(Num: Threads),
426 /*OnWrite=*/{}, ShouldEmitIndexFiles: ThinLTOEmitIndexes, ShouldEmitImportsFiles: ThinLTOEmitImports, LinkerOutputFile: OutputFilename,
427 Distributor: DTLTODistributor, DistributorArgs: DTLTODistributorArgsSV, RemoteCompiler: DTLTOCompiler,
428 RemoteCompilerPrependArgs: DTLTOCompilerPrependArgsSV, RemoteCompilerArgs: DTLTOCompilerArgsSV, SaveTemps);
429 } else
430 Backend = createInProcessThinBackend(
431 Parallelism: llvm::heavyweight_hardware_concurrency(Num: Threads),
432 /* OnWrite */ {}, ShouldEmitIndexFiles: ThinLTOEmitIndexes, ShouldEmitImportsFiles: ThinLTOEmitImports);
433
434 // Track whether we hit an error; in particular, in the multi-threaded case,
435 // we can't exit() early because the rest of the threads wouldn't have had a
436 // change to be join-ed, and that would result in a "terminate called without
437 // an active exception". Altogether, this results in nondeterministic
438 // behavior. Instead, we don't exit in the multi-threaded case, but we make
439 // sure to report the error and then at the end (after joining cleanly)
440 // exit(1).
441 std::atomic<bool> HasErrors{false};
442 Conf.DiagHandler = [&](const DiagnosticInfo &DI) {
443 DiagnosticPrinterRawOStream DP(errs());
444 DI.print(DP);
445 errs() << '\n';
446 if (DI.getSeverity() == DS_Error)
447 HasErrors = true;
448 };
449
450 LTO::LTOKind LTOMode = UnifiedLTOMode;
451
452 LTO Lto(std::move(Conf), std::move(Backend), 1, LTOMode);
453
454 for (std::string F : InputFilenames) {
455 std::unique_ptr<MemoryBuffer> MB = check(E: MemoryBuffer::getFile(Filename: F), Msg: F);
456 std::unique_ptr<InputFile> Input =
457 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: F);
458
459 std::vector<SymbolResolution> Res;
460 for (const InputFile::Symbol &Sym : Input->symbols()) {
461 auto I = CommandLineResolutions.find(x: {F, std::string(Sym.getName())});
462 // If it isn't found, look for ".", which would have been added
463 // (followed by a hash) when the symbol was promoted during module
464 // splitting if it was defined in one part and used in the other.
465 // Try looking up the symbol name before the suffix.
466 if (I == CommandLineResolutions.end()) {
467 auto SplitName = Sym.getName().rsplit(Separator: ".");
468 I = CommandLineResolutions.find(x: {F, std::string(SplitName.first)});
469 }
470 if (I == CommandLineResolutions.end()) {
471 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
472 << ',' << Sym.getName() << '\n';
473 HasErrors = true;
474 } else {
475 Res.push_back(x: I->second.front());
476 I->second.pop_front();
477 if (I->second.empty())
478 CommandLineResolutions.erase(position: I);
479 }
480 }
481
482 if (HasErrors)
483 continue;
484
485 MBs.push_back(x: std::move(MB));
486 check(E: Lto.add(Obj: std::move(Input), Res), Msg: F);
487 }
488
489 if (!CommandLineResolutions.empty()) {
490 HasErrors = true;
491 for (auto UnusedRes : CommandLineResolutions)
492 llvm::errs() << argv[0] << ": unused symbol resolution for "
493 << UnusedRes.first.first << ',' << UnusedRes.first.second
494 << '\n';
495 }
496 if (HasErrors)
497 return 1;
498
499 auto AddStream =
500 [&](size_t Task,
501 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
502 std::string Path = OutputFilename + "." + utostr(X: Task);
503
504 std::error_code EC;
505 auto S = std::make_unique<raw_fd_ostream>(args&: Path, args&: EC, args: sys::fs::OF_None);
506 check(EC, Msg: Path);
507 return std::make_unique<CachedFileStream>(args: std::move(S), args&: Path);
508 };
509
510 auto AddBuffer = [&](size_t Task, const Twine &ModuleName,
511 std::unique_ptr<MemoryBuffer> MB) {
512 auto Stream = AddStream(Task, ModuleName);
513 *Stream->OS << MB->getBuffer();
514 check(E: Stream->commit(), Msg: "Failed to commit cache");
515 };
516
517 FileCache Cache;
518 if (!CacheDir.empty())
519 Cache = check(E: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: CacheDir, AddBuffer),
520 Msg: "failed to create cache");
521
522 check(E: Lto.run(AddStream, Cache), Msg: "LTO::run failed");
523 return static_cast<int>(HasErrors);
524}
525
526static int dumpSymtab(int argc, char **argv) {
527 for (StringRef F : make_range(x: argv + 1, y: argv + argc)) {
528 std::unique_ptr<MemoryBuffer> MB =
529 check(E: MemoryBuffer::getFile(Filename: F), Msg: std::string(F));
530 BitcodeFileContents BFC =
531 check(E: getBitcodeFileContents(Buffer: *MB), Msg: std::string(F));
532
533 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
534 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
535 BFC.Symtab.data());
536 outs() << "version: " << Hdr->Version << '\n';
537 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
538 outs() << "producer: " << Hdr->Producer.get(Strtab: BFC.StrtabForSymtab)
539 << '\n';
540 }
541
542 std::unique_ptr<InputFile> Input =
543 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: std::string(F));
544
545 outs() << "target triple: " << Input->getTargetTriple() << '\n';
546 Triple TT(Input->getTargetTriple());
547
548 outs() << "source filename: " << Input->getSourceFileName() << '\n';
549
550 if (TT.isOSBinFormatCOFF())
551 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
552
553 if (TT.isOSBinFormatELF()) {
554 outs() << "dependent libraries:";
555 for (auto L : Input->getDependentLibraries())
556 outs() << " \"" << L << "\"";
557 outs() << '\n';
558 }
559
560 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable =
561 Input->getComdatTable();
562 for (const InputFile::Symbol &Sym : Input->symbols()) {
563 switch (Sym.getVisibility()) {
564 case GlobalValue::HiddenVisibility:
565 outs() << 'H';
566 break;
567 case GlobalValue::ProtectedVisibility:
568 outs() << 'P';
569 break;
570 case GlobalValue::DefaultVisibility:
571 outs() << 'D';
572 break;
573 }
574
575 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
576 PrintBool('U', Sym.isUndefined());
577 PrintBool('C', Sym.isCommon());
578 PrintBool('W', Sym.isWeak());
579 PrintBool('I', Sym.isIndirect());
580 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
581 PrintBool('T', Sym.isTLS());
582 PrintBool('X', Sym.isExecutable());
583 outs() << ' ' << Sym.getName() << '\n';
584
585 if (Sym.isCommon())
586 outs() << " size " << Sym.getCommonSize() << " align "
587 << Sym.getCommonAlignment() << '\n';
588
589 int Comdat = Sym.getComdatIndex();
590 if (Comdat != -1) {
591 outs() << " comdat ";
592 switch (ComdatTable[Comdat].second) {
593 case Comdat::Any:
594 outs() << "any";
595 break;
596 case Comdat::ExactMatch:
597 outs() << "exactmatch";
598 break;
599 case Comdat::Largest:
600 outs() << "largest";
601 break;
602 case Comdat::NoDeduplicate:
603 outs() << "nodeduplicate";
604 break;
605 case Comdat::SameSize:
606 outs() << "samesize";
607 break;
608 }
609 outs() << ' ' << ComdatTable[Comdat].first << '\n';
610 }
611
612 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
613 outs() << " fallback " << Sym.getCOFFWeakExternalFallback()
614 << '\n';
615
616 if (!Sym.getSectionName().empty())
617 outs() << " section " << Sym.getSectionName() << "\n";
618 }
619
620 outs() << '\n';
621 }
622
623 return 0;
624}
625
626int main(int argc, char **argv) {
627 InitLLVM X(argc, argv);
628 InitializeAllTargets();
629 InitializeAllTargetMCs();
630 InitializeAllAsmPrinters();
631 InitializeAllAsmParsers();
632
633 // FIXME: This should use llvm::cl subcommands, but it isn't currently
634 // possible to pass an argument not associated with a subcommand to a
635 // subcommand (e.g. -use-new-pm).
636 if (argc < 2)
637 return usage();
638
639 StringRef Subcommand = argv[1];
640 // Ensure that argv[0] is correct after adjusting argv/argc.
641 argv[1] = argv[0];
642 if (Subcommand == "dump-symtab")
643 return dumpSymtab(argc: argc - 1, argv: argv + 1);
644 if (Subcommand == "run")
645 return run(argc: argc - 1, argv: argv + 1);
646 if (Subcommand == "print-guid" && argc > 2) {
647 // Note the name of the function we're calling: this won't return the right
648 // answer for internal linkage symbols.
649 outs() << GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: argv[2]) << '\n';
650 return 0;
651 }
652 if (Subcommand == "--version") {
653 cl::PrintVersionMessage();
654 return 0;
655 }
656 return usage();
657}
658