]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp
MFC: r326864
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-lto2 / llvm-lto2.cpp
1 //===-- 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
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/Threading.h"
28
29 using namespace llvm;
30 using namespace lto;
31
32 static 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
37 static 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
42 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
43                                             cl::desc("<input bitcode files>"));
44
45 static cl::opt<std::string> OutputFilename("o", cl::Required,
46                                            cl::desc("Output filename"),
47                                            cl::value_desc("filename"));
48
49 static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
50                                      cl::value_desc("directory"));
51
52 static cl::opt<std::string> OptPipeline("opt-pipeline",
53                                         cl::desc("Optimizer Pipeline"),
54                                         cl::value_desc("pipeline"));
55
56 static cl::opt<std::string> AAPipeline("aa-pipeline",
57                                        cl::desc("Alias Analysis Pipeline"),
58                                        cl::value_desc("aapipeline"));
59
60 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
61
62 static 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
68 static cl::opt<int> Threads("thinlto-threads",
69                             cl::init(llvm::heavyweight_hardware_concurrency()));
70
71 static 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
85 static cl::opt<std::string> OverrideTriple(
86     "override-triple",
87     cl::desc("Replace target triples in input files with this triple"));
88
89 static cl::opt<std::string> DefaultTriple(
90     "default-triple",
91     cl::desc(
92         "Replace unspecified target triples in input files with this triple"));
93
94 static cl::opt<std::string>
95     OptRemarksOutput("pass-remarks-output",
96                      cl::desc("YAML output file for optimization remarks"));
97
98 static cl::opt<bool> OptRemarksWithHotness(
99     "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
103 static cl::opt<bool>
104     UseNewPM("use-new-pm",
105              cl::desc("Run LTO passes using the new pass manager"),
106              cl::init(false), cl::Hidden);
107
108 static void check(Error E, std::string Msg) {
109   if (!E)
110     return;
111   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
112     errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
113   });
114   exit(1);
115 }
116
117 template <typename T> static T check(Expected<T> E, std::string Msg) {
118   if (E)
119     return std::move(*E);
120   check(E.takeError(), Msg);
121   return T();
122 }
123
124 static void check(std::error_code EC, std::string Msg) {
125   check(errorCodeToError(EC), Msg);
126 }
127
128 template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
129   if (E)
130     return std::move(*E);
131   check(E.getError(), Msg);
132   return T();
133 }
134
135 static int usage() {
136   errs() << "Available subcommands: dump-symtab run\n";
137   return 1;
138 }
139
140 static int run(int argc, char **argv) {
141   cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
142
143   // FIXME: Workaround PR30396 which means that a symbol can appear
144   // more than once if it is defined in module-level assembly and
145   // has a GV declaration. We allow (file, symbol) pairs to have multiple
146   // resolutions and apply them in the order observed.
147   std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
148       CommandLineResolutions;
149   for (std::string R : SymbolResolutions) {
150     StringRef Rest = R;
151     StringRef FileName, SymbolName;
152     std::tie(FileName, Rest) = Rest.split(',');
153     if (Rest.empty()) {
154       llvm::errs() << "invalid resolution: " << R << '\n';
155       return 1;
156     }
157     std::tie(SymbolName, Rest) = Rest.split(',');
158     SymbolResolution Res;
159     for (char C : Rest) {
160       if (C == 'p')
161         Res.Prevailing = true;
162       else if (C == 'l')
163         Res.FinalDefinitionInLinkageUnit = true;
164       else if (C == 'x')
165         Res.VisibleToRegularObj = true;
166       else if (C == 'r')
167         Res.LinkerRedefined = true;
168       else {
169         llvm::errs() << "invalid character " << C << " in resolution: " << R
170                      << '\n';
171         return 1;
172       }
173     }
174     CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
175   }
176
177   std::vector<std::unique_ptr<MemoryBuffer>> MBs;
178
179   Config Conf;
180   Conf.DiagHandler = [](const DiagnosticInfo &DI) {
181     DiagnosticPrinterRawOStream DP(errs());
182     DI.print(DP);
183     errs() << '\n';
184     exit(1);
185   };
186
187   Conf.CPU = MCPU;
188   Conf.Options = InitTargetOptionsFromCodeGenFlags();
189   Conf.MAttrs = MAttrs;
190   if (auto RM = getRelocModel())
191     Conf.RelocModel = *RM;
192   Conf.CodeModel = CMModel;
193
194   if (SaveTemps)
195     check(Conf.addSaveTemps(OutputFilename + "."),
196           "Config::addSaveTemps failed");
197
198   // Optimization remarks.
199   Conf.RemarksFilename = OptRemarksOutput;
200   Conf.RemarksWithHotness = OptRemarksWithHotness;
201
202   // Run a custom pipeline, if asked for.
203   Conf.OptPipeline = OptPipeline;
204   Conf.AAPipeline = AAPipeline;
205
206   Conf.OptLevel = OptLevel - '0';
207   Conf.UseNewPM = UseNewPM;
208   switch (CGOptLevel) {
209   case '0':
210     Conf.CGOptLevel = CodeGenOpt::None;
211     break;
212   case '1':
213     Conf.CGOptLevel = CodeGenOpt::Less;
214     break;
215   case '2':
216     Conf.CGOptLevel = CodeGenOpt::Default;
217     break;
218   case '3':
219     Conf.CGOptLevel = CodeGenOpt::Aggressive;
220     break;
221   default:
222     llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
223     return 1;
224   }
225
226   if (FileType.getNumOccurrences())
227     Conf.CGFileType = FileType;
228
229   Conf.OverrideTriple = OverrideTriple;
230   Conf.DefaultTriple = DefaultTriple;
231
232   ThinBackend Backend;
233   if (ThinLTODistributedIndexes)
234     Backend = createWriteIndexesThinBackend("", "", true, "");
235   else
236     Backend = createInProcessThinBackend(Threads);
237   LTO Lto(std::move(Conf), std::move(Backend));
238
239   bool HasErrors = false;
240   for (std::string F : InputFilenames) {
241     std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
242     std::unique_ptr<InputFile> Input =
243         check(InputFile::create(MB->getMemBufferRef()), F);
244
245     std::vector<SymbolResolution> Res;
246     for (const InputFile::Symbol &Sym : Input->symbols()) {
247       auto I = CommandLineResolutions.find({F, Sym.getName()});
248       if (I == CommandLineResolutions.end()) {
249         llvm::errs() << argv[0] << ": missing symbol resolution for " << F
250                      << ',' << Sym.getName() << '\n';
251         HasErrors = true;
252       } else {
253         Res.push_back(I->second.front());
254         I->second.pop_front();
255         if (I->second.empty())
256           CommandLineResolutions.erase(I);
257       }
258     }
259
260     if (HasErrors)
261       continue;
262
263     MBs.push_back(std::move(MB));
264     check(Lto.add(std::move(Input), Res), F);
265   }
266
267   if (!CommandLineResolutions.empty()) {
268     HasErrors = true;
269     for (auto UnusedRes : CommandLineResolutions)
270       llvm::errs() << argv[0] << ": unused symbol resolution for "
271                    << UnusedRes.first.first << ',' << UnusedRes.first.second
272                    << '\n';
273   }
274   if (HasErrors)
275     return 1;
276
277   auto AddStream =
278       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
279     std::string Path = OutputFilename + "." + utostr(Task);
280
281     std::error_code EC;
282     auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
283     check(EC, Path);
284     return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
285   };
286
287   auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
288     *AddStream(Task)->OS << MB->getBuffer();
289   };
290
291   NativeObjectCache Cache;
292   if (!CacheDir.empty())
293     Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
294
295   check(Lto.run(AddStream, Cache), "LTO::run failed");
296   return 0;
297 }
298
299 static int dumpSymtab(int argc, char **argv) {
300   for (StringRef F : make_range(argv + 1, argv + argc)) {
301     std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
302     BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F);
303
304     if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
305       auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
306           BFC.Symtab.data());
307       outs() << "version: " << Hdr->Version << '\n';
308       if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
309         outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
310                << '\n';
311     }
312
313     std::unique_ptr<InputFile> Input =
314         check(InputFile::create(MB->getMemBufferRef()), F);
315
316     outs() << "target triple: " << Input->getTargetTriple() << '\n';
317     Triple TT(Input->getTargetTriple());
318
319     outs() << "source filename: " << Input->getSourceFileName() << '\n';
320
321     if (TT.isOSBinFormatCOFF())
322       outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
323
324     std::vector<StringRef> ComdatTable = Input->getComdatTable();
325     for (const InputFile::Symbol &Sym : Input->symbols()) {
326       switch (Sym.getVisibility()) {
327       case GlobalValue::HiddenVisibility:
328         outs() << 'H';
329         break;
330       case GlobalValue::ProtectedVisibility:
331         outs() << 'P';
332         break;
333       case GlobalValue::DefaultVisibility:
334         outs() << 'D';
335         break;
336       }
337
338       auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
339       PrintBool('U', Sym.isUndefined());
340       PrintBool('C', Sym.isCommon());
341       PrintBool('W', Sym.isWeak());
342       PrintBool('I', Sym.isIndirect());
343       PrintBool('O', Sym.canBeOmittedFromSymbolTable());
344       PrintBool('T', Sym.isTLS());
345       PrintBool('X', Sym.isExecutable());
346       outs() << ' ' << Sym.getName() << '\n';
347
348       if (Sym.isCommon())
349         outs() << "         size " << Sym.getCommonSize() << " align "
350                << Sym.getCommonAlignment() << '\n';
351
352       int Comdat = Sym.getComdatIndex();
353       if (Comdat != -1)
354         outs() << "         comdat " << ComdatTable[Comdat] << '\n';
355
356       if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
357         outs() << "         fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
358     }
359
360     outs() << '\n';
361   }
362
363   return 0;
364 }
365
366 int main(int argc, char **argv) {
367   InitializeAllTargets();
368   InitializeAllTargetMCs();
369   InitializeAllAsmPrinters();
370   InitializeAllAsmParsers();
371
372   // FIXME: This should use llvm::cl subcommands, but it isn't currently
373   // possible to pass an argument not associated with a subcommand to a
374   // subcommand (e.g. -use-new-pm).
375   if (argc < 2)
376     return usage();
377
378   StringRef Subcommand = argv[1];
379   // Ensure that argv[0] is correct after adjusting argv/argc.
380   argv[1] = argv[0];
381   if (Subcommand == "dump-symtab")
382     return dumpSymtab(argc - 1, argv + 1);
383   if (Subcommand == "run")
384     return run(argc - 1, argv + 1);
385   return usage();
386 }