blob: aab0f6f303a4a02ab064ee754ee2114c74bd2c30 [file] [log] [blame]
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program takes in a list of bitcode files, links them and performs
11// link-time optimization according to the provided symbol resolutions using the
12// resolution-based LTO interface, and outputs one or more object files.
13//
14// This program is intended to eventually replace llvm-lto which uses the legacy
15// LTO interface.
16//
17//===----------------------------------------------------------------------===//
18
Peter Collingbourne99b98c22017-06-27 23:50:24 +000019#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000020#include "llvm/CodeGen/CommandFlags.inc"
Mehdi Amini14f19bd2016-12-23 23:54:17 +000021#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbourne99b98c22017-06-27 23:50:24 +000022#include "llvm/LTO/Caching.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000023#include "llvm/LTO/LTO.h"
24#include "llvm/Support/CommandLine.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000025#include "llvm/Support/FileSystem.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026#include "llvm/Support/TargetSelect.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000027#include "llvm/Support/Threading.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028
29using namespace llvm;
30using namespace lto;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031
Teresa Johnson002af9b2016-10-31 22:12:21 +000032static cl::opt<char>
33 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
34 "(default = '-O2')"),
35 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
36
Peter Collingbournef4257522016-12-08 05:28:30 +000037static cl::opt<char> CGOptLevel(
38 "cg-opt-level",
39 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
40 cl::init('2'));
41
Teresa Johnson9ba95f92016-08-11 14:58:12 +000042static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
43 cl::desc("<input bitcode files>"));
44
45static cl::opt<std::string> OutputFilename("o", cl::Required,
46 cl::desc("Output filename"),
47 cl::value_desc("filename"));
48
Mehdi Aminiadc0e262016-08-23 21:30:12 +000049static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
50 cl::value_desc("directory"));
51
Davide Italianoec9612d2016-09-07 17:46:16 +000052static cl::opt<std::string> OptPipeline("opt-pipeline",
53 cl::desc("Optimizer Pipeline"),
54 cl::value_desc("pipeline"));
55
Davide Italiano14e9e8a2016-09-16 21:03:21 +000056static cl::opt<std::string> AAPipeline("aa-pipeline",
57 cl::desc("Alias Analysis Pipeline"),
58 cl::value_desc("aapipeline"));
59
Teresa Johnson9ba95f92016-08-11 14:58:12 +000060static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
61
Mehdi Amini458f8052016-08-19 23:54:40 +000062static cl::opt<bool>
63 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
64 cl::desc("Write out individual index and "
65 "import files for the "
66 "distributed backend case"));
67
Mehdi Amini95c1f912016-12-23 23:54:34 +000068static cl::opt<int> Threads("thinlto-threads",
Teresa Johnsonec544c52016-10-19 17:35:01 +000069 cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini458f8052016-08-19 23:54:40 +000070
Teresa Johnson9ba95f92016-08-11 14:58:12 +000071static cl::list<std::string> SymbolResolutions(
72 "r",
73 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
74 "where \"resolution\" is a sequence (which may be empty) of the\n"
75 "following characters:\n"
76 " p - prevailing: the linker has chosen this definition of the\n"
77 " symbol\n"
78 " l - local: the definition of this symbol is unpreemptable at\n"
79 " runtime and is known to be in this linkage unit\n"
80 " x - externally visible: the definition of this symbol is\n"
81 " visible outside of the LTO unit\n"
82 "A resolution for each symbol must be specified."),
83 cl::ZeroOrMore);
84
Peter Collingbournef4257522016-12-08 05:28:30 +000085static cl::opt<std::string> OverrideTriple(
86 "override-triple",
87 cl::desc("Replace target triples in input files with this triple"));
88
89static cl::opt<std::string> DefaultTriple(
90 "default-triple",
91 cl::desc(
92 "Replace unspecified target triples in input files with this triple"));
93
Davide Italianoebd47192017-02-12 03:31:30 +000094static cl::opt<std::string>
95 OptRemarksOutput("pass-remarks-output",
96 cl::desc("YAML output file for optimization remarks"));
97
Davide Italianocd6d7b12017-02-13 16:08:36 +000098static cl::opt<bool> OptRemarksWithHotness(
Davide Italiano6cb6f992017-02-12 05:05:35 +000099 "pass-remarks-with-hotness",
100 cl::desc("Whether to include hotness informations in the remarks.\n"
101 "Has effect only if -pass-remarks-output is specified."));
102
Tobias Edler von Koch819d8402017-07-28 23:43:22 +0000103static cl::opt<std::string>
104 SamplePGOFile("lto-sample-profile-file",
105 cl::desc("Specify a SamplePGO profile file"));
106
Tim Shen4e912aa2017-06-01 23:13:44 +0000107static cl::opt<bool>
108 UseNewPM("use-new-pm",
109 cl::desc("Run LTO passes using the new pass manager"),
110 cl::init(false), cl::Hidden);
111
Dehao Chen3246dc32017-08-02 03:03:19 +0000112static cl::opt<bool>
113 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
114 cl::desc("Print pass management debugging information"));
115
Florian Hahnd4332eb2018-04-20 10:18:36 +0000116static cl::opt<std::string>
117 StatsFile("stats-file", cl::desc("Filename to write statistics to"));
118
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000119static void check(Error E, std::string Msg) {
120 if (!E)
121 return;
122 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
Davide Italianofb6ed912017-02-12 03:42:09 +0000123 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000124 });
125 exit(1);
126}
127
128template <typename T> static T check(Expected<T> E, std::string Msg) {
129 if (E)
130 return std::move(*E);
131 check(E.takeError(), Msg);
132 return T();
133}
134
135static void check(std::error_code EC, std::string Msg) {
136 check(errorCodeToError(EC), Msg);
137}
138
139template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
140 if (E)
141 return std::move(*E);
142 check(E.getError(), Msg);
143 return T();
144}
145
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000146static int usage() {
Peter Collingbourne94baec62017-04-12 18:27:00 +0000147 errs() << "Available subcommands: dump-symtab run\n";
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000148 return 1;
149}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000150
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000151static int run(int argc, char **argv) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000152 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
153
Peter Collingbournea5b71642016-11-30 23:19:05 +0000154 // FIXME: Workaround PR30396 which means that a symbol can appear
155 // more than once if it is defined in module-level assembly and
156 // has a GV declaration. We allow (file, symbol) pairs to have multiple
157 // resolutions and apply them in the order observed.
158 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000159 CommandLineResolutions;
160 for (std::string R : SymbolResolutions) {
161 StringRef Rest = R;
162 StringRef FileName, SymbolName;
163 std::tie(FileName, Rest) = Rest.split(',');
164 if (Rest.empty()) {
165 llvm::errs() << "invalid resolution: " << R << '\n';
166 return 1;
167 }
168 std::tie(SymbolName, Rest) = Rest.split(',');
169 SymbolResolution Res;
170 for (char C : Rest) {
171 if (C == 'p')
172 Res.Prevailing = true;
173 else if (C == 'l')
174 Res.FinalDefinitionInLinkageUnit = true;
175 else if (C == 'x')
176 Res.VisibleToRegularObj = true;
Dmitry Mikulindb3b87b2017-06-05 16:24:25 +0000177 else if (C == 'r')
178 Res.LinkerRedefined = true;
Teresa Johnsona404d142017-03-07 18:15:13 +0000179 else {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000180 llvm::errs() << "invalid character " << C << " in resolution: " << R
181 << '\n';
Teresa Johnsona404d142017-03-07 18:15:13 +0000182 return 1;
183 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000184 }
Peter Collingbournea5b71642016-11-30 23:19:05 +0000185 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000186 }
187
188 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
189
190 Config Conf;
Mehdi Amini14f19bd2016-12-23 23:54:17 +0000191 Conf.DiagHandler = [](const DiagnosticInfo &DI) {
192 DiagnosticPrinterRawOStream DP(errs());
193 DI.print(DP);
194 errs() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000195 exit(1);
196 };
197
Peter Collingbournef4257522016-12-08 05:28:30 +0000198 Conf.CPU = MCPU;
199 Conf.Options = InitTargetOptionsFromCodeGenFlags();
200 Conf.MAttrs = MAttrs;
201 if (auto RM = getRelocModel())
202 Conf.RelocModel = *RM;
Rafael Espindola79e238a2017-08-03 02:16:21 +0000203 Conf.CodeModel = getCodeModel();
Peter Collingbournef4257522016-12-08 05:28:30 +0000204
Dehao Chen3246dc32017-08-02 03:03:19 +0000205 Conf.DebugPassManager = DebugPassManager;
206
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000207 if (SaveTemps)
Mehdi Aminieccffad2016-08-18 00:12:33 +0000208 check(Conf.addSaveTemps(OutputFilename + "."),
209 "Config::addSaveTemps failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000210
Davide Italianoebd47192017-02-12 03:31:30 +0000211 // Optimization remarks.
212 Conf.RemarksFilename = OptRemarksOutput;
Davide Italianocd6d7b12017-02-13 16:08:36 +0000213 Conf.RemarksWithHotness = OptRemarksWithHotness;
Davide Italianoebd47192017-02-12 03:31:30 +0000214
Tobias Edler von Koch819d8402017-07-28 23:43:22 +0000215 Conf.SampleProfile = SamplePGOFile;
216
Davide Italianoec9612d2016-09-07 17:46:16 +0000217 // Run a custom pipeline, if asked for.
218 Conf.OptPipeline = OptPipeline;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000219 Conf.AAPipeline = AAPipeline;
Davide Italianoec9612d2016-09-07 17:46:16 +0000220
Teresa Johnson002af9b2016-10-31 22:12:21 +0000221 Conf.OptLevel = OptLevel - '0';
Tim Shen4e912aa2017-06-01 23:13:44 +0000222 Conf.UseNewPM = UseNewPM;
Peter Collingbournef4257522016-12-08 05:28:30 +0000223 switch (CGOptLevel) {
224 case '0':
225 Conf.CGOptLevel = CodeGenOpt::None;
226 break;
227 case '1':
228 Conf.CGOptLevel = CodeGenOpt::Less;
229 break;
230 case '2':
231 Conf.CGOptLevel = CodeGenOpt::Default;
232 break;
233 case '3':
234 Conf.CGOptLevel = CodeGenOpt::Aggressive;
235 break;
236 default:
237 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
238 return 1;
239 }
240
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000241 if (FileType.getNumOccurrences())
242 Conf.CGFileType = FileType;
243
Peter Collingbournef4257522016-12-08 05:28:30 +0000244 Conf.OverrideTriple = OverrideTriple;
245 Conf.DefaultTriple = DefaultTriple;
Florian Hahnd4332eb2018-04-20 10:18:36 +0000246 Conf.StatsFile = StatsFile;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000247
Mehdi Amini458f8052016-08-19 23:54:40 +0000248 ThinBackend Backend;
249 if (ThinLTODistributedIndexes)
Vitaly Bukaa139b692018-02-22 19:06:15 +0000250 Backend = createWriteIndexesThinBackend(/* OldPrefix */ "",
251 /* NewPrefix */ "",
252 /* ShouldEmitImportsFiles */ true,
253 /* LinkedObjectsFile */ nullptr,
254 /* OnWrite */ {});
Mehdi Amini458f8052016-08-19 23:54:40 +0000255 else
256 Backend = createInProcessThinBackend(Threads);
257 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000258
259 bool HasErrors = false;
260 for (std::string F : InputFilenames) {
261 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
262 std::unique_ptr<InputFile> Input =
263 check(InputFile::create(MB->getMemBufferRef()), F);
264
265 std::vector<SymbolResolution> Res;
266 for (const InputFile::Symbol &Sym : Input->symbols()) {
267 auto I = CommandLineResolutions.find({F, Sym.getName()});
268 if (I == CommandLineResolutions.end()) {
269 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
270 << ',' << Sym.getName() << '\n';
271 HasErrors = true;
272 } else {
Peter Collingbournea5b71642016-11-30 23:19:05 +0000273 Res.push_back(I->second.front());
274 I->second.pop_front();
275 if (I->second.empty())
276 CommandLineResolutions.erase(I);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 }
278 }
279
280 if (HasErrors)
281 continue;
282
283 MBs.push_back(std::move(MB));
284 check(Lto.add(std::move(Input), Res), F);
285 }
286
287 if (!CommandLineResolutions.empty()) {
288 HasErrors = true;
289 for (auto UnusedRes : CommandLineResolutions)
290 llvm::errs() << argv[0] << ": unused symbol resolution for "
291 << UnusedRes.first.first << ',' << UnusedRes.first.second
292 << '\n';
293 }
294 if (HasErrors)
295 return 1;
296
Peter Collingbourne80186a52016-09-23 21:33:43 +0000297 auto AddStream =
298 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000299 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000300
Peter Collingbourne80186a52016-09-23 21:33:43 +0000301 std::error_code EC;
302 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
303 check(EC, Path);
304 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305 };
306
Teresa Johnsona344fd32018-02-20 20:21:53 +0000307 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Peter Collingbourne128423f2017-03-17 00:34:07 +0000308 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne80186a52016-09-23 21:33:43 +0000309 };
310
311 NativeObjectCache Cache;
312 if (!CacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000313 Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
Peter Collingbourne80186a52016-09-23 21:33:43 +0000314
315 check(Lto.run(AddStream, Cache), "LTO::run failed");
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000316 return 0;
317}
318
Peter Collingbourne94baec62017-04-12 18:27:00 +0000319static int dumpSymtab(int argc, char **argv) {
320 for (StringRef F : make_range(argv + 1, argv + argc)) {
321 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
Peter Collingbourne99b98c22017-06-27 23:50:24 +0000322 BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F);
323
324 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
325 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
326 BFC.Symtab.data());
327 outs() << "version: " << Hdr->Version << '\n';
328 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
329 outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
330 << '\n';
331 }
332
Peter Collingbourne94baec62017-04-12 18:27:00 +0000333 std::unique_ptr<InputFile> Input =
334 check(InputFile::create(MB->getMemBufferRef()), F);
335
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000336 outs() << "target triple: " << Input->getTargetTriple() << '\n';
337 Triple TT(Input->getTargetTriple());
338
Peter Collingbourne94baec62017-04-12 18:27:00 +0000339 outs() << "source filename: " << Input->getSourceFileName() << '\n';
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000340
341 if (TT.isOSBinFormatCOFF())
342 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000343
344 std::vector<StringRef> ComdatTable = Input->getComdatTable();
345 for (const InputFile::Symbol &Sym : Input->symbols()) {
346 switch (Sym.getVisibility()) {
347 case GlobalValue::HiddenVisibility:
348 outs() << 'H';
349 break;
350 case GlobalValue::ProtectedVisibility:
351 outs() << 'P';
352 break;
353 case GlobalValue::DefaultVisibility:
354 outs() << 'D';
355 break;
356 }
357
358 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
359 PrintBool('U', Sym.isUndefined());
360 PrintBool('C', Sym.isCommon());
361 PrintBool('W', Sym.isWeak());
362 PrintBool('I', Sym.isIndirect());
363 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
364 PrintBool('T', Sym.isTLS());
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000365 PrintBool('X', Sym.isExecutable());
Peter Collingbourne94baec62017-04-12 18:27:00 +0000366 outs() << ' ' << Sym.getName() << '\n';
367
368 if (Sym.isCommon())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000369 outs() << " size " << Sym.getCommonSize() << " align "
Peter Collingbourne94baec62017-04-12 18:27:00 +0000370 << Sym.getCommonAlignment() << '\n';
371
372 int Comdat = Sym.getComdatIndex();
373 if (Comdat != -1)
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000374 outs() << " comdat " << ComdatTable[Comdat] << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000375
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000376 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000377 outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000378
379 if (!Sym.getSectionName().empty())
380 outs() << " section " << Sym.getSectionName() << "\n";
Peter Collingbourne94baec62017-04-12 18:27:00 +0000381 }
382
383 outs() << '\n';
384 }
385
386 return 0;
387}
388
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000389int main(int argc, char **argv) {
390 InitializeAllTargets();
391 InitializeAllTargetMCs();
392 InitializeAllAsmPrinters();
393 InitializeAllAsmParsers();
394
395 // FIXME: This should use llvm::cl subcommands, but it isn't currently
396 // possible to pass an argument not associated with a subcommand to a
Tim Shen4e912aa2017-06-01 23:13:44 +0000397 // subcommand (e.g. -use-new-pm).
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000398 if (argc < 2)
399 return usage();
400
401 StringRef Subcommand = argv[1];
402 // Ensure that argv[0] is correct after adjusting argv/argc.
403 argv[1] = argv[0];
Peter Collingbourne94baec62017-04-12 18:27:00 +0000404 if (Subcommand == "dump-symtab")
405 return dumpSymtab(argc - 1, argv + 1);
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000406 if (Subcommand == "run")
407 return run(argc - 1, argv + 1);
408 return usage();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409}