blob: 7a8d40553384b0f44dfcc97814f68811ecf0ee2e [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
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102static void check(Error E, std::string Msg) {
103 if (!E)
104 return;
105 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
Davide Italianofb6ed912017-02-12 03:42:09 +0000106 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000107 });
108 exit(1);
109}
110
111template <typename T> static T check(Expected<T> E, std::string Msg) {
112 if (E)
113 return std::move(*E);
114 check(E.takeError(), Msg);
115 return T();
116}
117
118static void check(std::error_code EC, std::string Msg) {
119 check(errorCodeToError(EC), Msg);
120}
121
122template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
123 if (E)
124 return std::move(*E);
125 check(E.getError(), Msg);
126 return T();
127}
128
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000129static int usage() {
Peter Collingbourne94baec62017-04-12 18:27:00 +0000130 errs() << "Available subcommands: dump-symtab run\n";
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000131 return 1;
132}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000133
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000134static int run(int argc, char **argv) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000135 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
136
Peter Collingbournea5b71642016-11-30 23:19:05 +0000137 // FIXME: Workaround PR30396 which means that a symbol can appear
138 // more than once if it is defined in module-level assembly and
139 // has a GV declaration. We allow (file, symbol) pairs to have multiple
140 // resolutions and apply them in the order observed.
141 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000142 CommandLineResolutions;
143 for (std::string R : SymbolResolutions) {
144 StringRef Rest = R;
145 StringRef FileName, SymbolName;
146 std::tie(FileName, Rest) = Rest.split(',');
147 if (Rest.empty()) {
148 llvm::errs() << "invalid resolution: " << R << '\n';
149 return 1;
150 }
151 std::tie(SymbolName, Rest) = Rest.split(',');
152 SymbolResolution Res;
153 for (char C : Rest) {
154 if (C == 'p')
155 Res.Prevailing = true;
156 else if (C == 'l')
157 Res.FinalDefinitionInLinkageUnit = true;
158 else if (C == 'x')
159 Res.VisibleToRegularObj = true;
Teresa Johnsona404d142017-03-07 18:15:13 +0000160 else {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000161 llvm::errs() << "invalid character " << C << " in resolution: " << R
162 << '\n';
Teresa Johnsona404d142017-03-07 18:15:13 +0000163 return 1;
164 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000165 }
Peter Collingbournea5b71642016-11-30 23:19:05 +0000166 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000167 }
168
169 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
170
171 Config Conf;
Mehdi Amini14f19bd2016-12-23 23:54:17 +0000172 Conf.DiagHandler = [](const DiagnosticInfo &DI) {
173 DiagnosticPrinterRawOStream DP(errs());
174 DI.print(DP);
175 errs() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000176 exit(1);
177 };
178
Peter Collingbournef4257522016-12-08 05:28:30 +0000179 Conf.CPU = MCPU;
180 Conf.Options = InitTargetOptionsFromCodeGenFlags();
181 Conf.MAttrs = MAttrs;
182 if (auto RM = getRelocModel())
183 Conf.RelocModel = *RM;
184 Conf.CodeModel = CMModel;
185
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000186 if (SaveTemps)
Mehdi Aminieccffad2016-08-18 00:12:33 +0000187 check(Conf.addSaveTemps(OutputFilename + "."),
188 "Config::addSaveTemps failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000189
Davide Italianoebd47192017-02-12 03:31:30 +0000190 // Optimization remarks.
191 Conf.RemarksFilename = OptRemarksOutput;
Davide Italianocd6d7b12017-02-13 16:08:36 +0000192 Conf.RemarksWithHotness = OptRemarksWithHotness;
Davide Italianoebd47192017-02-12 03:31:30 +0000193
Davide Italianoec9612d2016-09-07 17:46:16 +0000194 // Run a custom pipeline, if asked for.
195 Conf.OptPipeline = OptPipeline;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000196 Conf.AAPipeline = AAPipeline;
Davide Italianoec9612d2016-09-07 17:46:16 +0000197
Teresa Johnson002af9b2016-10-31 22:12:21 +0000198 Conf.OptLevel = OptLevel - '0';
Peter Collingbournef4257522016-12-08 05:28:30 +0000199 switch (CGOptLevel) {
200 case '0':
201 Conf.CGOptLevel = CodeGenOpt::None;
202 break;
203 case '1':
204 Conf.CGOptLevel = CodeGenOpt::Less;
205 break;
206 case '2':
207 Conf.CGOptLevel = CodeGenOpt::Default;
208 break;
209 case '3':
210 Conf.CGOptLevel = CodeGenOpt::Aggressive;
211 break;
212 default:
213 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
214 return 1;
215 }
216
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000217 if (FileType.getNumOccurrences())
218 Conf.CGFileType = FileType;
219
Peter Collingbournef4257522016-12-08 05:28:30 +0000220 Conf.OverrideTriple = OverrideTriple;
221 Conf.DefaultTriple = DefaultTriple;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000222
Mehdi Amini458f8052016-08-19 23:54:40 +0000223 ThinBackend Backend;
224 if (ThinLTODistributedIndexes)
225 Backend = createWriteIndexesThinBackend("", "", true, "");
226 else
227 Backend = createInProcessThinBackend(Threads);
228 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000229
230 bool HasErrors = false;
231 for (std::string F : InputFilenames) {
232 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
233 std::unique_ptr<InputFile> Input =
234 check(InputFile::create(MB->getMemBufferRef()), F);
235
236 std::vector<SymbolResolution> Res;
237 for (const InputFile::Symbol &Sym : Input->symbols()) {
238 auto I = CommandLineResolutions.find({F, Sym.getName()});
239 if (I == CommandLineResolutions.end()) {
240 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
241 << ',' << Sym.getName() << '\n';
242 HasErrors = true;
243 } else {
Peter Collingbournea5b71642016-11-30 23:19:05 +0000244 Res.push_back(I->second.front());
245 I->second.pop_front();
246 if (I->second.empty())
247 CommandLineResolutions.erase(I);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000248 }
249 }
250
251 if (HasErrors)
252 continue;
253
254 MBs.push_back(std::move(MB));
255 check(Lto.add(std::move(Input), Res), F);
256 }
257
258 if (!CommandLineResolutions.empty()) {
259 HasErrors = true;
260 for (auto UnusedRes : CommandLineResolutions)
261 llvm::errs() << argv[0] << ": unused symbol resolution for "
262 << UnusedRes.first.first << ',' << UnusedRes.first.second
263 << '\n';
264 }
265 if (HasErrors)
266 return 1;
267
Peter Collingbourne80186a52016-09-23 21:33:43 +0000268 auto AddStream =
269 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000270 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000271
Peter Collingbourne80186a52016-09-23 21:33:43 +0000272 std::error_code EC;
273 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
274 check(EC, Path);
275 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276 };
277
Peter Collingbourne128423f2017-03-17 00:34:07 +0000278 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
279 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne80186a52016-09-23 21:33:43 +0000280 };
281
282 NativeObjectCache Cache;
283 if (!CacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000284 Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
Peter Collingbourne80186a52016-09-23 21:33:43 +0000285
286 check(Lto.run(AddStream, Cache), "LTO::run failed");
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000287 return 0;
288}
289
Peter Collingbourne94baec62017-04-12 18:27:00 +0000290static int dumpSymtab(int argc, char **argv) {
291 for (StringRef F : make_range(argv + 1, argv + argc)) {
292 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
293 std::unique_ptr<InputFile> Input =
294 check(InputFile::create(MB->getMemBufferRef()), F);
295
296 outs() << "source filename: " << Input->getSourceFileName() << '\n';
297 outs() << "linker opts (COFF only): " << Input->getCOFFLinkerOpts() << '\n';
298
299 std::vector<StringRef> ComdatTable = Input->getComdatTable();
300 for (const InputFile::Symbol &Sym : Input->symbols()) {
301 switch (Sym.getVisibility()) {
302 case GlobalValue::HiddenVisibility:
303 outs() << 'H';
304 break;
305 case GlobalValue::ProtectedVisibility:
306 outs() << 'P';
307 break;
308 case GlobalValue::DefaultVisibility:
309 outs() << 'D';
310 break;
311 }
312
313 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
314 PrintBool('U', Sym.isUndefined());
315 PrintBool('C', Sym.isCommon());
316 PrintBool('W', Sym.isWeak());
317 PrintBool('I', Sym.isIndirect());
318 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
319 PrintBool('T', Sym.isTLS());
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000320 PrintBool('X', Sym.isExecutable());
Peter Collingbourne94baec62017-04-12 18:27:00 +0000321 outs() << ' ' << Sym.getName() << '\n';
322
323 if (Sym.isCommon())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000324 outs() << " size " << Sym.getCommonSize() << " align "
Peter Collingbourne94baec62017-04-12 18:27:00 +0000325 << Sym.getCommonAlignment() << '\n';
326
327 int Comdat = Sym.getComdatIndex();
328 if (Comdat != -1)
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000329 outs() << " comdat " << ComdatTable[Comdat] << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000330
331 if (Sym.isWeak() && Sym.isIndirect())
Tobias Edler von Koch90df1f482017-04-13 16:24:14 +0000332 outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
Peter Collingbourne94baec62017-04-12 18:27:00 +0000333 }
334
335 outs() << '\n';
336 }
337
338 return 0;
339}
340
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000341int main(int argc, char **argv) {
342 InitializeAllTargets();
343 InitializeAllTargetMCs();
344 InitializeAllAsmPrinters();
345 InitializeAllAsmParsers();
346
347 // FIXME: This should use llvm::cl subcommands, but it isn't currently
348 // possible to pass an argument not associated with a subcommand to a
349 // subcommand (e.g. -lto-use-new-pm).
350 if (argc < 2)
351 return usage();
352
353 StringRef Subcommand = argv[1];
354 // Ensure that argv[0] is correct after adjusting argv/argc.
355 argv[1] = argv[0];
Peter Collingbourne94baec62017-04-12 18:27:00 +0000356 if (Subcommand == "dump-symtab")
357 return dumpSymtab(argc - 1, argv + 1);
Peter Collingbourne7faa60c2017-04-11 18:12:00 +0000358 if (Subcommand == "run")
359 return run(argc - 1, argv + 1);
360 return usage();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361}