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 //===----------------------------------------------------------------------===//
11 // This file contains routines to handle linking together LLVM bytecode files,
12 // and to handle annoying things like static libraries.
14 //===----------------------------------------------------------------------===//
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/WriteBytecodePass.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Transforms/Utils/Linker.h"
25 #include "Support/CommandLine.h"
26 #include "Support/FileUtilities.h"
27 #include "Support/Signals.h"
28 #include "Support/SystemUtils.h"
34 /// FileExists - determines if the specified filename exists and is readable.
37 /// FN - The name of the file.
43 /// TRUE - The file exists and is readable.
44 /// FALSE - The file does not exist or is unreadable.
46 static inline bool FileExists(const std::string &FN) {
47 return access(FN.c_str(), R_OK | F_OK) != -1;
50 /// IsArchive - determines if the specified file is an ar archive
51 /// by checking the magic string at the beginning of the file.
54 /// filename - A C++ string containing the name of the file.
60 /// TRUE - The file is an archive.
61 /// FALSE - The file is not an archive.
63 static inline bool IsArchive(const std::string &filename) {
64 std::string ArchiveMagic("!<arch>\012");
65 char buf[1 + ArchiveMagic.size()];
66 std::ifstream f(filename.c_str());
67 f.read(buf, ArchiveMagic.size());
68 buf[ArchiveMagic.size()] = '\0';
69 return ArchiveMagic == buf;
72 /// FindLib - locates a particular library. It will prepend and append
73 /// various directories, prefixes, and suffixes until it can find the library.
76 /// Filename - Name of the file to find.
77 /// Paths - List of directories to search.
83 /// The name of the file is returned.
84 /// If the file is not found, an empty string is returned.
87 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
88 // Determine if the pathname can be found as it stands.
89 if (FileExists(Filename))
92 // If that doesn't work, convert the name into a library name.
93 std::string LibName = "lib" + Filename;
95 // Iterate over the directories in Paths to see if we can find the library
97 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
98 std::string Directory = Paths[Index] + "/";
100 if (FileExists(Directory + LibName + ".bc"))
101 return Directory + LibName + ".bc";
103 if (FileExists(Directory + LibName + ".so"))
104 return Directory + LibName + ".so";
106 if (FileExists(Directory + LibName + ".a"))
107 return Directory + LibName + ".a";
110 // One last hope: Check LLVM_LIB_SEARCH_PATH.
111 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
112 if (SearchPath == NULL)
113 return std::string();
115 LibName = std::string(SearchPath) + "/" + LibName;
116 if (FileExists(LibName))
119 return std::string();
122 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified
126 /// M - The module in which to find defined symbols.
129 /// DefinedSymbols - A set of C++ strings that will contain the name of all
135 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
136 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
137 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
138 DefinedSymbols.insert(I->getName());
139 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
140 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
141 DefinedSymbols.insert(I->getName());
144 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
145 /// exist in an LLVM module. This is a bit tricky because there may be two
146 /// symbols with the same name but different LLVM types that will be resolved to
147 /// each other but aren't currently (thus we need to treat it as resolved).
150 /// M - The module in which to find undefined symbols.
153 /// UndefinedSymbols - A set of C++ strings containing the name of all
154 /// undefined symbols.
160 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
161 std::set<std::string> DefinedSymbols;
162 UndefinedSymbols.clear(); // Start out empty
164 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
167 UndefinedSymbols.insert(I->getName());
168 else if (!I->hasInternalLinkage())
169 DefinedSymbols.insert(I->getName());
171 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
174 UndefinedSymbols.insert(I->getName());
175 else if (!I->hasInternalLinkage())
176 DefinedSymbols.insert(I->getName());
179 // Prune out any defined symbols from the undefined symbols set...
180 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
181 I != UndefinedSymbols.end(); )
182 if (DefinedSymbols.count(*I))
183 UndefinedSymbols.erase(I++); // This symbol really is defined!
185 ++I; // Keep this symbol in the undefined symbols list
189 /// LoadObject - reads the specified bytecode object file.
192 /// FN - The name of the file to load.
195 /// OutErrorMessage - The error message to give back to the caller.
198 /// A pointer to a module represening the bytecode file is returned.
199 /// If an error occurs, the pointer is 0.
201 std::auto_ptr<Module>
202 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
203 std::string ErrorMessage;
204 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
205 if (Result) return std::auto_ptr<Module>(Result);
206 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
207 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
208 return std::auto_ptr<Module>();
211 /// LinkInArchive - opens an archive library and link in all objects which
212 /// provide symbols that are currently undefined.
215 /// M - The module in which to link the archives.
216 /// Filename - The pathname of the archive.
217 /// Verbose - Flags whether verbose messages should be printed.
220 /// ErrorMessage - A C++ string detailing what error occurred, if any.
223 /// TRUE - An error occurred.
224 /// FALSE - No errors.
226 static bool LinkInArchive(Module *M,
227 const std::string &Filename,
228 std::string &ErrorMessage,
231 // Find all of the symbols currently undefined in the bytecode program.
232 // If all the symbols are defined, the program is complete, and there is
233 // no reason to link in any archive files.
234 std::set<std::string> UndefinedSymbols;
235 GetAllUndefinedSymbols(M, UndefinedSymbols);
236 if (UndefinedSymbols.empty()) {
237 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
238 return false; // No need to link anything in!
241 // Load in the archive objects.
242 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
243 std::vector<Module*> Objects;
244 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
247 // Figure out which symbols are defined by all of the modules in the archive.
248 std::vector<std::set<std::string> > DefinedSymbols;
249 DefinedSymbols.resize(Objects.size());
250 for (unsigned i = 0; i != Objects.size(); ++i) {
251 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
254 // While we are linking in object files, loop.
259 for (unsigned i = 0; i != Objects.size(); ++i) {
260 // Consider whether we need to link in this module... we only need to
261 // link it in if it defines some symbol which is so far undefined.
263 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
265 bool ObjectRequired = false;
266 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
267 E = UndefinedSymbols.end(); I != E; ++I)
268 if (DefSymbols.count(*I)) {
270 std::cerr << " Found object providing symbol '" << *I << "'...\n";
271 ObjectRequired = true;
275 // We DO need to link this object into the program...
276 if (ObjectRequired) {
277 if (LinkModules(M, Objects[i], &ErrorMessage))
278 return true; // Couldn't link in the right object file...
280 // Since we have linked in this object, delete it from the list of
281 // objects to consider in this archive file.
282 std::swap(Objects[i], Objects.back());
283 std::swap(DefinedSymbols[i], DefinedSymbols.back());
285 DefinedSymbols.pop_back();
286 --i; // Do not skip an entry
288 // The undefined symbols set should have shrunk.
289 GetAllUndefinedSymbols(M, UndefinedSymbols);
290 Linked = true; // We have linked something in!
298 /// LinkInFile - opens an archive library and link in all objects which
299 /// provide symbols that are currently undefined.
302 /// HeadModule - The module in which to link the archives.
303 /// Filename - The pathname of the archive.
304 /// Verbose - Flags whether verbose messages should be printed.
307 /// ErrorMessage - A C++ string detailing what error occurred, if any.
310 /// TRUE - An error occurred.
311 /// FALSE - No errors.
313 static bool LinkInFile(Module *HeadModule,
314 const std::string &Filename,
315 std::string &ErrorMessage,
318 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
319 if (M.get() == 0) return true;
320 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
321 return LinkModules(HeadModule, M.get(), &ErrorMessage);
324 /// LinkFiles - takes a module and a list of files and links them all together.
325 /// It locates the file either in the current directory, as its absolute
326 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
329 /// progname - The name of the program (infamous argv[0]).
330 /// HeadModule - The module under which all files will be linked.
331 /// Files - A vector of C++ strings indicating the LLVM bytecode filenames
332 /// to be linked. The names can refer to a mixture of pure LLVM
333 /// bytecode files and archive (ar) formatted files.
334 /// Verbose - Flags whether verbose output should be printed while linking.
337 /// HeadModule - The module will have the specified LLVM bytecode files linked
341 /// FALSE - No errors.
342 /// TRUE - Some error occurred.
344 bool LinkFiles(const char *progname,
346 const std::vector<std::string> &Files,
349 // String in which to receive error messages.
350 std::string ErrorMessage;
352 // Full pathname of the file
353 std::string Pathname;
355 // Get the library search path from the environment
356 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
358 for (unsigned i = 1; i < Files.size(); ++i) {
359 // Determine where this file lives.
360 if (FileExists(Files[i])) {
363 if (SearchPath == NULL) {
364 std::cerr << progname << ": Cannot find linker input file '"
365 << Files[i] << "'\n";
369 Pathname = std::string(SearchPath)+"/"+Files[i];
370 if (!FileExists(Pathname)) {
371 std::cerr << progname << ": Cannot find linker input file '"
372 << Files[i] << "'\n";
377 // A user may specify an ar archive without -l, perhaps because it
378 // is not installed as a library. Detect that and link the library.
379 if (IsArchive(Pathname)) {
381 std::cerr << "Linking archive '" << Files[i] << "'\n";
383 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
384 PrintAndReturn(progname, ErrorMessage,
385 ": Error linking in '" + Files[i] + "'");
390 std::cerr << "Linking file '" << Files[i] << "'\n";
392 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
393 PrintAndReturn(progname, ErrorMessage,
394 ": Error linking in '" + Files[i] + "'");
403 /// LinkLibraries - takes the specified library files and links them into the
404 /// main bytecode object file.
407 /// progname - The name of the program (infamous argv[0]).
408 /// HeadModule - The module into which all necessary libraries will be linked.
409 /// Libraries - The list of libraries to link into the module.
410 /// LibPaths - The list of library paths in which to find libraries.
411 /// Verbose - Flags whether verbose messages should be printed.
412 /// Native - Flags whether native code is being generated.
415 /// HeadModule - The module will have all necessary libraries linked in.
418 /// FALSE - No error.
421 bool LinkLibraries(const char *progname,
423 const std::vector<std::string> &Libraries,
424 const std::vector<std::string> &LibPaths,
428 // String in which to receive error messages.
429 std::string ErrorMessage;
431 for (unsigned i = 1; i < Libraries.size(); ++i) {
432 // Determine where this library lives.
433 std::string Pathname = FindLib(Libraries[i], LibPaths);
434 if (Pathname.empty()) {
435 // If the pathname does not exist, then continue to the next one if
436 // we're doing a native link and give an error if we're doing a bytecode
439 PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
444 // A user may specify an ar archive without -l, perhaps because it
445 // is not installed as a library. Detect that and link the library.
446 if (IsArchive(Pathname)) {
448 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
450 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
451 PrintAndReturn(progname, ErrorMessage,
452 ": Error linking in '" + Libraries[i] + "'");
457 std::cerr << "Linking file '" << Libraries[i] << "'\n";
459 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
460 PrintAndReturn(progname, ErrorMessage,
461 ": error linking in '" + Libraries[i] + "'");