1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
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 utility may be invoked in the following manner:
11 //  llvm-link a.bc b.bc c.bc -o x.bc
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Linker/Linker.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/FunctionInfo.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/Object/FunctionIndexObjectFile.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include <memory>
37 using namespace llvm;
38 
39 static cl::list<std::string>
40 InputFilenames(cl::Positional, cl::OneOrMore,
41                cl::desc("<input bitcode files>"));
42 
43 static cl::list<std::string> OverridingInputs(
44     "override", cl::ZeroOrMore, cl::value_desc("filename"),
45     cl::desc(
46         "input bitcode file which can override previously defined symbol(s)"));
47 
48 // Option to simulate function importing for testing. This enables using
49 // llvm-link to simulate ThinLTO backend processes.
50 static cl::list<std::string> Imports(
51     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
52     cl::desc("Pair of function name and filename, where function should be "
53              "imported from bitcode in filename"));
54 
55 // Option to support testing of function importing. The function index
56 // must be specified in the case were we request imports via the -import
57 // option, as well as when compiling any module with functions that may be
58 // exported (imported by a different llvm-link -import invocation), to ensure
59 // consistent promotion and renaming of locals.
60 static cl::opt<std::string> FunctionIndex("functionindex",
61                                           cl::desc("Function index filename"),
62                                           cl::init(""),
63                                           cl::value_desc("filename"));
64 
65 static cl::opt<std::string>
66 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
67                cl::value_desc("filename"));
68 
69 static cl::opt<bool>
70 Internalize("internalize", cl::desc("Internalize linked symbols"));
71 
72 static cl::opt<bool>
73 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
74 
75 static cl::opt<bool>
76 Force("f", cl::desc("Enable binary output on terminals"));
77 
78 static cl::opt<bool>
79 OutputAssembly("S",
80          cl::desc("Write output as LLVM assembly"), cl::Hidden);
81 
82 static cl::opt<bool>
83 Verbose("v", cl::desc("Print information about actions taken"));
84 
85 static cl::opt<bool>
86 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
87 
88 static cl::opt<bool>
89 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
90                  cl::init(false));
91 
92 static cl::opt<bool> PreserveBitcodeUseListOrder(
93     "preserve-bc-uselistorder",
94     cl::desc("Preserve use-list order when writing LLVM bitcode."),
95     cl::init(true), cl::Hidden);
96 
97 static cl::opt<bool> PreserveAssemblyUseListOrder(
98     "preserve-ll-uselistorder",
99     cl::desc("Preserve use-list order when writing LLVM assembly."),
100     cl::init(false), cl::Hidden);
101 
102 // Read the specified bitcode file in and return it. This routine searches the
103 // link path for the specified file to try to find it...
104 //
105 static std::unique_ptr<Module> loadFile(const char *argv0,
106                                         const std::string &FN,
107                                         LLVMContext &Context,
108                                         bool MaterializeMetadata = true) {
109   SMDiagnostic Err;
110   if (Verbose) errs() << "Loading '" << FN << "'\n";
111   std::unique_ptr<Module> Result =
112       getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata);
113   if (!Result)
114     Err.print(argv0, errs());
115 
116   if (MaterializeMetadata) {
117     Result->materializeMetadata();
118     UpgradeDebugInfo(*Result);
119   }
120 
121   return Result;
122 }
123 
124 static void diagnosticHandler(const DiagnosticInfo &DI) {
125   unsigned Severity = DI.getSeverity();
126   switch (Severity) {
127   case DS_Error:
128     errs() << "ERROR: ";
129     break;
130   case DS_Warning:
131     if (SuppressWarnings)
132       return;
133     errs() << "WARNING: ";
134     break;
135   case DS_Remark:
136   case DS_Note:
137     llvm_unreachable("Only expecting warnings and errors");
138   }
139 
140   DiagnosticPrinterRawOStream DP(errs());
141   DI.print(DP);
142   errs() << '\n';
143 }
144 
145 static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) {
146   diagnosticHandler(DI);
147 }
148 
149 /// Import any functions requested via the -import option.
150 static bool importFunctions(const char *argv0, LLVMContext &Context,
151                             Linker &L) {
152   StringMap<std::unique_ptr<DenseMap<unsigned, MDNode *>>>
153       ModuleToTempMDValsMap;
154   for (const auto &Import : Imports) {
155     // Identify the requested function and its bitcode source file.
156     size_t Idx = Import.find(':');
157     if (Idx == std::string::npos) {
158       errs() << "Import parameter bad format: " << Import << "\n";
159       return false;
160     }
161     std::string FunctionName = Import.substr(0, Idx);
162     std::string FileName = Import.substr(Idx + 1, std::string::npos);
163 
164     // Load the specified source module.
165     std::unique_ptr<Module> M = loadFile(argv0, FileName, Context, false);
166     if (!M.get()) {
167       errs() << argv0 << ": error loading file '" << FileName << "'\n";
168       return false;
169     }
170 
171     if (verifyModule(*M, &errs())) {
172       errs() << argv0 << ": " << FileName
173              << ": error: input module is broken!\n";
174       return false;
175     }
176 
177     Function *F = M->getFunction(FunctionName);
178     if (!F) {
179       errs() << "Ignoring import request for non-existent function "
180              << FunctionName << " from " << FileName << "\n";
181       continue;
182     }
183     // We cannot import weak_any functions without possibly affecting the
184     // order they are seen and selected by the linker, changing program
185     // semantics.
186     if (F->hasWeakAnyLinkage()) {
187       errs() << "Ignoring import request for weak-any function " << FunctionName
188              << " from " << FileName << "\n";
189       continue;
190     }
191 
192     if (Verbose)
193       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
194 
195     std::unique_ptr<FunctionInfoIndex> Index;
196     if (!FunctionIndex.empty()) {
197       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
198           llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
199       std::error_code EC = IndexOrErr.getError();
200       if (EC) {
201         errs() << EC.message() << '\n';
202         return false;
203       }
204       Index = std::move(IndexOrErr.get());
205     }
206 
207     // Save the mapping of value ids to temporary metadata created when
208     // importing this function. If we have already imported from this module,
209     // add new temporary metadata to the existing mapping.
210     auto &TempMDVals = ModuleToTempMDValsMap[FileName];
211     if (!TempMDVals)
212       TempMDVals = llvm::make_unique<DenseMap<unsigned, MDNode *>>();
213 
214     // Link in the specified function.
215     DenseSet<const GlobalValue *> FunctionsToImport;
216     FunctionsToImport.insert(F);
217     if (L.linkInModule(std::move(M), Linker::Flags::None, Index.get(),
218                        &FunctionsToImport, TempMDVals.get()))
219       return false;
220   }
221 
222   // Now link in metadata for all modules from which we imported functions.
223   for (StringMapEntry<std::unique_ptr<DenseMap<unsigned, MDNode *>>> &SME :
224        ModuleToTempMDValsMap) {
225     // Load the specified source module.
226     std::unique_ptr<Module> M = loadFile(argv0, SME.getKey(), Context, true);
227     if (!M.get()) {
228       errs() << argv0 << ": error loading file '" << SME.getKey() << "'\n";
229       return false;
230     }
231 
232     if (verifyModule(*M, &errs())) {
233       errs() << argv0 << ": " << SME.getKey()
234              << ": error: input module is broken!\n";
235       return false;
236     }
237 
238     // Link in all necessary metadata from this module.
239     if (L.linkInMetadata(std::move(M), SME.getValue().get()))
240       return false;
241   }
242   return true;
243 }
244 
245 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
246                       const cl::list<std::string> &Files,
247                       unsigned Flags) {
248   // Filter out flags that don't apply to the first file we load.
249   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
250   for (const auto &File : Files) {
251     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
252     if (!M.get()) {
253       errs() << argv0 << ": error loading file '" << File << "'\n";
254       return false;
255     }
256 
257     if (verifyModule(*M, &errs())) {
258       errs() << argv0 << ": " << File << ": error: input module is broken!\n";
259       return false;
260     }
261 
262     // If a function index is supplied, load it so linkInModule can treat
263     // local functions/variables as exported and promote if necessary.
264     std::unique_ptr<FunctionInfoIndex> Index;
265     if (!FunctionIndex.empty()) {
266       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
267           llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
268       std::error_code EC = IndexOrErr.getError();
269       if (EC) {
270         errs() << EC.message() << '\n';
271         return false;
272       }
273       Index = std::move(IndexOrErr.get());
274     }
275 
276     if (Verbose)
277       errs() << "Linking in '" << File << "'\n";
278 
279     if (L.linkInModule(std::move(M), ApplicableFlags, Index.get()))
280       return false;
281     // All linker flags apply to linking of subsequent files.
282     ApplicableFlags = Flags;
283   }
284 
285   return true;
286 }
287 
288 int main(int argc, char **argv) {
289   // Print a stack trace if we signal out.
290   sys::PrintStackTraceOnErrorSignal();
291   PrettyStackTraceProgram X(argc, argv);
292 
293   LLVMContext &Context = getGlobalContext();
294   Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
295 
296   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
297   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
298 
299   auto Composite = make_unique<Module>("llvm-link", Context);
300   Linker L(*Composite);
301 
302   unsigned Flags = Linker::Flags::None;
303   if (Internalize)
304     Flags |= Linker::Flags::InternalizeLinkedSymbols;
305   if (OnlyNeeded)
306     Flags |= Linker::Flags::LinkOnlyNeeded;
307 
308   // First add all the regular input files
309   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
310     return 1;
311 
312   // Next the -override ones.
313   if (!linkFiles(argv[0], Context, L, OverridingInputs,
314                  Flags | Linker::Flags::OverrideFromSrc))
315     return 1;
316 
317   // Import any functions requested via -import
318   if (!importFunctions(argv[0], Context, L))
319     return 1;
320 
321   if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
322 
323   std::error_code EC;
324   tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
325   if (EC) {
326     errs() << EC.message() << '\n';
327     return 1;
328   }
329 
330   if (verifyModule(*Composite, &errs())) {
331     errs() << argv[0] << ": error: linked module is broken!\n";
332     return 1;
333   }
334 
335   if (Verbose) errs() << "Writing bitcode...\n";
336   if (OutputAssembly) {
337     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
338   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
339     WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
340 
341   // Declare success.
342   Out.keep();
343 
344   return 0;
345 }
346