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/CodeGen/CommandFlags.h"
17 #include "llvm/LTO/LTOCodeGenerator.h"
18 #include "llvm/LTO/LTOModule.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/Support/ToolOutputFile.h"
26 #include "llvm/Support/raw_ostream.h"
33 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
39 static cl::opt<bool> DisableVerify(
40 "disable-verify", cl::init(false),
41 cl::desc("Do not run the verifier during the optimization pipeline"));
44 DisableInline("disable-inlining", cl::init(false),
45 cl::desc("Do not run the inliner pass"));
48 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
49 cl::desc("Do not run the GVN load PRE pass"));
52 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
53 cl::desc("Do not run loop or slp vectorization during LTO"));
56 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
57 cl::desc("Use a diagnostic handler to test the handler interface"));
59 static cl::list<std::string>
60 InputFilenames(cl::Positional, cl::OneOrMore,
61 cl::desc("<input bitcode files>"));
63 static cl::opt<std::string>
64 OutputFilename("o", cl::init(""),
65 cl::desc("Override output filename"),
66 cl::value_desc("filename"));
68 static cl::list<std::string>
69 ExportedSymbols("exported-symbol",
70 cl::desc("Symbol to export from the resulting object file"),
73 static cl::list<std::string>
74 DSOSymbols("dso-symbol",
75 cl::desc("Symbol to put in the symtab in the resulting dso"),
78 static cl::opt<bool> ListSymbolsOnly(
79 "list-symbols-only", cl::init(false),
80 cl::desc("Instead of running LTO, list the symbols in each IR file"));
82 static cl::opt<bool> SetMergedModule(
83 "set-merged-module", cl::init(false),
84 cl::desc("Use the first input module as the merged module"));
86 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
87 cl::desc("Number of backend threads"));
91 std::vector<bool> CanBeHidden;
95 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
96 const char *Msg, void *) {
102 errs() << "remark: ";
108 errs() << "warning: ";
111 errs() << Msg << "\n";
114 static std::unique_ptr<LTOModule>
115 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
116 const TargetOptions &Options, std::string &Error) {
117 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
118 MemoryBuffer::getFile(Path);
119 if (std::error_code EC = BufferOrErr.getError()) {
120 Error = EC.message();
123 Buffer = std::move(BufferOrErr.get());
124 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
125 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
128 /// \brief List symbols in each IR file.
130 /// The main point here is to provide lit-testable coverage for the LTOModule
131 /// functionality that's exposed by the C API to list symbols. Moreover, this
132 /// provides testing coverage for modules that have been created in their own
134 static int listSymbols(StringRef Command, const TargetOptions &Options) {
135 for (auto &Filename : InputFilenames) {
137 std::unique_ptr<MemoryBuffer> Buffer;
138 std::unique_ptr<LTOModule> Module =
139 getLocalLTOModule(Filename, Buffer, Options, Error);
141 errs() << Command << ": error loading file '" << Filename
142 << "': " << Error << "\n";
147 outs() << Filename << ":\n";
148 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
149 outs() << Module->getSymbolName(I) << "\n";
154 int main(int argc, char **argv) {
155 // Print a stack trace if we signal out.
156 sys::PrintStackTraceOnErrorSignal();
157 PrettyStackTraceProgram X(argc, argv);
159 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
160 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
162 if (OptLevel < '0' || OptLevel > '3') {
163 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
167 // Initialize the configured targets.
168 InitializeAllTargets();
169 InitializeAllTargetMCs();
170 InitializeAllAsmPrinters();
171 InitializeAllAsmParsers();
173 // set up the TargetOptions for the machine
174 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
177 return listSymbols(argv[0], Options);
179 unsigned BaseArg = 0;
181 LTOCodeGenerator CodeGen;
183 if (UseDiagnosticHandler)
184 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
186 CodeGen.setCodePICModel(RelocModel);
188 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
189 CodeGen.setTargetOptions(Options);
191 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
192 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
193 DSOSymbolsSet.insert(DSOSymbols[i]);
195 std::vector<std::string> KeptDSOSyms;
197 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
199 std::unique_ptr<LTOModule> Module(
200 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
201 if (!error.empty()) {
202 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
203 << "': " << error << "\n";
207 unsigned NumSyms = Module->getSymbolCount();
208 for (unsigned I = 0; I < NumSyms; ++I) {
209 StringRef Name = Module->getSymbolName(I);
210 if (!DSOSymbolsSet.count(Name))
212 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
213 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
214 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
215 KeptDSOSyms.push_back(Name);
218 // We use the first input module as the destination module when
219 // SetMergedModule is true.
220 if (SetMergedModule && i == BaseArg) {
221 // Transfer ownership to the code generator.
222 CodeGen.setModule(std::move(Module));
223 } else if (!CodeGen.addModule(Module.get())) {
224 // Print a message here so that we know addModule() did not abort.
225 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
230 // Add all the exported symbols to the table of symbols to preserve.
231 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
232 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
234 // Add all the dso symbols to the table of symbols to expose.
235 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
236 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
238 // Set cpu and attrs strings for the default target/subtarget.
239 CodeGen.setCpu(MCPU.c_str());
241 CodeGen.setOptLevel(OptLevel - '0');
244 for (unsigned i = 0; i < MAttrs.size(); ++i) {
247 attrs.append(MAttrs[i]);
251 CodeGen.setAttr(attrs.c_str());
253 if (!OutputFilename.empty()) {
254 std::string ErrorInfo;
255 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
256 DisableLTOVectorization, ErrorInfo)) {
257 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
261 std::list<tool_output_file> OSs;
262 std::vector<raw_pwrite_stream *> OSPtrs;
263 for (unsigned I = 0; I != Parallelism; ++I) {
264 std::string PartFilename = OutputFilename;
265 if (Parallelism != 1)
266 PartFilename += "." + utostr(I);
268 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
270 errs() << argv[0] << ": error opening the file '" << PartFilename
271 << "': " << EC.message() << "\n";
274 OSPtrs.push_back(&OSs.back().os());
277 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
278 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
282 for (tool_output_file &OS : OSs)
285 if (Parallelism != 1) {
286 errs() << argv[0] << ": -j must be specified together with -o\n";
290 std::string ErrorInfo;
291 const char *OutputName = nullptr;
292 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
293 DisableGVNLoadPRE, DisableLTOVectorization,
296 << ": error compiling the code: " << ErrorInfo
301 outs() << "Wrote native object file '" << OutputName << "'\n";