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] "
40 DisableInline("disable-inlining", cl::init(false),
41 cl::desc("Do not run the inliner pass"));
44 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
45 cl::desc("Do not run the GVN load PRE pass"));
48 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
49 cl::desc("Do not run loop or slp vectorization during LTO"));
52 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
53 cl::desc("Use a diagnostic handler to test the handler interface"));
55 static cl::list<std::string>
56 InputFilenames(cl::Positional, cl::OneOrMore,
57 cl::desc("<input bitcode files>"));
59 static cl::opt<std::string>
60 OutputFilename("o", cl::init(""),
61 cl::desc("Override output filename"),
62 cl::value_desc("filename"));
64 static cl::list<std::string>
65 ExportedSymbols("exported-symbol",
66 cl::desc("Symbol to export from the resulting object file"),
69 static cl::list<std::string>
70 DSOSymbols("dso-symbol",
71 cl::desc("Symbol to put in the symtab in the resulting dso"),
74 static cl::opt<bool> ListSymbolsOnly(
75 "list-symbols-only", cl::init(false),
76 cl::desc("Instead of running LTO, list the symbols in each IR file"));
78 static cl::opt<bool> SetMergedModule(
79 "set-merged-module", cl::init(false),
80 cl::desc("Use the first input module as the merged module"));
82 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
83 cl::desc("Number of backend threads"));
87 std::vector<bool> CanBeHidden;
91 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
92 const char *Msg, void *) {
104 errs() << "warning: ";
107 errs() << Msg << "\n";
110 static std::unique_ptr<LTOModule>
111 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
112 const TargetOptions &Options, std::string &Error) {
113 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
114 MemoryBuffer::getFile(Path);
115 if (std::error_code EC = BufferOrErr.getError()) {
116 Error = EC.message();
119 Buffer = std::move(BufferOrErr.get());
120 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
121 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
124 /// \brief List symbols in each IR file.
126 /// The main point here is to provide lit-testable coverage for the LTOModule
127 /// functionality that's exposed by the C API to list symbols. Moreover, this
128 /// provides testing coverage for modules that have been created in their own
130 static int listSymbols(StringRef Command, const TargetOptions &Options) {
131 for (auto &Filename : InputFilenames) {
133 std::unique_ptr<MemoryBuffer> Buffer;
134 std::unique_ptr<LTOModule> Module =
135 getLocalLTOModule(Filename, Buffer, Options, Error);
137 errs() << Command << ": error loading file '" << Filename
138 << "': " << Error << "\n";
143 outs() << Filename << ":\n";
144 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
145 outs() << Module->getSymbolName(I) << "\n";
150 int main(int argc, char **argv) {
151 // Print a stack trace if we signal out.
152 sys::PrintStackTraceOnErrorSignal();
153 PrettyStackTraceProgram X(argc, argv);
155 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
156 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
158 if (OptLevel < '0' || OptLevel > '3') {
159 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
163 // Initialize the configured targets.
164 InitializeAllTargets();
165 InitializeAllTargetMCs();
166 InitializeAllAsmPrinters();
167 InitializeAllAsmParsers();
169 // set up the TargetOptions for the machine
170 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
173 return listSymbols(argv[0], Options);
175 unsigned BaseArg = 0;
177 LTOCodeGenerator CodeGen;
179 if (UseDiagnosticHandler)
180 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
182 CodeGen.setCodePICModel(RelocModel);
184 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
185 CodeGen.setTargetOptions(Options);
187 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
188 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
189 DSOSymbolsSet.insert(DSOSymbols[i]);
191 std::vector<std::string> KeptDSOSyms;
193 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
195 std::unique_ptr<LTOModule> Module(
196 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
197 if (!error.empty()) {
198 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
199 << "': " << error << "\n";
203 unsigned NumSyms = Module->getSymbolCount();
204 for (unsigned I = 0; I < NumSyms; ++I) {
205 StringRef Name = Module->getSymbolName(I);
206 if (!DSOSymbolsSet.count(Name))
208 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
209 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
210 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
211 KeptDSOSyms.push_back(Name);
214 // We use the first input module as the destination module when
215 // SetMergedModule is true.
216 if (SetMergedModule && i == BaseArg) {
217 // Transfer ownership to the code generator.
218 CodeGen.setModule(std::move(Module));
219 } else if (!CodeGen.addModule(Module.get())) {
220 // Print a message here so that we know addModule() did not abort.
221 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
226 // Add all the exported symbols to the table of symbols to preserve.
227 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
228 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
230 // Add all the dso symbols to the table of symbols to expose.
231 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
232 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
234 // Set cpu and attrs strings for the default target/subtarget.
235 CodeGen.setCpu(MCPU.c_str());
237 CodeGen.setOptLevel(OptLevel - '0');
240 for (unsigned i = 0; i < MAttrs.size(); ++i) {
243 attrs.append(MAttrs[i]);
247 CodeGen.setAttr(attrs.c_str());
249 if (!OutputFilename.empty()) {
250 std::string ErrorInfo;
251 if (!CodeGen.optimize(DisableInline, DisableGVNLoadPRE,
252 DisableLTOVectorization, ErrorInfo)) {
253 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
257 std::list<tool_output_file> OSs;
258 std::vector<raw_pwrite_stream *> OSPtrs;
259 for (unsigned I = 0; I != Parallelism; ++I) {
260 std::string PartFilename = OutputFilename;
261 if (Parallelism != 1)
262 PartFilename += "." + utostr(I);
264 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
266 errs() << argv[0] << ": error opening the file '" << PartFilename
267 << "': " << EC.message() << "\n";
270 OSPtrs.push_back(&OSs.back().os());
273 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
274 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
278 for (tool_output_file &OS : OSs)
281 if (Parallelism != 1) {
282 errs() << argv[0] << ": -j must be specified together with -o\n";
286 std::string ErrorInfo;
287 const char *OutputName = nullptr;
288 if (!CodeGen.compile_to_file(&OutputName, DisableInline,
289 DisableGVNLoadPRE, DisableLTOVectorization,
292 << ": error compiling the code: " << ErrorInfo
297 outs() << "Wrote native object file '" << OutputName << "'\n";