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/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/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/InitLLVM.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/SystemUtils.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Support/WithColor.h"
35 #include "llvm/Transforms/IPO/FunctionImport.h"
36 #include "llvm/Transforms/IPO/Internalize.h"
37 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
38 
39 #include <memory>
40 #include <utility>
41 using namespace llvm;
42 
43 static cl::list<std::string>
44 InputFilenames(cl::Positional, cl::OneOrMore,
45                cl::desc("<input bitcode files>"));
46 
47 static cl::list<std::string> OverridingInputs(
48     "override", cl::ZeroOrMore, cl::value_desc("filename"),
49     cl::desc(
50         "input bitcode file which can override previously defined symbol(s)"));
51 
52 // Option to simulate function importing for testing. This enables using
53 // llvm-link to simulate ThinLTO backend processes.
54 static cl::list<std::string> Imports(
55     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
56     cl::desc("Pair of function name and filename, where function should be "
57              "imported from bitcode in filename"));
58 
59 // Option to support testing of function importing. The module summary
60 // must be specified in the case were we request imports via the -import
61 // option, as well as when compiling any module with functions that may be
62 // exported (imported by a different llvm-link -import invocation), to ensure
63 // consistent promotion and renaming of locals.
64 static cl::opt<std::string>
65     SummaryIndex("summary-index", cl::desc("Module summary index filename"),
66                  cl::init(""), cl::value_desc("filename"));
67 
68 static cl::opt<std::string>
69 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
70                cl::value_desc("filename"));
71 
72 static cl::opt<bool>
73 Internalize("internalize", cl::desc("Internalize linked symbols"));
74 
75 static cl::opt<bool>
76     DisableDITypeMap("disable-debug-info-type-map",
77                      cl::desc("Don't use a uniquing type map for debug info"));
78 
79 static cl::opt<bool>
80 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
81 
82 static cl::opt<bool>
83 Force("f", cl::desc("Enable binary output on terminals"));
84 
85 static cl::opt<bool>
86     DisableLazyLoad("disable-lazy-loading",
87                     cl::desc("Disable lazy module loading"));
88 
89 static cl::opt<bool>
90     OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden);
91 
92 static cl::opt<bool>
93 Verbose("v", cl::desc("Print information about actions taken"));
94 
95 static cl::opt<bool>
96 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
97 
98 static cl::opt<bool>
99 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
100                  cl::init(false));
101 
102 static cl::opt<bool> PreserveBitcodeUseListOrder(
103     "preserve-bc-uselistorder",
104     cl::desc("Preserve use-list order when writing LLVM bitcode."),
105     cl::init(true), cl::Hidden);
106 
107 static cl::opt<bool> PreserveAssemblyUseListOrder(
108     "preserve-ll-uselistorder",
109     cl::desc("Preserve use-list order when writing LLVM assembly."),
110     cl::init(false), cl::Hidden);
111 
112 static ExitOnError ExitOnErr;
113 
114 // Read the specified bitcode file in and return it. This routine searches the
115 // link path for the specified file to try to find it...
116 //
loadFile(const char * argv0,const std::string & FN,LLVMContext & Context,bool MaterializeMetadata=true)117 static std::unique_ptr<Module> loadFile(const char *argv0,
118                                         const std::string &FN,
119                                         LLVMContext &Context,
120                                         bool MaterializeMetadata = true) {
121   SMDiagnostic Err;
122   if (Verbose)
123     errs() << "Loading '" << FN << "'\n";
124   std::unique_ptr<Module> Result;
125   if (DisableLazyLoad)
126     Result = parseIRFile(FN, Err, Context);
127   else
128     Result = getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata);
129 
130   if (!Result) {
131     Err.print(argv0, errs());
132     return nullptr;
133   }
134 
135   if (MaterializeMetadata) {
136     ExitOnErr(Result->materializeMetadata());
137     UpgradeDebugInfo(*Result);
138   }
139 
140   return Result;
141 }
142 
143 namespace {
144 
145 /// Helper to load on demand a Module from file and cache it for subsequent
146 /// queries during function importing.
147 class ModuleLazyLoaderCache {
148   /// Cache of lazily loaded module for import.
149   StringMap<std::unique_ptr<Module>> ModuleMap;
150 
151   /// Retrieve a Module from the cache or lazily load it on demand.
152   std::function<std::unique_ptr<Module>(const char *argv0,
153                                         const std::string &FileName)>
154       createLazyModule;
155 
156 public:
157   /// Create the loader, Module will be initialized in \p Context.
ModuleLazyLoaderCache(std::function<std::unique_ptr<Module> (const char * argv0,const std::string & FileName)> createLazyModule)158   ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>(
159                             const char *argv0, const std::string &FileName)>
160                             createLazyModule)
161       : createLazyModule(std::move(createLazyModule)) {}
162 
163   /// Retrieve a Module from the cache or lazily load it on demand.
164   Module &operator()(const char *argv0, const std::string &FileName);
165 
takeModule(const std::string & FileName)166   std::unique_ptr<Module> takeModule(const std::string &FileName) {
167     auto I = ModuleMap.find(FileName);
168     assert(I != ModuleMap.end());
169     std::unique_ptr<Module> Ret = std::move(I->second);
170     ModuleMap.erase(I);
171     return Ret;
172   }
173 };
174 
175 // Get a Module for \p FileName from the cache, or load it lazily.
operator ()(const char * argv0,const std::string & Identifier)176 Module &ModuleLazyLoaderCache::operator()(const char *argv0,
177                                           const std::string &Identifier) {
178   auto &Module = ModuleMap[Identifier];
179   if (!Module)
180     Module = createLazyModule(argv0, Identifier);
181   return *Module;
182 }
183 } // anonymous namespace
184 
185 namespace {
186 struct LLVMLinkDiagnosticHandler : public DiagnosticHandler {
handleDiagnostics__anon144c7e4a0211::LLVMLinkDiagnosticHandler187   bool handleDiagnostics(const DiagnosticInfo &DI) override {
188     unsigned Severity = DI.getSeverity();
189     switch (Severity) {
190     case DS_Error:
191       WithColor::error();
192       break;
193     case DS_Warning:
194       if (SuppressWarnings)
195         return true;
196       WithColor::warning();
197       break;
198     case DS_Remark:
199     case DS_Note:
200       llvm_unreachable("Only expecting warnings and errors");
201     }
202 
203     DiagnosticPrinterRawOStream DP(errs());
204     DI.print(DP);
205     errs() << '\n';
206     return true;
207   }
208 };
209 }
210 
211 /// Import any functions requested via the -import option.
importFunctions(const char * argv0,Module & DestModule)212 static bool importFunctions(const char *argv0, Module &DestModule) {
213   if (SummaryIndex.empty())
214     return true;
215   std::unique_ptr<ModuleSummaryIndex> Index =
216       ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex));
217 
218   // Map of Module -> List of globals to import from the Module
219   FunctionImporter::ImportMapTy ImportList;
220 
221   auto ModuleLoader = [&DestModule](const char *argv0,
222                                     const std::string &Identifier) {
223     return loadFile(argv0, Identifier, DestModule.getContext(), false);
224   };
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       WithColor::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 = ImportList[FileName];
265     Entry.insert(F->getGUID());
266   }
267   auto CachedModuleLoader = [&](StringRef Identifier) {
268     return ModuleLoaderCache.takeModule(Identifier);
269   };
270   FunctionImporter Importer(*Index, CachedModuleLoader);
271   ExitOnErr(Importer.importFunctions(DestModule, ImportList));
272 
273   return true;
274 }
275 
linkFiles(const char * argv0,LLVMContext & Context,Linker & L,const cl::list<std::string> & Files,unsigned Flags)276 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
277                       const cl::list<std::string> &Files,
278                       unsigned Flags) {
279   // Filter out flags that don't apply to the first file we load.
280   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
281   // Similar to some flags, internalization doesn't apply to the first file.
282   bool InternalizeLinkedSymbols = false;
283   for (const auto &File : Files) {
284     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
285     if (!M.get()) {
286       errs() << argv0 << ": ";
287       WithColor::error() << " loading file '" << File << "'\n";
288       return false;
289     }
290 
291     // Note that when ODR merging types cannot verify input files in here When
292     // doing that debug metadata in the src module might already be pointing to
293     // the destination.
294     if (DisableDITypeMap && verifyModule(*M, &errs())) {
295       errs() << argv0 << ": " << File << ": ";
296       WithColor::error() << "input module is broken!\n";
297       return false;
298     }
299 
300     // If a module summary index is supplied, load it so linkInModule can treat
301     // local functions/variables as exported and promote if necessary.
302     if (!SummaryIndex.empty()) {
303       std::unique_ptr<ModuleSummaryIndex> Index =
304           ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex));
305 
306       // Conservatively mark all internal values as promoted, since this tool
307       // does not do the ThinLink that would normally determine what values to
308       // promote.
309       for (auto &I : *Index) {
310         for (auto &S : I.second.SummaryList) {
311           if (GlobalValue::isLocalLinkage(S->linkage()))
312             S->setLinkage(GlobalValue::ExternalLinkage);
313         }
314       }
315 
316       // Promotion
317       if (renameModuleForThinLTO(*M, *Index))
318         return true;
319     }
320 
321     if (Verbose)
322       errs() << "Linking in '" << File << "'\n";
323 
324     bool Err = false;
325     if (InternalizeLinkedSymbols) {
326       Err = L.linkInModule(
327           std::move(M), ApplicableFlags, [](Module &M, const StringSet<> &GVS) {
328             internalizeModule(M, [&GVS](const GlobalValue &GV) {
329               return !GV.hasName() || (GVS.count(GV.getName()) == 0);
330             });
331           });
332     } else {
333       Err = L.linkInModule(std::move(M), ApplicableFlags);
334     }
335 
336     if (Err)
337       return false;
338 
339     // Internalization applies to linking of subsequent files.
340     InternalizeLinkedSymbols = Internalize;
341 
342     // All linker flags apply to linking of subsequent files.
343     ApplicableFlags = Flags;
344   }
345 
346   return true;
347 }
348 
main(int argc,char ** argv)349 int main(int argc, char **argv) {
350   InitLLVM X(argc, argv);
351   ExitOnErr.setBanner(std::string(argv[0]) + ": ");
352 
353   LLVMContext Context;
354   Context.setDiagnosticHandler(
355     llvm::make_unique<LLVMLinkDiagnosticHandler>(), true);
356   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
357 
358   if (!DisableDITypeMap)
359     Context.enableDebugTypeODRUniquing();
360 
361   auto Composite = make_unique<Module>("llvm-link", Context);
362   Linker L(*Composite);
363 
364   unsigned Flags = Linker::Flags::None;
365   if (OnlyNeeded)
366     Flags |= Linker::Flags::LinkOnlyNeeded;
367 
368   // First add all the regular input files
369   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
370     return 1;
371 
372   // Next the -override ones.
373   if (!linkFiles(argv[0], Context, L, OverridingInputs,
374                  Flags | Linker::Flags::OverrideFromSrc))
375     return 1;
376 
377   // Import any functions requested via -import
378   if (!importFunctions(argv[0], *Composite))
379     return 1;
380 
381   if (DumpAsm)
382     errs() << "Here's the assembly:\n" << *Composite;
383 
384   std::error_code EC;
385   ToolOutputFile Out(OutputFilename, EC, sys::fs::F_None);
386   if (EC) {
387     WithColor::error() << EC.message() << '\n';
388     return 1;
389   }
390 
391   if (verifyModule(*Composite, &errs())) {
392     errs() << argv[0] << ": ";
393     WithColor::error() << "linked module is broken!\n";
394     return 1;
395   }
396 
397   if (Verbose)
398     errs() << "Writing bitcode...\n";
399   if (OutputAssembly) {
400     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
401   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
402     WriteBitcodeToFile(*Composite, Out.os(), PreserveBitcodeUseListOrder);
403 
404   // Declare success.
405   Out.keep();
406 
407   return 0;
408 }
409