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/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/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 const std::string &FN, 120 LLVMContext &Context, 121 bool MaterializeMetadata = true) { 122 SMDiagnostic Err; 123 if (Verbose) 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. 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 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. 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 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) { 186 unsigned Severity = DI.getSeverity(); 187 switch (Severity) { 188 case DS_Error: 189 errs() << "ERROR: "; 190 break; 191 case DS_Warning: 192 if (SuppressWarnings) 193 return; 194 errs() << "WARNING: "; 195 break; 196 case DS_Remark: 197 case DS_Note: 198 llvm_unreachable("Only expecting warnings and errors"); 199 } 200 201 DiagnosticPrinterRawOStream DP(errs()); 202 DI.print(DP); 203 errs() << '\n'; 204 } 205 206 /// Import any functions requested via the -import option. 207 static bool importFunctions(const char *argv0, Module &DestModule) { 208 if (SummaryIndex.empty()) 209 return true; 210 std::unique_ptr<ModuleSummaryIndex> Index = 211 ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex)); 212 213 // Map of Module -> List of globals to import from the Module 214 FunctionImporter::ImportMapTy ImportList; 215 216 auto ModuleLoader = [&DestModule](const char *argv0, 217 const std::string &Identifier) { 218 return loadFile(argv0, Identifier, DestModule.getContext(), false); 219 }; 220 221 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader); 222 for (const auto &Import : Imports) { 223 // Identify the requested function and its bitcode source file. 224 size_t Idx = Import.find(':'); 225 if (Idx == std::string::npos) { 226 errs() << "Import parameter bad format: " << Import << "\n"; 227 return false; 228 } 229 std::string FunctionName = Import.substr(0, Idx); 230 std::string FileName = Import.substr(Idx + 1, std::string::npos); 231 232 // Load the specified source module. 233 auto &SrcModule = ModuleLoaderCache(argv0, FileName); 234 235 if (verifyModule(SrcModule, &errs())) { 236 errs() << argv0 << ": " << FileName 237 << ": error: input module is broken!\n"; 238 return false; 239 } 240 241 Function *F = SrcModule.getFunction(FunctionName); 242 if (!F) { 243 errs() << "Ignoring import request for non-existent function " 244 << FunctionName << " from " << FileName << "\n"; 245 continue; 246 } 247 // We cannot import weak_any functions without possibly affecting the 248 // order they are seen and selected by the linker, changing program 249 // semantics. 250 if (F->hasWeakAnyLinkage()) { 251 errs() << "Ignoring import request for weak-any function " << FunctionName 252 << " from " << FileName << "\n"; 253 continue; 254 } 255 256 if (Verbose) 257 errs() << "Importing " << FunctionName << " from " << FileName << "\n"; 258 259 auto &Entry = ImportList[FileName]; 260 Entry.insert(std::make_pair(F->getGUID(), /* (Unused) threshold */ 1.0)); 261 } 262 auto CachedModuleLoader = [&](StringRef Identifier) { 263 return ModuleLoaderCache.takeModule(Identifier); 264 }; 265 FunctionImporter Importer(*Index, CachedModuleLoader); 266 ExitOnErr(Importer.importFunctions(DestModule, ImportList)); 267 268 return true; 269 } 270 271 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L, 272 const cl::list<std::string> &Files, 273 unsigned Flags) { 274 // Filter out flags that don't apply to the first file we load. 275 unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc; 276 // Similar to some flags, internalization doesn't apply to the first file. 277 bool InternalizeLinkedSymbols = false; 278 for (const auto &File : Files) { 279 std::unique_ptr<Module> M = loadFile(argv0, File, Context); 280 if (!M.get()) { 281 errs() << argv0 << ": error loading file '" << File << "'\n"; 282 return false; 283 } 284 285 // Note that when ODR merging types cannot verify input files in here When 286 // doing that debug metadata in the src module might already be pointing to 287 // the destination. 288 if (DisableDITypeMap && verifyModule(*M, &errs())) { 289 errs() << argv0 << ": " << File << ": error: input module is broken!\n"; 290 return false; 291 } 292 293 // If a module summary index is supplied, load it so linkInModule can treat 294 // local functions/variables as exported and promote if necessary. 295 if (!SummaryIndex.empty()) { 296 std::unique_ptr<ModuleSummaryIndex> Index = 297 ExitOnErr(llvm::getModuleSummaryIndexForFile(SummaryIndex)); 298 299 // Conservatively mark all internal values as promoted, since this tool 300 // does not do the ThinLink that would normally determine what values to 301 // promote. 302 for (auto &I : *Index) { 303 for (auto &S : I.second.SummaryList) { 304 if (GlobalValue::isLocalLinkage(S->linkage())) 305 S->setLinkage(GlobalValue::ExternalLinkage); 306 } 307 } 308 309 // Promotion 310 if (renameModuleForThinLTO(*M, *Index)) 311 return true; 312 } 313 314 if (Verbose) 315 errs() << "Linking in '" << File << "'\n"; 316 317 bool Err = false; 318 if (InternalizeLinkedSymbols) { 319 Err = L.linkInModule( 320 std::move(M), ApplicableFlags, [](Module &M, const StringSet<> &GVS) { 321 internalizeModule(M, [&GVS](const GlobalValue &GV) { 322 return !GV.hasName() || (GVS.count(GV.getName()) == 0); 323 }); 324 }); 325 } else { 326 Err = L.linkInModule(std::move(M), ApplicableFlags); 327 } 328 329 if (Err) 330 return false; 331 332 // Internalization applies to linking of subsequent files. 333 InternalizeLinkedSymbols = Internalize; 334 335 // All linker flags apply to linking of subsequent files. 336 ApplicableFlags = Flags; 337 } 338 339 return true; 340 } 341 342 int main(int argc, char **argv) { 343 // Print a stack trace if we signal out. 344 sys::PrintStackTraceOnErrorSignal(argv[0]); 345 PrettyStackTraceProgram X(argc, argv); 346 347 ExitOnErr.setBanner(std::string(argv[0]) + ": "); 348 349 LLVMContext Context; 350 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true); 351 352 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 353 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n"); 354 355 if (!DisableDITypeMap) 356 Context.enableDebugTypeODRUniquing(); 357 358 auto Composite = make_unique<Module>("llvm-link", Context); 359 Linker L(*Composite); 360 361 unsigned Flags = Linker::Flags::None; 362 if (OnlyNeeded) 363 Flags |= Linker::Flags::LinkOnlyNeeded; 364 365 // First add all the regular input files 366 if (!linkFiles(argv[0], Context, L, InputFilenames, Flags)) 367 return 1; 368 369 // Next the -override ones. 370 if (!linkFiles(argv[0], Context, L, OverridingInputs, 371 Flags | Linker::Flags::OverrideFromSrc)) 372 return 1; 373 374 // Import any functions requested via -import 375 if (!importFunctions(argv[0], *Composite)) 376 return 1; 377 378 if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite; 379 380 std::error_code EC; 381 tool_output_file Out(OutputFilename, EC, sys::fs::F_None); 382 if (EC) { 383 errs() << EC.message() << '\n'; 384 return 1; 385 } 386 387 if (verifyModule(*Composite, &errs())) { 388 errs() << argv[0] << ": error: linked module is broken!\n"; 389 return 1; 390 } 391 392 if (Verbose) errs() << "Writing bitcode...\n"; 393 if (OutputAssembly) { 394 Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder); 395 } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true)) 396 WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder); 397 398 // Declare success. 399 Out.keep(); 400 401 return 0; 402 } 403