1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines to handle linking together LLVM bytecode files,
11 // and to handle annoying things like static libraries.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/WriteBytecodePass.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/Linker.h"
24 #include "Support/CommandLine.h"
25 #include "Support/FileUtilities.h"
26 #include "Support/Signals.h"
27 #include "Support/SystemUtils.h"
33 /// FileExists - Returns true IFF a file named FN exists and is readable.
35 static inline bool FileExists(const std::string &FN) {
36 return access(FN.c_str(), R_OK | F_OK) != -1;
39 /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
40 /// archive. The file named FN must exist.
42 static inline bool IsArchive(const std::string &FN) {
43 // Inspect the beginning of the file to see if it contains the "ar" magic
45 std::string ArchiveMagic("!<arch>\012");
46 char buf[1 + ArchiveMagic.size()];
47 std::ifstream f(FN.c_str());
48 f.read(buf, ArchiveMagic.size());
49 buf[ArchiveMagic.size()] = '\0';
50 return ArchiveMagic == buf;
53 /// FindLib - locates a particular library. It will prepend and append
54 /// various directories, prefixes, and suffixes until it can find the library.
57 /// Filename - Name of the file to find.
58 /// Paths - List of directories to search.
64 /// The name of the file is returned.
65 /// If the file is not found, an empty string is returned.
68 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
69 // Determine if the pathname can be found as it stands.
70 if (FileExists(Filename))
73 // If that doesn't work, convert the name into a library name.
74 std::string LibName = "lib" + Filename;
76 // Iterate over the directories in Paths to see if we can find the library
78 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
79 std::string Directory = Paths[Index] + "/";
81 if (FileExists(Directory + LibName + ".bc"))
82 return Directory + LibName + ".bc";
84 if (FileExists(Directory + LibName + ".so"))
85 return Directory + LibName + ".so";
87 if (FileExists(Directory + LibName + ".a"))
88 return Directory + LibName + ".a";
91 // One last hope: Check LLVM_LIB_SEARCH_PATH.
92 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
93 if (SearchPath == NULL)
96 LibName = std::string(SearchPath) + "/" + LibName;
97 if (FileExists(LibName))
100 return std::string();
103 /// GetAllDefinedSymbols - Modifies its parameter DefinedSymbols to contain the
104 /// name of each externally-visible symbol defined in M.
106 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
107 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
108 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
109 DefinedSymbols.insert(I->getName());
110 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
111 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
112 DefinedSymbols.insert(I->getName());
115 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
116 /// exist in an LLVM module. This is a bit tricky because there may be two
117 /// symbols with the same name but different LLVM types that will be resolved to
118 /// each other but aren't currently (thus we need to treat it as resolved).
121 /// M - The module in which to find undefined symbols.
124 /// UndefinedSymbols - A set of C++ strings containing the name of all
125 /// undefined symbols.
131 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
132 std::set<std::string> DefinedSymbols;
133 UndefinedSymbols.clear(); // Start out empty
135 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
138 UndefinedSymbols.insert(I->getName());
139 else if (!I->hasInternalLinkage())
140 DefinedSymbols.insert(I->getName());
142 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
145 UndefinedSymbols.insert(I->getName());
146 else if (!I->hasInternalLinkage())
147 DefinedSymbols.insert(I->getName());
150 // Prune out any defined symbols from the undefined symbols set...
151 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
152 I != UndefinedSymbols.end(); )
153 if (DefinedSymbols.count(*I))
154 UndefinedSymbols.erase(I++); // This symbol really is defined!
156 ++I; // Keep this symbol in the undefined symbols list
160 /// LoadObject - reads the specified bytecode object file.
163 /// FN - The name of the file to load.
166 /// OutErrorMessage - The error message to give back to the caller.
169 /// A pointer to a module represening the bytecode file is returned.
170 /// If an error occurs, the pointer is 0.
172 std::auto_ptr<Module>
173 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
174 std::string ErrorMessage;
175 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
176 if (Result) return std::auto_ptr<Module>(Result);
177 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
178 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
179 return std::auto_ptr<Module>();
182 /// LinkInArchive - opens an archive library and link in all objects which
183 /// provide symbols that are currently undefined.
186 /// M - The module in which to link the archives.
187 /// Filename - The pathname of the archive.
188 /// Verbose - Flags whether verbose messages should be printed.
191 /// ErrorMessage - A C++ string detailing what error occurred, if any.
194 /// TRUE - An error occurred.
195 /// FALSE - No errors.
197 static bool LinkInArchive(Module *M,
198 const std::string &Filename,
199 std::string &ErrorMessage,
202 // Find all of the symbols currently undefined in the bytecode program.
203 // If all the symbols are defined, the program is complete, and there is
204 // no reason to link in any archive files.
205 std::set<std::string> UndefinedSymbols;
206 GetAllUndefinedSymbols(M, UndefinedSymbols);
207 if (UndefinedSymbols.empty()) {
208 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
209 return false; // No need to link anything in!
212 // Load in the archive objects.
213 if (Verbose) std::cerr << " Loading archive file '" << Filename << "'\n";
214 std::vector<Module*> Objects;
215 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
218 // Figure out which symbols are defined by all of the modules in the archive.
219 std::vector<std::set<std::string> > DefinedSymbols;
220 DefinedSymbols.resize(Objects.size());
221 for (unsigned i = 0; i != Objects.size(); ++i) {
222 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
225 // While we are linking in object files, loop.
230 for (unsigned i = 0; i != Objects.size(); ++i) {
231 // Consider whether we need to link in this module... we only need to
232 // link it in if it defines some symbol which is so far undefined.
234 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
236 bool ObjectRequired = false;
237 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
238 E = UndefinedSymbols.end(); I != E; ++I)
239 if (DefSymbols.count(*I)) {
241 std::cerr << " Found object providing symbol '" << *I << "'...\n";
242 ObjectRequired = true;
246 // We DO need to link this object into the program...
247 if (ObjectRequired) {
248 if (LinkModules(M, Objects[i], &ErrorMessage))
249 return true; // Couldn't link in the right object file...
251 // Since we have linked in this object, delete it from the list of
252 // objects to consider in this archive file.
253 std::swap(Objects[i], Objects.back());
254 std::swap(DefinedSymbols[i], DefinedSymbols.back());
256 DefinedSymbols.pop_back();
257 --i; // Do not skip an entry
259 // The undefined symbols set should have shrunk.
260 GetAllUndefinedSymbols(M, UndefinedSymbols);
261 Linked = true; // We have linked something in!
269 /// LinkInFile - opens a bytecode file and links in all objects which
270 /// provide symbols that are currently undefined.
273 /// HeadModule - The module in which to link the bytecode file.
274 /// Filename - The pathname of the bytecode file.
275 /// Verbose - Flags whether verbose messages should be printed.
278 /// ErrorMessage - A C++ string detailing what error occurred, if any.
281 /// TRUE - An error occurred.
282 /// FALSE - No errors.
284 static bool LinkInFile(Module *HeadModule,
285 const std::string &Filename,
286 std::string &ErrorMessage,
289 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
290 if (M.get() == 0) return true;
291 bool Result = LinkModules(HeadModule, M.get(), &ErrorMessage);
292 if (Verbose) std::cerr << "Linked in bytecode file '" << Filename << "'\n";
296 /// LinkFiles - takes a module and a list of files and links them all together.
297 /// It locates the file either in the current directory, as its absolute
298 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
301 /// progname - The name of the program (infamous argv[0]).
302 /// HeadModule - The module under which all files will be linked.
303 /// Files - A vector of C++ strings indicating the LLVM bytecode filenames
304 /// to be linked. The names can refer to a mixture of pure LLVM
305 /// bytecode files and archive (ar) formatted files.
306 /// Verbose - Flags whether verbose output should be printed while linking.
309 /// HeadModule - The module will have the specified LLVM bytecode files linked
313 /// FALSE - No errors.
314 /// TRUE - Some error occurred.
316 bool LinkFiles(const char *progname,
318 const std::vector<std::string> &Files,
321 // String in which to receive error messages.
322 std::string ErrorMessage;
324 // Full pathname of the file
325 std::string Pathname;
327 // Get the library search path from the environment
328 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
330 for (unsigned i = 0; i < Files.size(); ++i) {
331 // Determine where this file lives.
332 if (FileExists(Files[i])) {
335 if (SearchPath == NULL) {
336 std::cerr << progname << ": Cannot find linker input file '"
337 << Files[i] << "'\n";
338 std::cerr << progname
339 << ": Warning: Your LLVM_LIB_SEARCH_PATH is unset.\n";
343 Pathname = std::string(SearchPath)+"/"+Files[i];
344 if (!FileExists(Pathname)) {
345 std::cerr << progname << ": Cannot find linker input file '"
346 << Files[i] << "'\n";
351 // A user may specify an ar archive without -l, perhaps because it
352 // is not installed as a library. Detect that and link the library.
353 if (IsArchive(Pathname)) {
355 std::cerr << "Trying to link archive '" << Pathname << "'\n";
357 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
358 PrintAndReturn(progname, ErrorMessage,
359 ": Error linking in archive '" + Pathname + "'");
364 std::cerr << "Trying to link bytecode file '" << Pathname << "'\n";
366 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
367 PrintAndReturn(progname, ErrorMessage,
368 ": Error linking in bytecode file '" + Pathname + "'");
377 /// LinkLibraries - takes the specified library files and links them into the
378 /// main bytecode object file.
381 /// progname - The name of the program (infamous argv[0]).
382 /// HeadModule - The module into which all necessary libraries will be linked.
383 /// Libraries - The list of libraries to link into the module.
384 /// LibPaths - The list of library paths in which to find libraries.
385 /// Verbose - Flags whether verbose messages should be printed.
386 /// Native - Flags whether native code is being generated.
389 /// HeadModule - The module will have all necessary libraries linked in.
392 /// FALSE - No error.
395 bool LinkLibraries(const char *progname,
397 const std::vector<std::string> &Libraries,
398 const std::vector<std::string> &LibPaths,
402 // String in which to receive error messages.
403 std::string ErrorMessage;
405 for (unsigned i = 0; i < Libraries.size(); ++i) {
406 // Determine where this library lives.
407 std::string Pathname = FindLib(Libraries[i], LibPaths);
408 if (Pathname.empty()) {
409 // If the pathname does not exist, then continue to the next one if
410 // we're doing a native link and give an error if we're doing a bytecode
413 PrintAndReturn(progname, "Cannot find library -l" + Libraries[i] + "\n");
418 // A user may specify an ar archive without -l, perhaps because it
419 // is not installed as a library. Detect that and link the library.
420 if (IsArchive(Pathname)) {
422 std::cerr << "Trying to link archive '" << Pathname << "' (-l" << Libraries[i] << ")\n";
424 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
425 PrintAndReturn(progname, ErrorMessage,
426 ": Error linking in archive '" + Pathname + "' (-l" + Libraries[i] + ")");
431 std::cerr << "Trying to link bytecode file '" << Pathname << "' (-l" << Libraries[i] << ")\n";
433 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
434 PrintAndReturn(progname, ErrorMessage,
435 ": error linking in bytecode file '" + Pathname + "' (-l" + Libraries[i] + ")");