1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility may be invoked in the following manner:
10 //  llvm-link a.bc b.bc c.bc -o x.bc
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/BinaryFormat/Magic.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/ModuleSummaryIndex.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/Linker/Linker.h"
27 #include "llvm/Object/Archive.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/InitLLVM.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/WithColor.h"
36 #include "llvm/Transforms/IPO/FunctionImport.h"
37 #include "llvm/Transforms/IPO/Internalize.h"
38 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
39 
40 #include <memory>
41 #include <utility>
42 using namespace llvm;
43 
44 static cl::list<std::string>
45 InputFilenames(cl::Positional, cl::OneOrMore,
46                cl::desc("<input bitcode files>"));
47 
48 static cl::list<std::string> OverridingInputs(
49     "override", cl::ZeroOrMore, cl::value_desc("filename"),
50     cl::desc(
51         "input bitcode file which can override previously defined symbol(s)"));
52 
53 // Option to simulate function importing for testing. This enables using
54 // llvm-link to simulate ThinLTO backend processes.
55 static cl::list<std::string> Imports(
56     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
57     cl::desc("Pair of function name and filename, where function should be "
58              "imported from bitcode in filename"));
59 
60 // Option to support testing of function importing. The module summary
61 // must be specified in the case were we request imports via the -import
62 // option, as well as when compiling any module with functions that may be
63 // exported (imported by a different llvm-link -import invocation), to ensure
64 // consistent promotion and renaming of locals.
65 static cl::opt<std::string>
66     SummaryIndex("summary-index", cl::desc("Module summary index filename"),
67                  cl::init(""), cl::value_desc("filename"));
68 
69 static cl::opt<std::string>
70 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
71                cl::value_desc("filename"));
72 
73 static cl::opt<bool>
74 Internalize("internalize", cl::desc("Internalize linked symbols"));
75 
76 static cl::opt<bool>
77     DisableDITypeMap("disable-debug-info-type-map",
78                      cl::desc("Don't use a uniquing type map for debug info"));
79 
80 static cl::opt<bool>
81 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
82 
83 static cl::opt<bool>
84 Force("f", cl::desc("Enable binary output on terminals"));
85 
86 static cl::opt<bool>
87     DisableLazyLoad("disable-lazy-loading",
88                     cl::desc("Disable lazy module loading"));
89 
90 static cl::opt<bool>
91     OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden);
92 
93 static cl::opt<bool>
94 Verbose("v", cl::desc("Print information about actions taken"));
95 
96 static cl::opt<bool>
97 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
98 
99 static cl::opt<bool>
100 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
101                  cl::init(false));
102 
103 static cl::opt<bool> PreserveBitcodeUseListOrder(
104     "preserve-bc-uselistorder",
105     cl::desc("Preserve use-list order when writing LLVM bitcode."),
106     cl::init(true), cl::Hidden);
107 
108 static cl::opt<bool> PreserveAssemblyUseListOrder(
109     "preserve-ll-uselistorder",
110     cl::desc("Preserve use-list order when writing LLVM assembly."),
111     cl::init(false), cl::Hidden);
112 
113 static ExitOnError ExitOnErr;
114 
115 // Read the specified bitcode file in and return it. This routine searches the
116 // link path for the specified file to try to find it...
117 //
118 static std::unique_ptr<Module> loadFile(const char *argv0,
119                                         std::unique_ptr<MemoryBuffer> Buffer,
120                                         LLVMContext &Context,
121                                         bool MaterializeMetadata = true) {
122   SMDiagnostic Err;
123   if (Verbose)
124     errs() << "Loading '" << Buffer->getBufferIdentifier() << "'\n";
125   std::unique_ptr<Module> Result;
126   if (DisableLazyLoad)
127     Result = parseIR(*Buffer, Err, Context);
128   else
129     Result =
130         getLazyIRModule(std::move(Buffer), Err, Context, !MaterializeMetadata);
131 
132   if (!Result) {
133     Err.print(argv0, errs());
134     return nullptr;
135   }
136 
137   if (MaterializeMetadata) {
138     ExitOnErr(Result->materializeMetadata());
139     UpgradeDebugInfo(*Result);
140   }
141 
142   return Result;
143 }
144 
145 static std::unique_ptr<Module> loadArFile(const char *Argv0,
146                                           std::unique_ptr<MemoryBuffer> Buffer,
147                                           LLVMContext &Context) {
148   std::unique_ptr<Module> Result(new Module("ArchiveModule", Context));
149   StringRef ArchiveName = Buffer->getBufferIdentifier();
150   if (Verbose)
151     errs() << "Reading library archive file '" << ArchiveName
152            << "' to memory\n";
153   Error Err = Error::success();
154   object::Archive Archive(*Buffer, Err);
155   ExitOnErr(std::move(Err));
156   Linker L(*Result);
157   for (const object::Archive::Child &C : Archive.children(Err)) {
158     Expected<StringRef> Ename = C.getName();
159     if (Error E = Ename.takeError()) {
160       errs() << Argv0 << ": ";
161       WithColor::error()
162           << " failed to read name of archive member"
163           << ArchiveName << "'\n";
164       return nullptr;
165     }
166     std::string ChildName = Ename.get().str();
167     if (Verbose)
168       errs() << "Parsing member '" << ChildName
169              << "' of archive library to module.\n";
170     SMDiagnostic ParseErr;
171     Expected<MemoryBufferRef> MemBuf = C.getMemoryBufferRef();
172     if (Error E = MemBuf.takeError()) {
173       errs() << Argv0 << ": ";
174       WithColor::error() << " loading memory for member '" << ChildName
175                          << "' of archive library failed'" << ArchiveName
176                          << "'\n";
177       return nullptr;
178     };
179 
180     if (!isBitcode(reinterpret_cast<const unsigned char *>
181                    (MemBuf.get().getBufferStart()),
182                    reinterpret_cast<const unsigned char *>
183                    (MemBuf.get().getBufferEnd()))) {
184       errs() << Argv0 << ": ";
185       WithColor::error() << "  member of archive is not a bitcode file: '"
186                          << ChildName << "'\n";
187       return nullptr;
188     }
189 
190     std::unique_ptr<Module> M;
191     if (DisableLazyLoad)
192       M = parseIR(MemBuf.get(), ParseErr, Context);
193     else
194       M = getLazyIRModule(MemoryBuffer::getMemBuffer(MemBuf.get(), false),
195                           ParseErr, Context);
196 
197     if (!M.get()) {
198       errs() << Argv0 << ": ";
199       WithColor::error() << " parsing member '" << ChildName
200                          << "' of archive library failed'" << ArchiveName
201                          << "'\n";
202       return nullptr;
203     }
204     if (Verbose)
205       errs() << "Linking member '" << ChildName << "' of archive library.\n";
206     if (L.linkInModule(std::move(M)))
207       return nullptr;
208   } // end for each child
209   ExitOnErr(std::move(Err));
210   return Result;
211 }
212 
213 namespace {
214 
215 /// Helper to load on demand a Module from file and cache it for subsequent
216 /// queries during function importing.
217 class ModuleLazyLoaderCache {
218   /// Cache of lazily loaded module for import.
219   StringMap<std::unique_ptr<Module>> ModuleMap;
220 
221   /// Retrieve a Module from the cache or lazily load it on demand.
222   std::function<std::unique_ptr<Module>(const char *argv0,
223                                         const std::string &FileName)>
224       createLazyModule;
225 
226 public:
227   /// Create the loader, Module will be initialized in \p Context.
228   ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>(
229                             const char *argv0, const std::string &FileName)>
230                             createLazyModule)
231       : createLazyModule(std::move(createLazyModule)) {}
232 
233   /// Retrieve a Module from the cache or lazily load it on demand.
234   Module &operator()(const char *argv0, const std::string &FileName);
235 
236   std::unique_ptr<Module> takeModule(const std::string &FileName) {
237     auto I = ModuleMap.find(FileName);
238     assert(I != ModuleMap.end());
239     std::unique_ptr<Module> Ret = std::move(I->second);
240     ModuleMap.erase(I);
241     return Ret;
242   }
243 };
244 
245 // Get a Module for \p FileName from the cache, or load it lazily.
246 Module &ModuleLazyLoaderCache::operator()(const char *argv0,
247                                           const std::string &Identifier) {
248   auto &Module = ModuleMap[Identifier];
249   if (!Module) {
250     Module = createLazyModule(argv0, Identifier);
251     assert(Module && "Failed to create lazy module!");
252   }
253   return *Module;
254 }
255 } // anonymous namespace
256 
257 namespace {
258 struct LLVMLinkDiagnosticHandler : public DiagnosticHandler {
259   bool handleDiagnostics(const DiagnosticInfo &DI) override {
260     unsigned Severity = DI.getSeverity();
261     switch (Severity) {
262     case DS_Error:
263       WithColor::error();
264       break;
265     case DS_Warning:
266       if (SuppressWarnings)
267         return true;
268       WithColor::warning();
269       break;
270     case DS_Remark:
271     case DS_Note:
272       llvm_unreachable("Only expecting warnings and errors");
273     }
274 
275     DiagnosticPrinterRawOStream DP(errs());
276     DI.print(DP);
277     errs() << '\n';
278     return true;
279   }
280 };
281 }
282 
283 /// Import any functions requested via the -import option.
284 static bool importFunctions(const char *argv0, Module &DestModule) {
285   if (SummaryIndex.empty())
286     return true;
287   std::unique_ptr<ModuleSummaryIndex> Index =
288       ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex));
289 
290   // Map of Module -> List of globals to import from the Module
291   FunctionImporter::ImportMapTy ImportList;
292 
293   auto ModuleLoader = [&DestModule](const char *argv0,
294                                     const std::string &Identifier) {
295     std::unique_ptr<MemoryBuffer> Buffer =
296         ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Identifier)));
297     return loadFile(argv0, std::move(Buffer), DestModule.getContext(), false);
298   };
299 
300   ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
301   for (const auto &Import : Imports) {
302     // Identify the requested function and its bitcode source file.
303     size_t Idx = Import.find(':');
304     if (Idx == std::string::npos) {
305       errs() << "Import parameter bad format: " << Import << "\n";
306       return false;
307     }
308     std::string FunctionName = Import.substr(0, Idx);
309     std::string FileName = Import.substr(Idx + 1, std::string::npos);
310 
311     // Load the specified source module.
312     auto &SrcModule = ModuleLoaderCache(argv0, FileName);
313 
314     if (verifyModule(SrcModule, &errs())) {
315       errs() << argv0 << ": " << FileName;
316       WithColor::error() << "input module is broken!\n";
317       return false;
318     }
319 
320     Function *F = SrcModule.getFunction(FunctionName);
321     if (!F) {
322       errs() << "Ignoring import request for non-existent function "
323              << FunctionName << " from " << FileName << "\n";
324       continue;
325     }
326     // We cannot import weak_any functions without possibly affecting the
327     // order they are seen and selected by the linker, changing program
328     // semantics.
329     if (F->hasWeakAnyLinkage()) {
330       errs() << "Ignoring import request for weak-any function " << FunctionName
331              << " from " << FileName << "\n";
332       continue;
333     }
334 
335     if (Verbose)
336       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
337 
338     auto &Entry = ImportList[FileName];
339     Entry.insert(F->getGUID());
340   }
341   auto CachedModuleLoader = [&](StringRef Identifier) {
342     return ModuleLoaderCache.takeModule(std::string(Identifier));
343   };
344   FunctionImporter Importer(*Index, CachedModuleLoader,
345                             /*ClearDSOLocalOnDeclarations=*/false);
346   ExitOnErr(Importer.importFunctions(DestModule, ImportList));
347 
348   return true;
349 }
350 
351 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
352                       const cl::list<std::string> &Files,
353                       unsigned Flags) {
354   // Filter out flags that don't apply to the first file we load.
355   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
356   // Similar to some flags, internalization doesn't apply to the first file.
357   bool InternalizeLinkedSymbols = false;
358   for (const auto &File : Files) {
359     std::unique_ptr<MemoryBuffer> Buffer =
360         ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(File)));
361 
362     std::unique_ptr<Module> M =
363         identify_magic(Buffer->getBuffer()) == file_magic::archive
364             ? loadArFile(argv0, std::move(Buffer), Context)
365             : loadFile(argv0, std::move(Buffer), Context);
366     if (!M.get()) {
367       errs() << argv0 << ": ";
368       WithColor::error() << " loading file '" << File << "'\n";
369       return false;
370     }
371 
372     // Note that when ODR merging types cannot verify input files in here When
373     // doing that debug metadata in the src module might already be pointing to
374     // the destination.
375     if (DisableDITypeMap && verifyModule(*M, &errs())) {
376       errs() << argv0 << ": " << File << ": ";
377       WithColor::error() << "input module is broken!\n";
378       return false;
379     }
380 
381     // If a module summary index is supplied, load it so linkInModule can treat
382     // local functions/variables as exported and promote if necessary.
383     if (!SummaryIndex.empty()) {
384       std::unique_ptr<ModuleSummaryIndex> Index =
385           ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex));
386 
387       // Conservatively mark all internal values as promoted, since this tool
388       // does not do the ThinLink that would normally determine what values to
389       // promote.
390       for (auto &I : *Index) {
391         for (auto &S : I.second.SummaryList) {
392           if (GlobalValue::isLocalLinkage(S->linkage()))
393             S->setLinkage(GlobalValue::ExternalLinkage);
394         }
395       }
396 
397       // Promotion
398       if (renameModuleForThinLTO(*M, *Index,
399                                  /*ClearDSOLocalOnDeclarations=*/false))
400         return true;
401     }
402 
403     if (Verbose)
404       errs() << "Linking in '" << File << "'\n";
405 
406     bool Err = false;
407     if (InternalizeLinkedSymbols) {
408       Err = L.linkInModule(
409           std::move(M), ApplicableFlags, [](Module &M, const StringSet<> &GVS) {
410             internalizeModule(M, [&GVS](const GlobalValue &GV) {
411               return !GV.hasName() || (GVS.count(GV.getName()) == 0);
412             });
413           });
414     } else {
415       Err = L.linkInModule(std::move(M), ApplicableFlags);
416     }
417 
418     if (Err)
419       return false;
420 
421     // Internalization applies to linking of subsequent files.
422     InternalizeLinkedSymbols = Internalize;
423 
424     // All linker flags apply to linking of subsequent files.
425     ApplicableFlags = Flags;
426   }
427 
428   return true;
429 }
430 
431 int main(int argc, char **argv) {
432   InitLLVM X(argc, argv);
433   ExitOnErr.setBanner(std::string(argv[0]) + ": ");
434 
435   LLVMContext Context;
436   Context.setDiagnosticHandler(
437     std::make_unique<LLVMLinkDiagnosticHandler>(), true);
438   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
439 
440   if (!DisableDITypeMap)
441     Context.enableDebugTypeODRUniquing();
442 
443   auto Composite = std::make_unique<Module>("llvm-link", Context);
444   Linker L(*Composite);
445 
446   unsigned Flags = Linker::Flags::None;
447   if (OnlyNeeded)
448     Flags |= Linker::Flags::LinkOnlyNeeded;
449 
450   // First add all the regular input files
451   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
452     return 1;
453 
454   // Next the -override ones.
455   if (!linkFiles(argv[0], Context, L, OverridingInputs,
456                  Flags | Linker::Flags::OverrideFromSrc))
457     return 1;
458 
459   // Import any functions requested via -import
460   if (!importFunctions(argv[0], *Composite))
461     return 1;
462 
463   if (DumpAsm)
464     errs() << "Here's the assembly:\n" << *Composite;
465 
466   std::error_code EC;
467   ToolOutputFile Out(OutputFilename, EC,
468                      OutputAssembly ? sys::fs::OF_Text : sys::fs::OF_None);
469   if (EC) {
470     WithColor::error() << EC.message() << '\n';
471     return 1;
472   }
473 
474   if (verifyModule(*Composite, &errs())) {
475     errs() << argv[0] << ": ";
476     WithColor::error() << "linked module is broken!\n";
477     return 1;
478   }
479 
480   if (Verbose)
481     errs() << "Writing bitcode...\n";
482   if (OutputAssembly) {
483     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
484   } else if (Force || !CheckBitcodeOutputToConsole(Out.os()))
485     WriteBitcodeToFile(*Composite, Out.os(), PreserveBitcodeUseListOrder);
486 
487   // Declare success.
488   Out.keep();
489 
490   return 0;
491 }
492