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"
26 /// FileExists - determines if the specified filename exists and is readable.
29 /// FN - The name of the file.
35 /// TRUE - The file exists and is readable.
36 /// FALSE - The file does not exist or is unreadable.
38 static inline bool FileExists(const std::string &FN) {
39 return access(FN.c_str(), R_OK | F_OK) != -1;
42 /// IsArchive - determines if the specified file is an ar archive
43 /// by checking the magic string at the beginning of the file.
46 /// filename - A C++ string containing the name of the file.
52 /// TRUE - The file is an archive.
53 /// FALSE - The file is not an archive.
55 static inline bool IsArchive(const std::string &filename) {
56 std::string ArchiveMagic("!<arch>\012");
57 char buf[1 + ArchiveMagic.size()];
58 std::ifstream f(filename.c_str());
59 f.read(buf, ArchiveMagic.size());
60 buf[ArchiveMagic.size()] = '\0';
61 return ArchiveMagic == buf;
64 /// FindLib - locates a particular library. It will prepend and append
65 /// various directories, prefixes, and suffixes until it can find the library.
68 /// Filename - Name of the file to find.
69 /// Paths - List of directories to search.
75 /// The name of the file is returned.
76 /// If the file is not found, an empty string is returned.
79 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
80 // Determine if the pathname can be found as it stands.
81 if (FileExists(Filename))
84 // If that doesn't work, convert the name into a library name.
85 std::string LibName = "lib" + Filename;
87 // Iterate over the directories in Paths to see if we can find the library
89 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
90 std::string Directory = Paths[Index] + "/";
92 if (FileExists(Directory + LibName + ".bc"))
93 return Directory + LibName + ".bc";
95 if (FileExists(Directory + LibName + ".so"))
96 return Directory + LibName + ".so";
98 if (FileExists(Directory + LibName + ".a"))
99 return Directory + LibName + ".a";
102 // One last hope: Check LLVM_LIB_SEARCH_PATH.
103 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
104 if (SearchPath == NULL)
105 return std::string();
107 LibName = std::string(SearchPath) + "/" + LibName;
108 if (FileExists(LibName))
111 return std::string();
114 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified
118 /// M - The module in which to find defined symbols.
121 /// DefinedSymbols - A set of C++ strings that will contain the name of all
127 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
128 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
129 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
130 DefinedSymbols.insert(I->getName());
131 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
132 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
133 DefinedSymbols.insert(I->getName());
136 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
137 /// exist in an LLVM module. This is a bit tricky because there may be two
138 /// symbols with the same name but different LLVM types that will be resolved to
139 /// each other but aren't currently (thus we need to treat it as resolved).
142 /// M - The module in which to find undefined symbols.
145 /// UndefinedSymbols - A set of C++ strings containing the name of all
146 /// undefined symbols.
152 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
153 std::set<std::string> DefinedSymbols;
154 UndefinedSymbols.clear(); // Start out empty
156 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
159 UndefinedSymbols.insert(I->getName());
160 else if (!I->hasInternalLinkage())
161 DefinedSymbols.insert(I->getName());
163 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
166 UndefinedSymbols.insert(I->getName());
167 else if (!I->hasInternalLinkage())
168 DefinedSymbols.insert(I->getName());
171 // Prune out any defined symbols from the undefined symbols set...
172 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
173 I != UndefinedSymbols.end(); )
174 if (DefinedSymbols.count(*I))
175 UndefinedSymbols.erase(I++); // This symbol really is defined!
177 ++I; // Keep this symbol in the undefined symbols list
181 /// LoadObject - reads the specified bytecode object file.
184 /// FN - The name of the file to load.
187 /// OutErrorMessage - The error message to give back to the caller.
190 /// A pointer to a module represening the bytecode file is returned.
191 /// If an error occurs, the pointer is 0.
193 std::auto_ptr<Module>
194 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
195 std::string ErrorMessage;
196 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
197 if (Result) return std::auto_ptr<Module>(Result);
198 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
199 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
200 return std::auto_ptr<Module>();
203 /// LinkInArchive - opens an archive library and link in all objects which
204 /// provide symbols that are currently undefined.
207 /// M - The module in which to link the archives.
208 /// Filename - The pathname of the archive.
209 /// Verbose - Flags whether verbose messages should be printed.
212 /// ErrorMessage - A C++ string detailing what error occurred, if any.
215 /// TRUE - An error occurred.
216 /// FALSE - No errors.
218 static bool LinkInArchive(Module *M,
219 const std::string &Filename,
220 std::string &ErrorMessage,
223 // Find all of the symbols currently undefined in the bytecode program.
224 // If all the symbols are defined, the program is complete, and there is
225 // no reason to link in any archive files.
226 std::set<std::string> UndefinedSymbols;
227 GetAllUndefinedSymbols(M, UndefinedSymbols);
228 if (UndefinedSymbols.empty()) {
229 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
230 return false; // No need to link anything in!
233 // Load in the archive objects.
234 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
235 std::vector<Module*> Objects;
236 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
239 // Figure out which symbols are defined by all of the modules in the archive.
240 std::vector<std::set<std::string> > DefinedSymbols;
241 DefinedSymbols.resize(Objects.size());
242 for (unsigned i = 0; i != Objects.size(); ++i) {
243 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
246 // While we are linking in object files, loop.
251 for (unsigned i = 0; i != Objects.size(); ++i) {
252 // Consider whether we need to link in this module... we only need to
253 // link it in if it defines some symbol which is so far undefined.
255 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
257 bool ObjectRequired = false;
258 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
259 E = UndefinedSymbols.end(); I != E; ++I)
260 if (DefSymbols.count(*I)) {
262 std::cerr << " Found object providing symbol '" << *I << "'...\n";
263 ObjectRequired = true;
267 // We DO need to link this object into the program...
268 if (ObjectRequired) {
269 if (LinkModules(M, Objects[i], &ErrorMessage))
270 return true; // Couldn't link in the right object file...
272 // Since we have linked in this object, delete it from the list of
273 // objects to consider in this archive file.
274 std::swap(Objects[i], Objects.back());
275 std::swap(DefinedSymbols[i], DefinedSymbols.back());
277 DefinedSymbols.pop_back();
278 --i; // Do not skip an entry
280 // The undefined symbols set should have shrunk.
281 GetAllUndefinedSymbols(M, UndefinedSymbols);
282 Linked = true; // We have linked something in!
290 /// LinkInFile - opens an archive library and link in all objects which
291 /// provide symbols that are currently undefined.
294 /// HeadModule - The module in which to link the archives.
295 /// Filename - The pathname of the archive.
296 /// Verbose - Flags whether verbose messages should be printed.
299 /// ErrorMessage - A C++ string detailing what error occurred, if any.
302 /// TRUE - An error occurred.
303 /// FALSE - No errors.
305 static bool LinkInFile(Module *HeadModule,
306 const std::string &Filename,
307 std::string &ErrorMessage,
310 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
311 if (M.get() == 0) return true;
312 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
313 return LinkModules(HeadModule, M.get(), &ErrorMessage);
316 /// LinkFiles - takes a module and a list of files and links them all together.
317 /// It locates the file either in the current directory, as its absolute
318 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
321 /// progname - The name of the program (infamous argv[0]).
322 /// HeadModule - The module under which all files will be linked.
323 /// Files - A vector of C++ strings indicating the LLVM bytecode filenames
324 /// to be linked. The names can refer to a mixture of pure LLVM
325 /// bytecode files and archive (ar) formatted files.
326 /// Verbose - Flags whether verbose output should be printed while linking.
329 /// HeadModule - The module will have the specified LLVM bytecode files linked
333 /// FALSE - No errors.
334 /// TRUE - Some error occurred.
336 bool LinkFiles(const char *progname,
338 const std::vector<std::string> &Files,
341 // String in which to receive error messages.
342 std::string ErrorMessage;
344 // Full pathname of the file
345 std::string Pathname;
347 // Get the library search path from the environment
348 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
350 for (unsigned i = 1; i < Files.size(); ++i) {
351 // Determine where this file lives.
352 if (FileExists(Files[i])) {
355 if (SearchPath == NULL) {
356 std::cerr << progname << ": Cannot find linker input file '"
357 << Files[i] << "'\n";
361 Pathname = std::string(SearchPath)+"/"+Files[i];
362 if (!FileExists(Pathname)) {
363 std::cerr << progname << ": Cannot find linker input file '"
364 << Files[i] << "'\n";
369 // A user may specify an ar archive without -l, perhaps because it
370 // is not installed as a library. Detect that and link the library.
371 if (IsArchive(Pathname)) {
373 std::cerr << "Linking archive '" << Files[i] << "'\n";
375 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
376 PrintAndReturn(progname, ErrorMessage,
377 ": Error linking in '" + Files[i] + "'");
382 std::cerr << "Linking file '" << Files[i] << "'\n";
384 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
385 PrintAndReturn(progname, ErrorMessage,
386 ": Error linking in '" + Files[i] + "'");
395 /// LinkLibraries - takes the specified library files and links them into the
396 /// main bytecode object file.
399 /// progname - The name of the program (infamous argv[0]).
400 /// HeadModule - The module into which all necessary libraries will be linked.
401 /// Libraries - The list of libraries to link into the module.
402 /// LibPaths - The list of library paths in which to find libraries.
403 /// Verbose - Flags whether verbose messages should be printed.
404 /// Native - Flags whether native code is being generated.
407 /// HeadModule - The module will have all necessary libraries linked in.
410 /// FALSE - No error.
413 bool LinkLibraries(const char *progname,
415 const std::vector<std::string> &Libraries,
416 const std::vector<std::string> &LibPaths,
420 // String in which to receive error messages.
421 std::string ErrorMessage;
423 for (unsigned i = 1; i < Libraries.size(); ++i) {
424 // Determine where this library lives.
425 std::string Pathname = FindLib(Libraries[i], LibPaths);
426 if (Pathname.empty()) {
427 // If the pathname does not exist, then continue to the next one if
428 // we're doing a native link and give an error if we're doing a bytecode
431 PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
436 // A user may specify an ar archive without -l, perhaps because it
437 // is not installed as a library. Detect that and link the library.
438 if (IsArchive(Pathname)) {
440 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
442 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
443 PrintAndReturn(progname, ErrorMessage,
444 ": Error linking in '" + Libraries[i] + "'");
449 std::cerr << "Linking file '" << Libraries[i] << "'\n";
451 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
452 PrintAndReturn(progname, ErrorMessage,
453 ": error linking in '" + Libraries[i] + "'");