1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
3 // This file contains routines to handle linking together LLVM bytecode files,
4 // and to handle annoying things like static libraries.
6 //===----------------------------------------------------------------------===//
9 #include "llvm/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Bytecode/Reader.h"
12 #include "llvm/Bytecode/WriteBytecodePass.h"
13 #include "llvm/Target/TargetData.h"
14 #include "llvm/Transforms/IPO.h"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Transforms/Utils/Linker.h"
17 #include "Support/CommandLine.h"
18 #include "Support/FileUtilities.h"
19 #include "Support/Signals.h"
20 #include "Support/SystemUtils.h"
21 #include "Config/stdlib.h"
27 /// FileExists - determines if the specified filename exists and is readable.
30 /// FN - The name of the file.
36 /// TRUE - The file exists and is readable.
37 /// FALSE - The file does not exist or is unreadable.
39 static inline bool FileExists(const std::string &FN) {
40 return access(FN.c_str(), R_OK | F_OK) != -1;
43 /// IsArchive - determines if the specified file is an ar archive
44 /// by checking the magic string at the beginning of the file.
47 /// filename - A C++ string containing the name of the file.
53 /// TRUE - The file is an archive.
54 /// FALSE - The file is not an archive.
56 static inline bool IsArchive(const std::string &filename) {
57 std::string ArchiveMagic("!<arch>\012");
58 char buf[1 + ArchiveMagic.size()];
59 std::ifstream f(filename.c_str());
60 f.read(buf, ArchiveMagic.size());
61 buf[ArchiveMagic.size()] = '\0';
62 return ArchiveMagic == buf;
65 /// FindLib - locates a particular library. It will prepend and append
66 /// various directories, prefixes, and suffixes until it can find the library.
69 /// Filename - Name of the file to find.
70 /// Paths - List of directories to search.
76 /// The name of the file is returned.
77 /// If the file is not found, an empty string is returned.
80 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
81 // Determine if the pathname can be found as it stands.
82 if (FileExists(Filename))
85 // If that doesn't work, convert the name into a library name.
86 std::string LibName = "lib" + Filename;
88 // Iterate over the directories in Paths to see if we can find the library
90 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
91 std::string Directory = Paths[Index] + "/";
93 if (FileExists(Directory + LibName + ".bc"))
94 return Directory + LibName + ".bc";
96 if (FileExists(Directory + LibName + ".so"))
97 return Directory + LibName + ".so";
99 if (FileExists(Directory + LibName + ".a"))
100 return Directory + LibName + ".a";
103 // One last hope: Check LLVM_LIB_SEARCH_PATH.
104 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
105 if (SearchPath == NULL)
106 return std::string();
108 LibName = std::string(SearchPath) + "/" + LibName;
109 if (FileExists(LibName))
112 return std::string();
115 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified
119 /// M - The module in which to find defined symbols.
122 /// DefinedSymbols - A set of C++ strings that will contain the name of all
128 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
129 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
130 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
131 DefinedSymbols.insert(I->getName());
132 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
133 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
134 DefinedSymbols.insert(I->getName());
137 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
138 /// exist in an LLVM module. This is a bit tricky because there may be two
139 /// symbols with the same name but different LLVM types that will be resolved to
140 /// each other but aren't currently (thus we need to treat it as resolved).
143 /// M - The module in which to find undefined symbols.
146 /// UndefinedSymbols - A set of C++ strings containing the name of all
147 /// undefined symbols.
153 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
154 std::set<std::string> DefinedSymbols;
155 UndefinedSymbols.clear(); // Start out empty
157 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
160 UndefinedSymbols.insert(I->getName());
161 else if (!I->hasInternalLinkage())
162 DefinedSymbols.insert(I->getName());
164 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
167 UndefinedSymbols.insert(I->getName());
168 else if (!I->hasInternalLinkage())
169 DefinedSymbols.insert(I->getName());
172 // Prune out any defined symbols from the undefined symbols set...
173 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
174 I != UndefinedSymbols.end(); )
175 if (DefinedSymbols.count(*I))
176 UndefinedSymbols.erase(I++); // This symbol really is defined!
178 ++I; // Keep this symbol in the undefined symbols list
182 /// LoadObject - reads the specified bytecode object file.
185 /// FN - The name of the file to load.
188 /// OutErrorMessage - The error message to give back to the caller.
191 /// A pointer to a module represening the bytecode file is returned.
192 /// If an error occurs, the pointer is 0.
194 std::auto_ptr<Module>
195 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
196 std::string ErrorMessage;
197 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
198 if (Result) return std::auto_ptr<Module>(Result);
199 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
200 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
201 return std::auto_ptr<Module>();
204 /// LinkInArchive - opens an archive library and link in all objects which
205 /// provide symbols that are currently undefined.
208 /// M - The module in which to link the archives.
209 /// Filename - The pathname of the archive.
210 /// Verbose - Flags whether verbose messages should be printed.
213 /// ErrorMessage - A C++ string detailing what error occurred, if any.
216 /// TRUE - An error occurred.
217 /// FALSE - No errors.
219 static bool LinkInArchive(Module *M,
220 const std::string &Filename,
221 std::string &ErrorMessage,
224 // Find all of the symbols currently undefined in the bytecode program.
225 // If all the symbols are defined, the program is complete, and there is
226 // no reason to link in any archive files.
227 std::set<std::string> UndefinedSymbols;
228 GetAllUndefinedSymbols(M, UndefinedSymbols);
229 if (UndefinedSymbols.empty()) {
230 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
231 return false; // No need to link anything in!
234 // Load in the archive objects.
235 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
236 std::vector<Module*> Objects;
237 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
240 // Figure out which symbols are defined by all of the modules in the archive.
241 std::vector<std::set<std::string> > DefinedSymbols;
242 DefinedSymbols.resize(Objects.size());
243 for (unsigned i = 0; i != Objects.size(); ++i) {
244 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
247 // While we are linking in object files, loop.
252 for (unsigned i = 0; i != Objects.size(); ++i) {
253 // Consider whether we need to link in this module... we only need to
254 // link it in if it defines some symbol which is so far undefined.
256 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
258 bool ObjectRequired = false;
259 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
260 E = UndefinedSymbols.end(); I != E; ++I)
261 if (DefSymbols.count(*I)) {
263 std::cerr << " Found object providing symbol '" << *I << "'...\n";
264 ObjectRequired = true;
268 // We DO need to link this object into the program...
269 if (ObjectRequired) {
270 if (LinkModules(M, Objects[i], &ErrorMessage))
271 return true; // Couldn't link in the right object file...
273 // Since we have linked in this object, delete it from the list of
274 // objects to consider in this archive file.
275 std::swap(Objects[i], Objects.back());
276 std::swap(DefinedSymbols[i], DefinedSymbols.back());
278 DefinedSymbols.pop_back();
279 --i; // Do not skip an entry
281 // The undefined symbols set should have shrunk.
282 GetAllUndefinedSymbols(M, UndefinedSymbols);
283 Linked = true; // We have linked something in!
291 /// LinkInFile - opens an archive library and link in all objects which
292 /// provide symbols that are currently undefined.
295 /// HeadModule - The module in which to link the archives.
296 /// Filename - The pathname of the archive.
297 /// Verbose - Flags whether verbose messages should be printed.
300 /// ErrorMessage - A C++ string detailing what error occurred, if any.
303 /// TRUE - An error occurred.
304 /// FALSE - No errors.
306 static bool LinkInFile(Module *HeadModule,
307 const std::string &Filename,
308 std::string &ErrorMessage,
311 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
312 if (M.get() == 0) return true;
313 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
314 return LinkModules(HeadModule, M.get(), &ErrorMessage);
317 /// LinkFiles - takes a module and a list of files and links them all together.
318 /// It locates the file either in the current directory, as its absolute
319 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
322 /// progname - The name of the program (infamous argv[0]).
323 /// HeadModule - The module under which all files will be linked.
324 /// Files - A vector of C++ strings indicating the LLVM bytecode filenames
325 /// to be linked. The names can refer to a mixture of pure LLVM
326 /// bytecode files and archive (ar) formatted files.
327 /// Verbose - Flags whether verbose output should be printed while linking.
330 /// HeadModule - The module will have the specified LLVM bytecode files linked
334 /// FALSE - No errors.
335 /// TRUE - Some error occurred.
337 bool LinkFiles(const char *progname,
339 const std::vector<std::string> &Files,
342 // String in which to receive error messages.
343 std::string ErrorMessage;
345 // Full pathname of the file
346 std::string Pathname;
348 // Get the library search path from the environment
349 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
351 for (unsigned i = 1; i < Files.size(); ++i) {
352 // Determine where this file lives.
353 if (FileExists(Files[i])) {
356 if (SearchPath == NULL) {
357 std::cerr << "Cannot find linker input file '" << Files[i] << "'";
361 Pathname = std::string(SearchPath)+"/"+Files[i];
362 if (!FileExists(Pathname)) {
363 std::cerr << "Cannot find linker input file '" << Files[i] << "'";
368 // A user may specify an ar archive without -l, perhaps because it
369 // is not installed as a library. Detect that and link the library.
370 if (IsArchive(Pathname)) {
372 std::cerr << "Linking archive '" << Files[i] << "'\n";
374 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
375 PrintAndReturn(progname, ErrorMessage,
376 ": Error linking in '" + Files[i] + "'");
381 std::cerr << "Linking file '" << Files[i] << "'\n";
383 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
384 PrintAndReturn(progname, ErrorMessage,
385 ": error linking in '" + Files[i] + "'");
394 /// LinkLibraries - takes the specified library files and links them into the
395 /// main bytecode object file.
398 /// progname - The name of the program (infamous argv[0]).
399 /// HeadModule - The module into which all necessary libraries will be linked.
400 /// Libraries - The list of libraries to link into the module.
401 /// LibPaths - The list of library paths in which to find libraries.
402 /// Verbose - Flags whether verbose messages should be printed.
403 /// Native - Flags whether native code is being generated.
406 /// HeadModule - The module will have all necessary libraries linked in.
409 /// FALSE - No error.
412 bool LinkLibraries(const char *progname,
414 const std::vector<std::string> &Libraries,
415 const std::vector<std::string> &LibPaths,
419 // String in which to receive error messages.
420 std::string ErrorMessage;
422 for (unsigned i = 1; i < Libraries.size(); ++i) {
423 // Determine where this library lives.
424 std::string Pathname = FindLib(Libraries[i], LibPaths);
425 if (Pathname.empty()) {
426 // If the pathname does not exist, then continue to the next one if
427 // we're doing a native link and give an error if we're doing a bytecode
430 PrintAndReturn(progname, "Cannot find " + Libraries[i]);
435 // A user may specify an ar archive without -l, perhaps because it
436 // is not installed as a library. Detect that and link the library.
437 if (IsArchive(Pathname)) {
439 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
441 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
442 PrintAndReturn(progname, ErrorMessage,
443 ": Error linking in '" + Libraries[i] + "'");
448 std::cerr << "Linking file '" << Libraries[i] << "'\n";
450 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
451 PrintAndReturn(progname, ErrorMessage,
452 ": error linking in '" + Libraries[i] + "'");