blob: bbfece517c801915c618605234f2b53b32421d2f [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
Mehdi Aminiadc0e262016-08-23 21:30:12 +000019#include "llvm/LTO/Caching.h"
Peter Collingbournef4257522016-12-08 05:28:30 +000020#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini14f19bd2016-12-23 23:54:17 +000021#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000022#include "llvm/LTO/LTO.h"
23#include "llvm/Support/CommandLine.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000024#include "llvm/Support/FileSystem.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000025#include "llvm/Support/TargetSelect.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000026#include "llvm/Support/Threading.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000027
28using namespace llvm;
29using namespace lto;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030
Teresa Johnson002af9b2016-10-31 22:12:21 +000031static cl::opt<char>
32 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
33 "(default = '-O2')"),
34 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
35
Peter Collingbournef4257522016-12-08 05:28:30 +000036static cl::opt<char> CGOptLevel(
37 "cg-opt-level",
38 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
39 cl::init('2'));
40
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
42 cl::desc("<input bitcode files>"));
43
44static cl::opt<std::string> OutputFilename("o", cl::Required,
45 cl::desc("Output filename"),
46 cl::value_desc("filename"));
47
Mehdi Aminiadc0e262016-08-23 21:30:12 +000048static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
49 cl::value_desc("directory"));
50
Davide Italianoec9612d2016-09-07 17:46:16 +000051static cl::opt<std::string> OptPipeline("opt-pipeline",
52 cl::desc("Optimizer Pipeline"),
53 cl::value_desc("pipeline"));
54
Davide Italiano14e9e8a2016-09-16 21:03:21 +000055static cl::opt<std::string> AAPipeline("aa-pipeline",
56 cl::desc("Alias Analysis Pipeline"),
57 cl::value_desc("aapipeline"));
58
Teresa Johnson9ba95f92016-08-11 14:58:12 +000059static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
60
Mehdi Amini458f8052016-08-19 23:54:40 +000061static cl::opt<bool>
62 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
63 cl::desc("Write out individual index and "
64 "import files for the "
65 "distributed backend case"));
66
Mehdi Amini95c1f912016-12-23 23:54:34 +000067static cl::opt<int> Threads("thinlto-threads",
Teresa Johnsonec544c52016-10-19 17:35:01 +000068 cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini458f8052016-08-19 23:54:40 +000069
Teresa Johnson9ba95f92016-08-11 14:58:12 +000070static cl::list<std::string> SymbolResolutions(
71 "r",
72 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
73 "where \"resolution\" is a sequence (which may be empty) of the\n"
74 "following characters:\n"
75 " p - prevailing: the linker has chosen this definition of the\n"
76 " symbol\n"
77 " l - local: the definition of this symbol is unpreemptable at\n"
78 " runtime and is known to be in this linkage unit\n"
79 " x - externally visible: the definition of this symbol is\n"
80 " visible outside of the LTO unit\n"
81 "A resolution for each symbol must be specified."),
82 cl::ZeroOrMore);
83
Peter Collingbournef4257522016-12-08 05:28:30 +000084static cl::opt<std::string> OverrideTriple(
85 "override-triple",
86 cl::desc("Replace target triples in input files with this triple"));
87
88static cl::opt<std::string> DefaultTriple(
89 "default-triple",
90 cl::desc(
91 "Replace unspecified target triples in input files with this triple"));
92
Davide Italianoebd47192017-02-12 03:31:30 +000093static cl::opt<std::string>
94 OptRemarksOutput("pass-remarks-output",
95 cl::desc("YAML output file for optimization remarks"));
96
Davide Italianocd6d7b12017-02-13 16:08:36 +000097static cl::opt<bool> OptRemarksWithHotness(
Davide Italiano6cb6f992017-02-12 05:05:35 +000098 "pass-remarks-with-hotness",
99 cl::desc("Whether to include hotness informations in the remarks.\n"
100 "Has effect only if -pass-remarks-output is specified."));
101
Tim Shen4e912aa2017-06-01 23:13:44 +0000102static cl::opt<bool>
103 UseNewPM("use-new-pm",
104 cl::desc("Run LTO passes using the new pass manager"),
105 cl::init(false), cl::Hidden);
106
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000107static void check(Error E, std::string Msg) {
108 if (!E)
109 return;
110 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
Davide Italianofb6ed912017-02-12 03:42:09 +0000111 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000112 });
113 exit(1);
114}
115
116template <typename T> static T check(Expected<T> E, std::string Msg) {
117 if (E)
118 return std::move(*E);
119 check(E.takeError(), Msg);
120 return T();
121}
122
123static void check(std::error_code EC, std::string Msg) {
124 check(errorCodeToError(EC), Msg);
125}
126
127template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
128 if (E)
129 return std::move(*E);
130 check(E.getError(), Msg);
131 return T();
132}
133
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000134static int usage() {
Peter Collingbourne94baec62017-04-12 18:27:00 +0000135 errs() << "Available subcommands: dump-symtab run\n";
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000136 return 1;
137}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000138
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000139static int run(int argc, char **argv) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000140 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
141
Peter Collingbournea5b71642016-11-30 23:19:05 +0000142 // FIXME: Workaround PR30396 which means that a symbol can appear
143 // more than once if it is defined in module-level assembly and
144 // has a GV declaration. We allow (file, symbol) pairs to have multiple
145 // resolutions and apply them in the order observed.
146 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000147 CommandLineResolutions;
148 for (std::string R : SymbolResolutions) {
149 StringRef Rest = R;
150 StringRef FileName, SymbolName;
151 std::tie(FileName, Rest) = Rest.split(',');
152 if (Rest.empty()) {
153 llvm::errs() << "invalid resolution: " << R << '\n';
154 return 1;
155 }
156 std::tie(SymbolName, Rest) = Rest.split(',');
157 SymbolResolution Res;
158 for (char C : Rest) {
159 if (C == 'p')
160 Res.Prevailing = true;
161 else if (C == 'l')
162 Res.FinalDefinitionInLinkageUnit = true;
163 else if (C == 'x')
164 Res.VisibleToRegularObj = true;
Dmitry Mikulindb3b87b2017-06-05 16:24:25 +0000165 else if (C == 'r')
166 Res.LinkerRedefined = true;
Teresa Johnsona404d142017-03-07 18:15:13 +0000167 else {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000168 llvm::errs() << "invalid character " << C << " in resolution: " << R
169 << '\n';
Teresa Johnsona404d142017-03-07 18:15:13 +0000170 return 1;
171 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000172 }
Peter Collingbournea5b71642016-11-30 23:19:05 +0000173 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000174 }
175
176 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
177
178 Config Conf;
Mehdi Amini14f19bd2016-12-23 23:54:17 +0000179 Conf.DiagHandler = [](const DiagnosticInfo &DI) {
180 DiagnosticPrinterRawOStream DP(errs());
181 DI.print(DP);
182 errs() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000183 exit(1);
184 };
185
Peter Collingbournef4257522016-12-08 05:28:30 +0000186 Conf.CPU = MCPU;
187 Conf.Options = InitTargetOptionsFromCodeGenFlags();
188 Conf.MAttrs = MAttrs;
189 if (auto RM = getRelocModel())
190 Conf.RelocModel = *RM;
191 Conf.CodeModel = CMModel;
192
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000193 if (SaveTemps)
Mehdi Aminieccffad2016-08-18 00:12:33 +0000194 check(Conf.addSaveTemps(OutputFilename + "."),
195 "Config::addSaveTemps failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000196
Davide Italianoebd47192017-02-12 03:31:30 +0000197 // Optimization remarks.
198 Conf.RemarksFilename = OptRemarksOutput;
Davide Italianocd6d7b12017-02-13 16:08:36 +0000199 Conf.RemarksWithHotness = OptRemarksWithHotness;
Davide Italianoebd47192017-02-12 03:31:30 +0000200
Davide Italianoec9612d2016-09-07 17:46:16 +0000201 // Run a custom pipeline, if asked for.
202 Conf.OptPipeline = OptPipeline;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000203 Conf.AAPipeline = AAPipeline;
Davide Italianoec9612d2016-09-07 17:46:16 +0000204
Teresa Johnson002af9b2016-10-31 22:12:21 +0000205 Conf.OptLevel = OptLevel - '0';
Tim Shen4e912aa2017-06-01 23:13:44 +0000206 Conf.UseNewPM = UseNewPM;
Peter Collingbournef4257522016-12-08 05:28:30 +0000207 switch (CGOptLevel) {
208 case '0':
209 Conf.CGOptLevel = CodeGenOpt::None;
210 break;
211 case '1':
212 Conf.CGOptLevel = CodeGenOpt::Less;
213 break;
214 case '2':
215 Conf.CGOptLevel = CodeGenOpt::Default;
216 break;
217 case '3':
218 Conf.CGOptLevel = CodeGenOpt::Aggressive;
219 break;
220 default:
221 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
222 return 1;
223 }
224
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000225 if (FileType.getNumOccurrences())
226 Conf.CGFileType = FileType;
227
Peter Collingbournef4257522016-12-08 05:28:30 +0000228 Conf.OverrideTriple = OverrideTriple;
229 Conf.DefaultTriple = DefaultTriple;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000230
Mehdi Amini458f8052016-08-19 23:54:40 +0000231 ThinBackend Backend;
232 if (ThinLTODistributedIndexes)
233 Backend = createWriteIndexesThinBackend("", "", true, "");
234 else
235 Backend = createInProcessThinBackend(Threads);
236 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237
238 bool HasErrors = false;
239 for (std::string F : InputFilenames) {
240 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
241 std::unique_ptr<InputFile> Input =
242 check(InputFile::create(MB->getMemBufferRef()), F);
243
244 std::vector<SymbolResolution> Res;
245 for (const InputFile::Symbol &Sym : Input->symbols()) {
246 auto I = CommandLineResolutions.find({F, Sym.getName()});
247 if (I == CommandLineResolutions.end()) {
248 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
249 << ',' << Sym.getName() << '\n';
250 HasErrors = true;
251 } else {
Peter Collingbournea5b71642016-11-30 23:19:05 +0000252 Res.push_back(I->second.front());
253 I->second.pop_front();
254 if (I->second.empty())
255 CommandLineResolutions.erase(I);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000256 }
257 }
258
259 if (HasErrors)
260 continue;
261
262 MBs.push_back(std::move(MB));
263 check(Lto.add(std::move(Input), Res), F);
264 }
265
266 if (!CommandLineResolutions.empty()) {
267 HasErrors = true;
268 for (auto UnusedRes : CommandLineResolutions)
269 llvm::errs() << argv[0] << ": unused symbol resolution for "
270 << UnusedRes.first.first << ',' << UnusedRes.first.second
271 << '\n';
272 }
273 if (HasErrors)
274 return 1;
275
Peter Collingbourne80186a52016-09-23 21:33:43 +0000276 auto AddStream =
277 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000278 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000279
Peter Collingbourne80186a52016-09-23 21:33:43 +0000280 std::error_code EC;
281 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
282 check(EC, Path);
283 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000284 };
285
Peter Collingbourne128423f2017-03-17 00:34:07 +0000286 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
287 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne80186a52016-09-23 21:33:43 +0000288 };
289
290 NativeObjectCache Cache;
291 if (!CacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000292 Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
Peter Collingbourne80186a52016-09-23 21:33:43 +0000293
294 check(Lto.run(AddStream, Cache), "LTO::run failed");
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000295 return 0;
296}
297
Peter Collingbourne94baec62017-04-12 18:27:00 +0000298static int dumpSymtab(int argc, char **argv) {
299 for (StringRef F : make_range(argv + 1, argv + argc)) {
300 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
301 std::unique_ptr<InputFile> Input =
302 check(InputFile::create(MB->getMemBufferRef()), F);
303
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000304 outs() << "target triple: " << Input->getTargetTriple() << '\n';
305 Triple TT(Input->getTargetTriple());
306
Peter Collingbourne94baec62017-04-12 18:27:00 +0000307 outs() << "source filename: " << Input->getSourceFileName() << '\n';
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000308
309 if (TT.isOSBinFormatCOFF())
310 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000311
312 std::vector<StringRef> ComdatTable = Input->getComdatTable();
313 for (const InputFile::Symbol &Sym : Input->symbols()) {
314 switch (Sym.getVisibility()) {
315 case GlobalValue::HiddenVisibility:
316 outs() << 'H';
317 break;
318 case GlobalValue::ProtectedVisibility:
319 outs() << 'P';
320 break;
321 case GlobalValue::DefaultVisibility:
322 outs() << 'D';
323 break;
324 }
325
326 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
327 PrintBool('U', Sym.isUndefined());
328 PrintBool('C', Sym.isCommon());
329 PrintBool('W', Sym.isWeak());
330 PrintBool('I', Sym.isIndirect());
331 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
332 PrintBool('T', Sym.isTLS());
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000333 PrintBool('X', Sym.isExecutable());
Peter Collingbourne94baec62017-04-12 18:27:00 +0000334 outs() << ' ' << Sym.getName() << '\n';
335
336 if (Sym.isCommon())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000337 outs() << " size " << Sym.getCommonSize() << " align "
Peter Collingbourne94baec62017-04-12 18:27:00 +0000338 << Sym.getCommonAlignment() << '\n';
339
340 int Comdat = Sym.getComdatIndex();
341 if (Comdat != -1)
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000342 outs() << " comdat " << ComdatTable[Comdat] << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000343
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000344 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000345 outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000346 }
347
348 outs() << '\n';
349 }
350
351 return 0;
352}
353
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000354int main(int argc, char **argv) {
355 InitializeAllTargets();
356 InitializeAllTargetMCs();
357 InitializeAllAsmPrinters();
358 InitializeAllAsmParsers();
359
360 // FIXME: This should use llvm::cl subcommands, but it isn't currently
361 // possible to pass an argument not associated with a subcommand to a
Tim Shen4e912aa2017-06-01 23:13:44 +0000362 // subcommand (e.g. -use-new-pm).
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000363 if (argc < 2)
364 return usage();
365
366 StringRef Subcommand = argv[1];
367 // Ensure that argv[0] is correct after adjusting argv/argc.
368 argv[1] = argv[0];
Peter Collingbourne94baec62017-04-12 18:27:00 +0000369 if (Subcommand == "dump-symtab")
370 return dumpSymtab(argc - 1, argv + 1);
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000371 if (Subcommand == "run")
372 return run(argc - 1, argv + 1);
373 return usage();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374}