llvm-link.cpp 17 KB

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