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/ADT/STLExtras.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/DiagnosticInfo.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/ModuleSummaryIndex.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/Object/ModuleSummaryIndexObjectFile.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 "llvm/Transforms/Utils/FunctionImportUtils.h"
37 
38 #include <memory>
39 #include <utility>
40 using namespace llvm;
41 
42 static cl::list<std::string>
43 InputFilenames(cl::Positional, cl::OneOrMore,
44                cl::desc("<input bitcode files>"));
45 
46 static cl::list<std::string> OverridingInputs(
47     "override", cl::ZeroOrMore, cl::value_desc("filename"),
48     cl::desc(
49         "input bitcode file which can override previously defined symbol(s)"));
50 
51 // Option to simulate function importing for testing. This enables using
52 // llvm-link to simulate ThinLTO backend processes.
53 static cl::list<std::string> Imports(
54     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
55     cl::desc("Pair of function name and filename, where function should be "
56              "imported from bitcode in filename"));
57 
58 // Option to support testing of function importing. The module summary
59 // must be specified in the case were we request imports via the -import
60 // option, as well as when compiling any module with functions that may be
61 // exported (imported by a different llvm-link -import invocation), to ensure
62 // consistent promotion and renaming of locals.
63 static cl::opt<std::string>
64     SummaryIndex("summary-index", cl::desc("Module summary index filename"),
65                  cl::init(""), cl::value_desc("filename"));
66 
67 static cl::opt<std::string>
68 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
69                cl::value_desc("filename"));
70 
71 static cl::opt<bool>
72 Internalize("internalize", cl::desc("Internalize linked symbols"));
73 
74 static cl::opt<bool>
75     DisableDITypeMap("disable-debug-info-type-map",
76                      cl::desc("Don't use a uniquing type map for debug info"));
77 
78 static cl::opt<bool>
79 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
80 
81 static cl::opt<bool>
82 Force("f", cl::desc("Enable binary output on terminals"));
83 
84 static cl::opt<bool>
85     DisableLazyLoad("disable-lazy-loading",
86                     cl::desc("Disable lazy module loading"));
87 
88 static cl::opt<bool>
89     OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden);
90 
91 static cl::opt<bool>
92 Verbose("v", cl::desc("Print information about actions taken"));
93 
94 static cl::opt<bool>
95 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
96 
97 static cl::opt<bool>
98 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
99                  cl::init(false));
100 
101 static cl::opt<bool> PreserveBitcodeUseListOrder(
102     "preserve-bc-uselistorder",
103     cl::desc("Preserve use-list order when writing LLVM bitcode."),
104     cl::init(true), cl::Hidden);
105 
106 static cl::opt<bool> PreserveAssemblyUseListOrder(
107     "preserve-ll-uselistorder",
108     cl::desc("Preserve use-list order when writing LLVM assembly."),
109     cl::init(false), cl::Hidden);
110 
111 // Read the specified bitcode file in and return it. This routine searches the
112 // link path for the specified file to try to find it...
113 //
114 static std::unique_ptr<Module> loadFile(const char *argv0,
115                                         const std::string &FN,
116                                         LLVMContext &Context,
117                                         bool MaterializeMetadata = true) {
118   SMDiagnostic Err;
119   if (Verbose) errs() << "Loading '" << FN << "'\n";
120   std::unique_ptr<Module> Result;
121   if (DisableLazyLoad)
122     Result = parseIRFile(FN, Err, Context);
123   else
124     Result = getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata);
125 
126   if (!Result) {
127     Err.print(argv0, errs());
128     return nullptr;
129   }
130 
131   if (MaterializeMetadata) {
132     Result->materializeMetadata();
133     UpgradeDebugInfo(*Result);
134   }
135 
136   return Result;
137 }
138 
139 namespace {
140 
141 /// Helper to load on demand a Module from file and cache it for subsequent
142 /// queries during function importing.
143 class ModuleLazyLoaderCache {
144   /// Cache of lazily loaded module for import.
145   StringMap<std::unique_ptr<Module>> ModuleMap;
146 
147   /// Retrieve a Module from the cache or lazily load it on demand.
148   std::function<std::unique_ptr<Module>(const char *argv0,
149                                         const std::string &FileName)>
150       createLazyModule;
151 
152 public:
153   /// Create the loader, Module will be initialized in \p Context.
154   ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>(
155                             const char *argv0, const std::string &FileName)>
156                             createLazyModule)
157       : createLazyModule(std::move(createLazyModule)) {}
158 
159   /// Retrieve a Module from the cache or lazily load it on demand.
160   Module &operator()(const char *argv0, const std::string &FileName);
161 
162   std::unique_ptr<Module> takeModule(const std::string &FileName) {
163     auto I = ModuleMap.find(FileName);
164     assert(I != ModuleMap.end());
165     std::unique_ptr<Module> Ret = std::move(I->second);
166     ModuleMap.erase(I);
167     return Ret;
168   }
169 };
170 
171 // Get a Module for \p FileName from the cache, or load it lazily.
172 Module &ModuleLazyLoaderCache::operator()(const char *argv0,
173                                           const std::string &Identifier) {
174   auto &Module = ModuleMap[Identifier];
175   if (!Module)
176     Module = createLazyModule(argv0, Identifier);
177   return *Module;
178 }
179 } // anonymous namespace
180 
181 static void diagnosticHandler(const DiagnosticInfo &DI) {
182   unsigned Severity = DI.getSeverity();
183   switch (Severity) {
184   case DS_Error:
185     errs() << "ERROR: ";
186     break;
187   case DS_Warning:
188     if (SuppressWarnings)
189       return;
190     errs() << "WARNING: ";
191     break;
192   case DS_Remark:
193   case DS_Note:
194     llvm_unreachable("Only expecting warnings and errors");
195   }
196 
197   DiagnosticPrinterRawOStream DP(errs());
198   DI.print(DP);
199   errs() << '\n';
200 }
201 
202 static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) {
203   diagnosticHandler(DI);
204 }
205 
206 /// Import any functions requested via the -import option.
207 static bool importFunctions(const char *argv0, LLVMContext &Context,
208                             Linker &L) {
209   if (SummaryIndex.empty())
210     return true;
211   ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
212       llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler);
213   std::error_code EC = IndexOrErr.getError();
214   if (EC) {
215     errs() << EC.message() << '\n';
216     return false;
217   }
218   auto Index = std::move(IndexOrErr.get());
219 
220   // Map of Module -> List of globals to import from the Module
221   std::map<StringRef, DenseSet<const GlobalValue *>> ModuleToGlobalsToImportMap;
222   auto ModuleLoader = [&Context](const char *argv0,
223                                  const std::string &Identifier) {
224     return loadFile(argv0, Identifier, Context, false);
225   };
226   ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
227   for (const auto &Import : Imports) {
228     // Identify the requested function and its bitcode source file.
229     size_t Idx = Import.find(':');
230     if (Idx == std::string::npos) {
231       errs() << "Import parameter bad format: " << Import << "\n";
232       return false;
233     }
234     std::string FunctionName = Import.substr(0, Idx);
235     std::string FileName = Import.substr(Idx + 1, std::string::npos);
236 
237     // Load the specified source module.
238     auto &SrcModule = ModuleLoaderCache(argv0, FileName);
239 
240     if (verifyModule(SrcModule, &errs())) {
241       errs() << argv0 << ": " << FileName
242              << ": error: input module is broken!\n";
243       return false;
244     }
245 
246     Function *F = SrcModule.getFunction(FunctionName);
247     if (!F) {
248       errs() << "Ignoring import request for non-existent function "
249              << FunctionName << " from " << FileName << "\n";
250       continue;
251     }
252     // We cannot import weak_any functions without possibly affecting the
253     // order they are seen and selected by the linker, changing program
254     // semantics.
255     if (F->hasWeakAnyLinkage()) {
256       errs() << "Ignoring import request for weak-any function " << FunctionName
257              << " from " << FileName << "\n";
258       continue;
259     }
260 
261     if (Verbose)
262       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
263 
264     auto &Entry = ModuleToGlobalsToImportMap[SrcModule.getModuleIdentifier()];
265     Entry.insert(F);
266 
267     F->materialize();
268   }
269 
270   // Do the actual import of globals now, one Module at a time
271   for (auto &GlobalsToImportPerModule : ModuleToGlobalsToImportMap) {
272     // Get the module for the import
273     auto &GlobalsToImport = GlobalsToImportPerModule.second;
274     std::unique_ptr<Module> SrcModule =
275         ModuleLoaderCache.takeModule(GlobalsToImportPerModule.first);
276     assert(&Context == &SrcModule->getContext() && "Context mismatch");
277 
278     // If modules were created with lazy metadata loading, materialize it
279     // now, before linking it (otherwise this will be a noop).
280     SrcModule->materializeMetadata();
281     UpgradeDebugInfo(*SrcModule);
282 
283     // Linkage Promotion and renaming
284     if (renameModuleForThinLTO(*SrcModule, *Index, &GlobalsToImport))
285       return true;
286 
287     // Instruct the linker to not automatically import linkonce defintion.
288     unsigned Flags = Linker::Flags::DontForceLinkLinkonceODR;
289 
290     if (L.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
291       return false;
292   }
293 
294   return true;
295 }
296 
297 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
298                       const cl::list<std::string> &Files,
299                       unsigned Flags) {
300   // Filter out flags that don't apply to the first file we load.
301   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
302   for (const auto &File : Files) {
303     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
304     if (!M.get()) {
305       errs() << argv0 << ": error loading file '" << File << "'\n";
306       return false;
307     }
308 
309     // Note that when ODR merging types cannot verify input files in here When
310     // doing that debug metadata in the src module might already be pointing to
311     // the destination.
312     if (DisableDITypeMap && verifyModule(*M, &errs())) {
313       errs() << argv0 << ": " << File << ": error: input module is broken!\n";
314       return false;
315     }
316 
317     // If a module summary index is supplied, load it so linkInModule can treat
318     // local functions/variables as exported and promote if necessary.
319     if (!SummaryIndex.empty()) {
320       ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
321           llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler);
322       std::error_code EC = IndexOrErr.getError();
323       if (EC) {
324         errs() << EC.message() << '\n';
325         return false;
326       }
327       auto Index = std::move(IndexOrErr.get());
328 
329       // Promotion
330       if (renameModuleForThinLTO(*M, *Index))
331         return true;
332     }
333 
334     if (Verbose)
335       errs() << "Linking in '" << File << "'\n";
336 
337     if (L.linkInModule(std::move(M), ApplicableFlags))
338       return false;
339     // All linker flags apply to linking of subsequent files.
340     ApplicableFlags = Flags;
341   }
342 
343   return true;
344 }
345 
346 int main(int argc, char **argv) {
347   // Print a stack trace if we signal out.
348   sys::PrintStackTraceOnErrorSignal(argv[0]);
349   PrettyStackTraceProgram X(argc, argv);
350 
351   LLVMContext Context;
352   Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
353 
354   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
355   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
356 
357   if (!DisableDITypeMap)
358     Context.enableDebugTypeODRUniquing();
359 
360   auto Composite = make_unique<Module>("llvm-link", Context);
361   Linker L(*Composite);
362 
363   unsigned Flags = Linker::Flags::None;
364   if (Internalize)
365     Flags |= Linker::Flags::InternalizeLinkedSymbols;
366   if (OnlyNeeded)
367     Flags |= Linker::Flags::LinkOnlyNeeded;
368 
369   // First add all the regular input files
370   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
371     return 1;
372 
373   // Next the -override ones.
374   if (!linkFiles(argv[0], Context, L, OverridingInputs,
375                  Flags | Linker::Flags::OverrideFromSrc))
376     return 1;
377 
378   // Import any functions requested via -import
379   if (!importFunctions(argv[0], Context, L))
380     return 1;
381 
382   if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
383 
384   std::error_code EC;
385   tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
386   if (EC) {
387     errs() << EC.message() << '\n';
388     return 1;
389   }
390 
391   if (verifyModule(*Composite, &errs())) {
392     errs() << argv[0] << ": error: linked module is broken!\n";
393     return 1;
394   }
395 
396   if (Verbose) errs() << "Writing bitcode...\n";
397   if (OutputAssembly) {
398     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
399   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
400     WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
401 
402   // Declare success.
403   Out.keep();
404 
405   return 0;
406 }
407