OSDN Git Service

b112f028e41676d637795725424e735b890ddb2c
[android-x86/external-llvm.git] / 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/LTO/Caching.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/Support/Threading.h"
26
27 using namespace llvm;
28 using namespace lto;
29 using namespace object;
30
31 static 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
36 static 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
41 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
42                                             cl::desc("<input bitcode files>"));
43
44 static cl::opt<std::string> OutputFilename("o", cl::Required,
45                                            cl::desc("Output filename"),
46                                            cl::value_desc("filename"));
47
48 static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
49                                      cl::value_desc("directory"));
50
51 static cl::opt<std::string> OptPipeline("opt-pipeline",
52                                         cl::desc("Optimizer Pipeline"),
53                                         cl::value_desc("pipeline"));
54
55 static cl::opt<std::string> AAPipeline("aa-pipeline",
56                                        cl::desc("Alias Analysis Pipeline"),
57                                        cl::value_desc("aapipeline"));
58
59 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
60
61 static 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
67 static cl::opt<int> Threads("thinlto-threads",
68                             cl::init(llvm::heavyweight_hardware_concurrency()));
69
70 static 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
84 static cl::opt<std::string> OverrideTriple(
85     "override-triple",
86     cl::desc("Replace target triples in input files with this triple"));
87
88 static cl::opt<std::string> DefaultTriple(
89     "default-triple",
90     cl::desc(
91         "Replace unspecified target triples in input files with this triple"));
92
93 static cl::opt<std::string>
94     OptRemarksOutput("pass-remarks-output",
95                      cl::desc("YAML output file for optimization remarks"));
96
97 static cl::opt<bool> OptRemarksWithHotness(
98     "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
102 static void check(Error E, std::string Msg) {
103   if (!E)
104     return;
105   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
106     errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
107   });
108   exit(1);
109 }
110
111 template <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
118 static void check(std::error_code EC, std::string Msg) {
119   check(errorCodeToError(EC), Msg);
120 }
121
122 template <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
129 int main(int argc, char **argv) {
130   InitializeAllTargets();
131   InitializeAllTargetMCs();
132   InitializeAllAsmPrinters();
133   InitializeAllAsmParsers();
134
135   cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
136
137   // 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>>
142       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;
160       else
161         llvm::errs() << "invalid character " << C << " in resolution: " << R
162                      << '\n';
163     }
164     CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
165   }
166
167   std::vector<std::unique_ptr<MemoryBuffer>> MBs;
168
169   Config Conf;
170   Conf.DiagHandler = [](const DiagnosticInfo &DI) {
171     DiagnosticPrinterRawOStream DP(errs());
172     DI.print(DP);
173     errs() << '\n';
174     exit(1);
175   };
176
177   Conf.CPU = MCPU;
178   Conf.Options = InitTargetOptionsFromCodeGenFlags();
179   Conf.MAttrs = MAttrs;
180   if (auto RM = getRelocModel())
181     Conf.RelocModel = *RM;
182   Conf.CodeModel = CMModel;
183
184   if (SaveTemps)
185     check(Conf.addSaveTemps(OutputFilename + "."),
186           "Config::addSaveTemps failed");
187
188   // Optimization remarks.
189   Conf.RemarksFilename = OptRemarksOutput;
190   Conf.RemarksWithHotness = OptRemarksWithHotness;
191
192   // Run a custom pipeline, if asked for.
193   Conf.OptPipeline = OptPipeline;
194   Conf.AAPipeline = AAPipeline;
195
196   Conf.OptLevel = OptLevel - '0';
197   switch (CGOptLevel) {
198   case '0':
199     Conf.CGOptLevel = CodeGenOpt::None;
200     break;
201   case '1':
202     Conf.CGOptLevel = CodeGenOpt::Less;
203     break;
204   case '2':
205     Conf.CGOptLevel = CodeGenOpt::Default;
206     break;
207   case '3':
208     Conf.CGOptLevel = CodeGenOpt::Aggressive;
209     break;
210   default:
211     llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
212     return 1;
213   }
214
215   if (FileType.getNumOccurrences())
216     Conf.CGFileType = FileType;
217
218   Conf.OverrideTriple = OverrideTriple;
219   Conf.DefaultTriple = DefaultTriple;
220
221   ThinBackend Backend;
222   if (ThinLTODistributedIndexes)
223     Backend = createWriteIndexesThinBackend("", "", true, "");
224   else
225     Backend = createInProcessThinBackend(Threads);
226   LTO Lto(std::move(Conf), std::move(Backend));
227
228   bool HasErrors = false;
229   for (std::string F : InputFilenames) {
230     std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
231     std::unique_ptr<InputFile> Input =
232         check(InputFile::create(MB->getMemBufferRef()), F);
233
234     std::vector<SymbolResolution> Res;
235     for (const InputFile::Symbol &Sym : Input->symbols()) {
236       auto I = CommandLineResolutions.find({F, Sym.getName()});
237       if (I == CommandLineResolutions.end()) {
238         llvm::errs() << argv[0] << ": missing symbol resolution for " << F
239                      << ',' << Sym.getName() << '\n';
240         HasErrors = true;
241       } else {
242         Res.push_back(I->second.front());
243         I->second.pop_front();
244         if (I->second.empty())
245           CommandLineResolutions.erase(I);
246       }
247     }
248
249     if (HasErrors)
250       continue;
251
252     MBs.push_back(std::move(MB));
253     check(Lto.add(std::move(Input), Res), F);
254   }
255
256   if (!CommandLineResolutions.empty()) {
257     HasErrors = true;
258     for (auto UnusedRes : CommandLineResolutions)
259       llvm::errs() << argv[0] << ": unused symbol resolution for "
260                    << UnusedRes.first.first << ',' << UnusedRes.first.second
261                    << '\n';
262   }
263   if (HasErrors)
264     return 1;
265
266   auto AddStream =
267       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
268     std::string Path = OutputFilename + "." + utostr(Task);
269
270     std::error_code EC;
271     auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
272     check(EC, Path);
273     return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
274   };
275
276   auto AddFile = [&](size_t Task, StringRef Path) {
277     auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path);
278     if (auto EC = ReloadedBufferOrErr.getError())
279       report_fatal_error(Twine("Can't reload cached file '") + Path + "': " +
280                          EC.message() + "\n");
281
282     *AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer();
283   };
284
285   NativeObjectCache Cache;
286   if (!CacheDir.empty())
287     Cache = localCache(CacheDir, AddFile);
288
289   check(Lto.run(AddStream, Cache), "LTO::run failed");
290 }