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/raw_ostream.h"
31 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
38 DisableInline("disable-inlining", cl::init(false),
39 cl::desc("Do not run the inliner pass"));
42 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
43 cl::desc("Do not run the GVN load PRE pass"));
46 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
47 cl::desc("Do not run loop or slp vectorization during LTO"));
50 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
51 cl::desc("Use a diagnostic handler to test the handler interface"));
53 static cl::list<std::string>
54 InputFilenames(cl::Positional, cl::OneOrMore,
55 cl::desc("<input bitcode files>"));
57 static cl::opt<std::string>
58 OutputFilename("o", cl::init(""),
59 cl::desc("Override output filename"),
60 cl::value_desc("filename"));
62 static cl::list<std::string>
63 ExportedSymbols("exported-symbol",
64 cl::desc("Symbol to export from the resulting object file"),
67 static cl::list<std::string>
68 DSOSymbols("dso-symbol",
69 cl::desc("Symbol to put in the symtab in the resulting dso"),
72 static cl::opt<bool> ListSymbolsOnly(
73 "list-symbols-only", cl::init(false),
74 cl::desc("Instead of running LTO, list the symbols in each IR file"));
76 static cl::opt<bool> SetMergedModule(
77 "set-merged-module", cl::init(false),
78 cl::desc("Use the first input module as the merged module"));
82 std::vector<bool> CanBeHidden;
86 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
87 const char *Msg, void *) {
99 errs() << "warning: ";
102 errs() << Msg << "\n";
105 static std::unique_ptr<LTOModule>
106 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
107 const TargetOptions &Options, std::string &Error) {
108 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
109 MemoryBuffer::getFile(Path);
110 if (std::error_code EC = BufferOrErr.getError()) {
111 Error = EC.message();
114 Buffer = std::move(BufferOrErr.get());
115 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
116 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
119 /// \brief List symbols in each IR file.
121 /// The main point here is to provide lit-testable coverage for the LTOModule
122 /// functionality that's exposed by the C API to list symbols. Moreover, this
123 /// provides testing coverage for modules that have been created in their own
125 static int listSymbols(StringRef Command, const TargetOptions &Options) {
126 for (auto &Filename : InputFilenames) {
128 std::unique_ptr<MemoryBuffer> Buffer;
129 std::unique_ptr<LTOModule> Module =
130 getLocalLTOModule(Filename, Buffer, Options, Error);
132 errs() << Command << ": error loading file '" << Filename
133 << "': " << Error << "\n";
138 outs() << Filename << ":\n";
139 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
140 outs() << Module->getSymbolName(I) << "\n";
145 int main(int argc, char **argv) {
146 // Print a stack trace if we signal out.
147 sys::PrintStackTraceOnErrorSignal();
148 PrettyStackTraceProgram X(argc, argv);
150 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
151 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
153 if (OptLevel < '0' || OptLevel > '3') {
154 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
158 // Initialize the configured targets.
159 InitializeAllTargets();
160 InitializeAllTargetMCs();
161 InitializeAllAsmPrinters();
162 InitializeAllAsmParsers();
164 // set up the TargetOptions for the machine
165 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
168 return listSymbols(argv[0], Options);
170 unsigned BaseArg = 0;
172 LTOCodeGenerator CodeGen;
174 if (UseDiagnosticHandler)
175 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
177 switch (RelocModel) {
179 CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_STATIC);
182 CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC);
184 case Reloc::DynamicNoPIC:
185 CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC);
188 CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DEFAULT);
191 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
192 CodeGen.setTargetOptions(Options);
194 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
195 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
196 DSOSymbolsSet.insert(DSOSymbols[i]);
198 std::vector<std::string> KeptDSOSyms;
200 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
202 std::unique_ptr<LTOModule> Module(
203 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
204 if (!error.empty()) {
205 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
206 << "': " << error << "\n";
210 LTOModule *LTOMod = Module.get();
212 // We use the first input module as the destination module when
213 // SetMergedModule is true.
214 if (SetMergedModule && i == BaseArg) {
215 // Transfer ownership to the code generator.
216 CodeGen.setModule(Module.release());
217 } else if (!CodeGen.addModule(Module.get()))
220 unsigned NumSyms = LTOMod->getSymbolCount();
221 for (unsigned I = 0; I < NumSyms; ++I) {
222 StringRef Name = LTOMod->getSymbolName(I);
223 if (!DSOSymbolsSet.count(Name))
225 lto_symbol_attributes Attrs = LTOMod->getSymbolAttributes(I);
226 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
227 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
228 KeptDSOSyms.push_back(Name);
232 // Add all the exported symbols to the table of symbols to preserve.
233 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
234 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
236 // Add all the dso symbols to the table of symbols to expose.
237 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
238 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
240 // Set cpu and attrs strings for the default target/subtarget.
241 CodeGen.setCpu(MCPU.c_str());
243 CodeGen.setOptLevel(OptLevel - '0');
246 for (unsigned i = 0; i < MAttrs.size(); ++i) {
249 attrs.append(MAttrs[i]);
253 CodeGen.setAttr(attrs.c_str());
255 if (!OutputFilename.empty()) {
256 std::string ErrorInfo;
257 std::unique_ptr<MemoryBuffer> Code = CodeGen.compile(
258 DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, ErrorInfo);
261 << ": error compiling the code: " << ErrorInfo << "\n";
266 raw_fd_ostream FileStream(OutputFilename, EC, sys::fs::F_None);
268 errs() << argv[0] << ": error opening the file '" << OutputFilename
269 << "': " << EC.message() << "\n";
273 FileStream.write(Code->getBufferStart(), Code->getBufferSize());
275 std::string ErrorInfo;
276 const char *OutputName = nullptr;
277 if (!CodeGen.compile_to_file(&OutputName, DisableInline,
278 DisableGVNLoadPRE, DisableLTOVectorization,
281 << ": error compiling the code: " << ErrorInfo
286 outs() << "Wrote native object file '" << OutputName << "'\n";