blob: e8bf7a397f2f1231078f532427711de96e56a381 [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"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000021#include "llvm/LTO/LTO.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/TargetSelect.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000024#include "llvm/Support/Threading.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000025
26using namespace llvm;
27using namespace lto;
28using namespace object;
29
Teresa Johnson002af9b2016-10-31 22:12:21 +000030static cl::opt<char>
31 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
32 "(default = '-O2')"),
33 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
34
Peter Collingbournef4257522016-12-08 05:28:30 +000035static cl::opt<char> CGOptLevel(
36 "cg-opt-level",
37 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
38 cl::init('2'));
39
Teresa Johnson9ba95f92016-08-11 14:58:12 +000040static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
41 cl::desc("<input bitcode files>"));
42
43static cl::opt<std::string> OutputFilename("o", cl::Required,
44 cl::desc("Output filename"),
45 cl::value_desc("filename"));
46
Mehdi Aminiadc0e262016-08-23 21:30:12 +000047static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
48 cl::value_desc("directory"));
49
Davide Italianoec9612d2016-09-07 17:46:16 +000050static cl::opt<std::string> OptPipeline("opt-pipeline",
51 cl::desc("Optimizer Pipeline"),
52 cl::value_desc("pipeline"));
53
Davide Italiano14e9e8a2016-09-16 21:03:21 +000054static cl::opt<std::string> AAPipeline("aa-pipeline",
55 cl::desc("Alias Analysis Pipeline"),
56 cl::value_desc("aapipeline"));
57
Teresa Johnson9ba95f92016-08-11 14:58:12 +000058static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
59
Mehdi Amini458f8052016-08-19 23:54:40 +000060static cl::opt<bool>
61 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
62 cl::desc("Write out individual index and "
63 "import files for the "
64 "distributed backend case"));
65
66static cl::opt<int> Threads("-thinlto-threads",
Teresa Johnsonec544c52016-10-19 17:35:01 +000067 cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini458f8052016-08-19 23:54:40 +000068
Teresa Johnson9ba95f92016-08-11 14:58:12 +000069static cl::list<std::string> SymbolResolutions(
70 "r",
71 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
72 "where \"resolution\" is a sequence (which may be empty) of the\n"
73 "following characters:\n"
74 " p - prevailing: the linker has chosen this definition of the\n"
75 " symbol\n"
76 " l - local: the definition of this symbol is unpreemptable at\n"
77 " runtime and is known to be in this linkage unit\n"
78 " x - externally visible: the definition of this symbol is\n"
79 " visible outside of the LTO unit\n"
80 "A resolution for each symbol must be specified."),
81 cl::ZeroOrMore);
82
Peter Collingbournef4257522016-12-08 05:28:30 +000083static cl::opt<std::string> OverrideTriple(
84 "override-triple",
85 cl::desc("Replace target triples in input files with this triple"));
86
87static cl::opt<std::string> DefaultTriple(
88 "default-triple",
89 cl::desc(
90 "Replace unspecified target triples in input files with this triple"));
91
Teresa Johnson9ba95f92016-08-11 14:58:12 +000092static void check(Error E, std::string Msg) {
93 if (!E)
94 return;
95 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
96 errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n';
97 });
98 exit(1);
99}
100
101template <typename T> static T check(Expected<T> E, std::string Msg) {
102 if (E)
103 return std::move(*E);
104 check(E.takeError(), Msg);
105 return T();
106}
107
108static void check(std::error_code EC, std::string Msg) {
109 check(errorCodeToError(EC), Msg);
110}
111
112template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
113 if (E)
114 return std::move(*E);
115 check(E.getError(), Msg);
116 return T();
117}
118
119int main(int argc, char **argv) {
120 InitializeAllTargets();
121 InitializeAllTargetMCs();
122 InitializeAllAsmPrinters();
123 InitializeAllAsmParsers();
124
125 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
126
Peter Collingbournea5b71642016-11-30 23:19:05 +0000127 // FIXME: Workaround PR30396 which means that a symbol can appear
128 // more than once if it is defined in module-level assembly and
129 // has a GV declaration. We allow (file, symbol) pairs to have multiple
130 // resolutions and apply them in the order observed.
131 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000132 CommandLineResolutions;
133 for (std::string R : SymbolResolutions) {
134 StringRef Rest = R;
135 StringRef FileName, SymbolName;
136 std::tie(FileName, Rest) = Rest.split(',');
137 if (Rest.empty()) {
138 llvm::errs() << "invalid resolution: " << R << '\n';
139 return 1;
140 }
141 std::tie(SymbolName, Rest) = Rest.split(',');
142 SymbolResolution Res;
143 for (char C : Rest) {
144 if (C == 'p')
145 Res.Prevailing = true;
146 else if (C == 'l')
147 Res.FinalDefinitionInLinkageUnit = true;
148 else if (C == 'x')
149 Res.VisibleToRegularObj = true;
150 else
151 llvm::errs() << "invalid character " << C << " in resolution: " << R
152 << '\n';
153 }
Peter Collingbournea5b71642016-11-30 23:19:05 +0000154 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000155 }
156
157 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
158
159 Config Conf;
160 Conf.DiagHandler = [](const DiagnosticInfo &) {
161 exit(1);
162 };
163
Peter Collingbournef4257522016-12-08 05:28:30 +0000164 Conf.CPU = MCPU;
165 Conf.Options = InitTargetOptionsFromCodeGenFlags();
166 Conf.MAttrs = MAttrs;
167 if (auto RM = getRelocModel())
168 Conf.RelocModel = *RM;
169 Conf.CodeModel = CMModel;
170
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000171 if (SaveTemps)
Mehdi Aminieccffad2016-08-18 00:12:33 +0000172 check(Conf.addSaveTemps(OutputFilename + "."),
173 "Config::addSaveTemps failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000174
Davide Italianoec9612d2016-09-07 17:46:16 +0000175 // Run a custom pipeline, if asked for.
176 Conf.OptPipeline = OptPipeline;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000177 Conf.AAPipeline = AAPipeline;
Davide Italianoec9612d2016-09-07 17:46:16 +0000178
Teresa Johnson002af9b2016-10-31 22:12:21 +0000179 Conf.OptLevel = OptLevel - '0';
Peter Collingbournef4257522016-12-08 05:28:30 +0000180 switch (CGOptLevel) {
181 case '0':
182 Conf.CGOptLevel = CodeGenOpt::None;
183 break;
184 case '1':
185 Conf.CGOptLevel = CodeGenOpt::Less;
186 break;
187 case '2':
188 Conf.CGOptLevel = CodeGenOpt::Default;
189 break;
190 case '3':
191 Conf.CGOptLevel = CodeGenOpt::Aggressive;
192 break;
193 default:
194 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
195 return 1;
196 }
197
198 Conf.OverrideTriple = OverrideTriple;
199 Conf.DefaultTriple = DefaultTriple;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000200
Mehdi Amini458f8052016-08-19 23:54:40 +0000201 ThinBackend Backend;
202 if (ThinLTODistributedIndexes)
203 Backend = createWriteIndexesThinBackend("", "", true, "");
204 else
205 Backend = createInProcessThinBackend(Threads);
206 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000207
208 bool HasErrors = false;
209 for (std::string F : InputFilenames) {
210 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
211 std::unique_ptr<InputFile> Input =
212 check(InputFile::create(MB->getMemBufferRef()), F);
213
214 std::vector<SymbolResolution> Res;
215 for (const InputFile::Symbol &Sym : Input->symbols()) {
216 auto I = CommandLineResolutions.find({F, Sym.getName()});
217 if (I == CommandLineResolutions.end()) {
218 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
219 << ',' << Sym.getName() << '\n';
220 HasErrors = true;
221 } else {
Peter Collingbournea5b71642016-11-30 23:19:05 +0000222 Res.push_back(I->second.front());
223 I->second.pop_front();
224 if (I->second.empty())
225 CommandLineResolutions.erase(I);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000226 }
227 }
228
229 if (HasErrors)
230 continue;
231
232 MBs.push_back(std::move(MB));
233 check(Lto.add(std::move(Input), Res), F);
234 }
235
236 if (!CommandLineResolutions.empty()) {
237 HasErrors = true;
238 for (auto UnusedRes : CommandLineResolutions)
239 llvm::errs() << argv[0] << ": unused symbol resolution for "
240 << UnusedRes.first.first << ',' << UnusedRes.first.second
241 << '\n';
242 }
243 if (HasErrors)
244 return 1;
245
Peter Collingbourne80186a52016-09-23 21:33:43 +0000246 auto AddStream =
247 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000248 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000249
Peter Collingbourne80186a52016-09-23 21:33:43 +0000250 std::error_code EC;
251 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
252 check(EC, Path);
253 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000254 };
255
Peter Collingbourne80186a52016-09-23 21:33:43 +0000256 auto AddFile = [&](size_t Task, StringRef Path) {
257 auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path);
258 if (auto EC = ReloadedBufferOrErr.getError())
259 report_fatal_error(Twine("Can't reload cached file '") + Path + "': " +
260 EC.message() + "\n");
261
262 *AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer();
263 };
264
265 NativeObjectCache Cache;
266 if (!CacheDir.empty())
267 Cache = localCache(CacheDir, AddFile);
268
269 check(Lto.run(AddStream, Cache), "LTO::run failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000270}