1 //===-- llvm-lto: a simple command-line program to link modules with LTO --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program takes in a list of bitcode files, links them, performs link-time
11 // optimization, and outputs an object file.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/LTO/LTOCodeGenerator.h"
21 #include "llvm/LTO/LTOModule.h"
22 #include "llvm/Object/FunctionIndexObjectFile.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/TargetSelect.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include "llvm/Support/raw_ostream.h"
37 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
43 static cl::opt<bool> DisableVerify(
44 "disable-verify", cl::init(false),
45 cl::desc("Do not run the verifier during the optimization pipeline"));
48 DisableInline("disable-inlining", cl::init(false),
49 cl::desc("Do not run the inliner pass"));
52 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
53 cl::desc("Do not run the GVN load PRE pass"));
56 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
57 cl::desc("Do not run loop or slp vectorization during LTO"));
60 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
61 cl::desc("Use a diagnostic handler to test the handler interface"));
64 ThinLTO("thinlto", cl::init(false),
65 cl::desc("Only write combined global index for ThinLTO backends"));
67 static cl::list<std::string>
68 InputFilenames(cl::Positional, cl::OneOrMore,
69 cl::desc("<input bitcode files>"));
71 static cl::opt<std::string>
72 OutputFilename("o", cl::init(""),
73 cl::desc("Override output filename"),
74 cl::value_desc("filename"));
76 static cl::list<std::string>
77 ExportedSymbols("exported-symbol",
78 cl::desc("Symbol to export from the resulting object file"),
81 static cl::list<std::string>
82 DSOSymbols("dso-symbol",
83 cl::desc("Symbol to put in the symtab in the resulting dso"),
86 static cl::opt<bool> ListSymbolsOnly(
87 "list-symbols-only", cl::init(false),
88 cl::desc("Instead of running LTO, list the symbols in each IR file"));
90 static cl::opt<bool> SetMergedModule(
91 "set-merged-module", cl::init(false),
92 cl::desc("Use the first input module as the merged module"));
94 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
95 cl::desc("Number of backend threads"));
99 std::vector<bool> CanBeHidden;
103 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
104 const char *Msg, void *) {
105 errs() << "llvm-lto: ";
111 errs() << "remark: ";
117 errs() << "warning: ";
120 errs() << Msg << "\n";
123 static void diagnosticHandler(const DiagnosticInfo &DI) {
124 raw_ostream &OS = errs();
126 switch (DI.getSeverity()) {
141 DiagnosticPrinterRawOStream DP(OS);
145 if (DI.getSeverity() == DS_Error)
149 static std::unique_ptr<LTOModule>
150 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
151 const TargetOptions &Options, std::string &Error) {
152 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
153 MemoryBuffer::getFile(Path);
154 if (std::error_code EC = BufferOrErr.getError()) {
155 Error = EC.message();
158 Buffer = std::move(BufferOrErr.get());
159 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
160 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
163 /// \brief List symbols in each IR file.
165 /// The main point here is to provide lit-testable coverage for the LTOModule
166 /// functionality that's exposed by the C API to list symbols. Moreover, this
167 /// provides testing coverage for modules that have been created in their own
169 static int listSymbols(StringRef Command, const TargetOptions &Options) {
170 for (auto &Filename : InputFilenames) {
172 std::unique_ptr<MemoryBuffer> Buffer;
173 std::unique_ptr<LTOModule> Module =
174 getLocalLTOModule(Filename, Buffer, Options, Error);
176 errs() << Command << ": error loading file '" << Filename
177 << "': " << Error << "\n";
182 outs() << Filename << ":\n";
183 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
184 outs() << Module->getSymbolName(I) << "\n";
189 /// Parse the function index out of an IR file and return the function
190 /// index object if found, or nullptr if not.
191 static std::unique_ptr<FunctionInfoIndex>
192 getFunctionIndexForFile(StringRef Path, std::string &Error,
193 DiagnosticHandlerFunction DiagnosticHandler) {
194 std::unique_ptr<MemoryBuffer> Buffer;
195 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
196 MemoryBuffer::getFile(Path);
197 if (std::error_code EC = BufferOrErr.getError()) {
198 Error = EC.message();
201 Buffer = std::move(BufferOrErr.get());
202 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
203 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
205 if (std::error_code EC = ObjOrErr.getError()) {
206 Error = EC.message();
209 return (*ObjOrErr)->takeIndex();
212 /// Create a combined index file from the input IR files and write it.
214 /// This is meant to enable testing of ThinLTO combined index generation,
215 /// currently available via the gold plugin via -thinlto.
216 static int createCombinedFunctionIndex(StringRef Command) {
217 FunctionInfoIndex CombinedIndex;
218 uint64_t NextModuleId = 0;
219 for (auto &Filename : InputFilenames) {
221 std::unique_ptr<FunctionInfoIndex> Index =
222 getFunctionIndexForFile(Filename, Error, diagnosticHandler);
224 errs() << Command << ": error loading file '" << Filename
225 << "': " << Error << "\n";
228 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
231 assert(!OutputFilename.empty());
232 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
233 sys::fs::OpenFlags::F_None);
235 errs() << Command << ": error opening the file '" << OutputFilename
236 << ".thinlto.bc': " << EC.message() << "\n";
239 WriteFunctionSummaryToFile(CombinedIndex, OS);
244 int main(int argc, char **argv) {
245 // Print a stack trace if we signal out.
246 sys::PrintStackTraceOnErrorSignal();
247 PrettyStackTraceProgram X(argc, argv);
249 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
250 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
252 if (OptLevel < '0' || OptLevel > '3') {
253 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
257 // Initialize the configured targets.
258 InitializeAllTargets();
259 InitializeAllTargetMCs();
260 InitializeAllAsmPrinters();
261 InitializeAllAsmParsers();
263 // set up the TargetOptions for the machine
264 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
267 return listSymbols(argv[0], Options);
270 return createCombinedFunctionIndex(argv[0]);
272 unsigned BaseArg = 0;
274 LTOCodeGenerator CodeGen;
276 if (UseDiagnosticHandler)
277 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
279 CodeGen.setCodePICModel(RelocModel);
281 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
282 CodeGen.setTargetOptions(Options);
284 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
285 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
286 DSOSymbolsSet.insert(DSOSymbols[i]);
288 std::vector<std::string> KeptDSOSyms;
290 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
292 std::unique_ptr<LTOModule> Module(
293 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
294 if (!error.empty()) {
295 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
296 << "': " << error << "\n";
300 unsigned NumSyms = Module->getSymbolCount();
301 for (unsigned I = 0; I < NumSyms; ++I) {
302 StringRef Name = Module->getSymbolName(I);
303 if (!DSOSymbolsSet.count(Name))
305 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
306 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
307 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
308 KeptDSOSyms.push_back(Name);
311 // We use the first input module as the destination module when
312 // SetMergedModule is true.
313 if (SetMergedModule && i == BaseArg) {
314 // Transfer ownership to the code generator.
315 CodeGen.setModule(std::move(Module));
316 } else if (!CodeGen.addModule(Module.get())) {
317 // Print a message here so that we know addModule() did not abort.
318 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
323 // Add all the exported symbols to the table of symbols to preserve.
324 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
325 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
327 // Add all the dso symbols to the table of symbols to expose.
328 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
329 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
331 // Set cpu and attrs strings for the default target/subtarget.
332 CodeGen.setCpu(MCPU.c_str());
334 CodeGen.setOptLevel(OptLevel - '0');
337 for (unsigned i = 0; i < MAttrs.size(); ++i) {
340 attrs.append(MAttrs[i]);
344 CodeGen.setAttr(attrs.c_str());
346 if (!OutputFilename.empty()) {
347 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
348 DisableLTOVectorization)) {
349 // Diagnostic messages should have been printed by the handler.
350 errs() << argv[0] << ": error optimizing the code\n";
354 std::list<tool_output_file> OSs;
355 std::vector<raw_pwrite_stream *> OSPtrs;
356 for (unsigned I = 0; I != Parallelism; ++I) {
357 std::string PartFilename = OutputFilename;
358 if (Parallelism != 1)
359 PartFilename += "." + utostr(I);
361 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
363 errs() << argv[0] << ": error opening the file '" << PartFilename
364 << "': " << EC.message() << "\n";
367 OSPtrs.push_back(&OSs.back().os());
370 if (!CodeGen.compileOptimized(OSPtrs)) {
371 // Diagnostic messages should have been printed by the handler.
372 errs() << argv[0] << ": error compiling the code\n";
376 for (tool_output_file &OS : OSs)
379 if (Parallelism != 1) {
380 errs() << argv[0] << ": -j must be specified together with -o\n";
384 const char *OutputName = nullptr;
385 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
386 DisableGVNLoadPRE, DisableLTOVectorization)) {
387 // Diagnostic messages should have been printed by the handler.
388 errs() << argv[0] << ": error compiling the code\n";
392 outs() << "Wrote native object file '" << OutputName << "'\n";