1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
3 // This utility is intended to be compatible with GCC, and follows standard
4 // system 'ld' conventions. As such, the default output file is ./a.out.
5 // Additionally, this program outputs a shell script that is used to invoke LLI
6 // to execute the program. In this manner, the generated executable (a.out for
7 // example), is directly executable, whereas the bytecode file actually lives in
8 // the a.out.bc file generated by this program. Also, Force is on by default.
10 // Note that if someone (or a script) deletes the executable program generated,
11 // the .bc file will be left around. Considering that this is a temporary hack,
12 // I'm not too worried about this.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/Linker.h"
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 "Support/FileUtilities.h"
25 #include "Support/SystemUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Signals.h"
28 #include "Config/stdlib.h"
37 // Function: FileExists ()
40 // Determine if the specified filename exists and is readable.
43 // FN - The name of the file.
49 // TRUE - The file exists and is readable.
50 // FALSE - The file does not exist or is unreadable.
53 FileExists(const std::string &FN)
55 return access(FN.c_str(), R_OK | F_OK) != -1;
59 // Function: IsArchive ()
62 // Determine if the specified file is an ar archive. It determines this by
63 // checking the magic string at the beginning of the file.
66 // filename - A C++ string containing the name of the file.
72 // TRUE - The file is an archive.
73 // FALSE - The file is not an archive.
76 IsArchive (const std::string &filename)
78 std::string ArchiveMagic("!<arch>\012");
79 char buf[1 + ArchiveMagic.size()];
81 std::ifstream f(filename.c_str());
82 f.read(buf, ArchiveMagic.size());
83 buf[ArchiveMagic.size()] = '\0';
84 return ArchiveMagic == buf;
88 // Function: FindLib ()
91 // This function locates a particular library. It will prepend and append
92 // various directories, prefixes, and suffixes until it can find the library.
95 // Filename - Name of the file to find.
96 // Paths - List of directories to search.
102 // The name of the file is returned.
103 // If the file is not found, an empty string is returned.
106 FindLib (const std::string & Filename, const std::vector<std::string> & Paths)
109 // Determine if the pathname can be found as it stands.
111 if (FileExists (Filename))
117 // If that doesn't work, convert the name into a library name.
119 std::string LibName = "lib" + Filename;
122 // Iterate over the directories in Paths to see if we can find the library
125 for (unsigned Index = 0; Index != Paths.size(); ++Index)
127 std::string Directory = Paths[Index] + "/";
129 if (FileExists (Directory + LibName + ".bc"))
131 return Directory + LibName + ".bc";
134 if (FileExists (Directory + LibName + ".so"))
136 return Directory + LibName + ".so";
139 if (FileExists (Directory + LibName + ".a"))
141 return Directory + LibName + ".a";
146 // One last hope: Check LLVM_LIB_SEARCH_PATH.
148 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
149 if (SearchPath == NULL)
151 return std::string();
154 LibName = std::string(SearchPath) + "/" + LibName;
155 if (FileExists (LibName))
160 return std::string();
164 // Function: GetAllDefinedSymbols ()
167 // Find all of the defined symbols in the specified module.
170 // M - The module in which to find defined symbols.
173 // DefinedSymbols - A set of C++ strings that will contain the name of all
180 GetAllDefinedSymbols (Module *M, std::set<std::string> &DefinedSymbols)
182 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
183 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
184 DefinedSymbols.insert(I->getName());
185 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
186 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
187 DefinedSymbols.insert(I->getName());
191 // Function: GetAllUndefinedSymbols ()
194 // This calculates the set of undefined symbols that still exist in an LLVM
195 // module. This is a bit tricky because there may be two symbols with the
196 // same name but different LLVM types that will be resolved to each other but
197 // aren't currently (thus we need to treat it as resolved).
200 // M - The module in which to find undefined symbols.
203 // UndefinedSymbols - A set of C++ strings containing the name of all
204 // undefined symbols.
210 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols)
212 std::set<std::string> DefinedSymbols;
213 UndefinedSymbols.clear(); // Start out empty
215 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
218 UndefinedSymbols.insert(I->getName());
219 else if (!I->hasInternalLinkage())
220 DefinedSymbols.insert(I->getName());
222 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
225 UndefinedSymbols.insert(I->getName());
226 else if (!I->hasInternalLinkage())
227 DefinedSymbols.insert(I->getName());
230 // Prune out any defined symbols from the undefined symbols set...
231 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
232 I != UndefinedSymbols.end(); )
233 if (DefinedSymbols.count(*I))
234 UndefinedSymbols.erase(I++); // This symbol really is defined!
236 ++I; // Keep this symbol in the undefined symbols list
241 // Function: LoadObject ()
244 // Read the specified bytecode object file.
247 // FN - The name of the file to load.
250 // OutErrorMessage - The error message to give back to the caller.
253 // A pointer to a module represening the bytecode file is returned.
254 // If an error occurs, the pointer is 0.
256 std::auto_ptr<Module>
257 LoadObject (const std::string & FN, std::string &OutErrorMessage)
259 std::string ErrorMessage;
260 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
261 if (Result) return std::auto_ptr<Module>(Result);
263 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
264 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
265 return std::auto_ptr<Module>();
269 // Function: LinkInArchive ()
272 // This function will open an archive library and link in all objects which
273 // provide symbols that are currently undefined.
276 // M - The module in which to link the archives.
277 // Filename - The pathname of the archive.
278 // Verbose - Flags whether verbose messages should be printed.
281 // ErrorMessage - A C++ string detailing what error occurred, if any.
284 // TRUE - An error occurred.
285 // FALSE - No errors.
288 LinkInArchive (Module * M,
289 const std::string & Filename,
290 std::string & ErrorMessage,
294 // Find all of the symbols currently undefined in the bytecode program.
295 // If all the symbols are defined, the program is complete, and there is
296 // no reason to link in any archive files.
298 std::set<std::string> UndefinedSymbols;
299 GetAllUndefinedSymbols (M, UndefinedSymbols);
300 if (UndefinedSymbols.empty())
302 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
303 return false; // No need to link anything in!
307 // Load in the archive objects.
309 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
310 std::vector<Module*> Objects;
311 if (ReadArchiveFile (Filename, Objects, &ErrorMessage))
317 // Figure out which symbols are defined by all of the modules in the archive.
319 std::vector<std::set<std::string> > DefinedSymbols;
320 DefinedSymbols.resize (Objects.size());
321 for (unsigned i = 0; i != Objects.size(); ++i)
323 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
326 // While we are linking in object files, loop.
332 for (unsigned i = 0; i != Objects.size(); ++i) {
333 // Consider whether we need to link in this module... we only need to
334 // link it in if it defines some symbol which is so far undefined.
336 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
338 bool ObjectRequired = false;
339 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
340 E = UndefinedSymbols.end(); I != E; ++I)
341 if (DefSymbols.count(*I)) {
343 std::cerr << " Found object providing symbol '" << *I << "'...\n";
344 ObjectRequired = true;
348 // We DO need to link this object into the program...
349 if (ObjectRequired) {
350 if (LinkModules(M, Objects[i], &ErrorMessage))
351 return true; // Couldn't link in the right object file...
353 // Since we have linked in this object, delete it from the list of
354 // objects to consider in this archive file.
355 std::swap(Objects[i], Objects.back());
356 std::swap(DefinedSymbols[i], DefinedSymbols.back());
358 DefinedSymbols.pop_back();
359 --i; // Do not skip an entry
361 // The undefined symbols set should have shrunk.
362 GetAllUndefinedSymbols(M, UndefinedSymbols);
363 Linked = true; // We have linked something in!
372 // Function: LinkInFile ()
375 // This function will open an archive library and link in all objects which
376 // provide symbols that are currently undefined.
379 // HeadModule - The module in which to link the archives.
380 // Filename - The pathname of the archive.
381 // Verbose - Flags whether verbose messages should be printed.
384 // ErrorMessage - A C++ string detailing what error occurred, if any.
387 // TRUE - An error occurred.
388 // FALSE - No errors.
391 LinkInFile (Module * HeadModule,
392 const std::string & Filename,
393 std::string & ErrorMessage,
396 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
402 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
404 return (LinkModules (HeadModule, M.get(), &ErrorMessage));
408 // Function: LinkFiles ()
411 // This function takes a module and a list of files and links them all
412 // together. It locates the file either in the current directory, as it's
413 // absolute or relative pathname, or as a file somewhere in
414 // LLVM_LIB_SEARCH_PATH.
417 // progname - The name of the program (infamous argv[0]).
418 // HeadModule - The module under which all files will be linked.
419 // Files - A vector of C++ strings indicating the LLVM bytecode filenames
420 // to be linked. The names can refer to a mixture of pure LLVM
421 // bytecode files and archive (ar) formatted files.
422 // Verbose - Flags whether verbose output should be printed while linking.
425 // HeadModule - The module will have the specified LLVM bytecode files linked
429 // FALSE - No errors.
430 // TRUE - Some error occurred.
433 LinkFiles (const char * progname,
435 const std::vector<std::string> & Files,
438 // String in which to receive error messages.
439 std::string ErrorMessage;
441 // Full pathname of the file
442 std::string Pathname;
444 // Get the library search path from the environment
445 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
447 for (unsigned i = 1; i < Files.size(); ++i)
450 // Determine where this file lives.
452 if (FileExists (Files[i]))
458 if (SearchPath == NULL)
460 std::cerr << "Cannot find " << Files[i];
464 Pathname = std::string(SearchPath)+"/"+Files[i];
465 if (!FileExists (Pathname))
467 std::cerr << "Cannot find " << Files[i];
473 // A user may specify an ar archive without -l, perhaps because it
474 // is not installed as a library. Detect that and link the library.
476 if (IsArchive(Pathname))
480 std::cerr << "Linking archive '" << Files[i] << "'\n";
483 if (LinkInArchive (HeadModule, Pathname, ErrorMessage, Verbose))
485 PrintAndReturn(progname, ErrorMessage,
486 ": Error linking in '" + Files[i] + "'");
494 std::cerr << "Linking file '" << Files[i] << "'\n";
497 if (LinkInFile (HeadModule, Pathname, ErrorMessage, Verbose))
499 PrintAndReturn(progname, ErrorMessage,
500 ": error linking in '" + Files[i] + "'");
510 // Function: LinkLibraries ()
513 // This function takes the specified library files and links them into the
514 // main bytecode object file.
517 // progname - The name of the program (infamous argv[0]).
518 // HeadModule - The module into which all necessary libraries will be linked.
519 // Libraries - The list of libraries to link into the module.
520 // LibPaths - The list of library paths in which to find libraries.
521 // Verbose - Flags whether verbose messages should be printed.
522 // Native - Flags whether native code is being generated.
525 // HeadModule - The module will have all necessary libraries linked in.
532 LinkLibraries (const char * progname,
534 const std::vector<std::string> & Libraries,
535 const std::vector<std::string> & LibPaths,
539 // String in which to receive error messages.
540 std::string ErrorMessage;
542 for (unsigned i = 1; i < Libraries.size(); ++i)
545 // Determine where this library lives.
547 std::string Pathname = FindLib (Libraries[i], LibPaths);
548 if (Pathname.empty())
551 // If the pathname does not exist, then continue to the next one if
552 // we're doing a native link and give an error if we're doing a bytecode
561 PrintAndReturn (progname, "Cannot find " + Libraries[i]);
567 // A user may specify an ar archive without -l, perhaps because it
568 // is not installed as a library. Detect that and link the library.
570 if (IsArchive(Pathname))
574 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
577 if (LinkInArchive (HeadModule, Pathname, ErrorMessage, Verbose))
579 PrintAndReturn(progname, ErrorMessage,
580 ": Error linking in '" + Libraries[i] + "'");
588 std::cerr << "Linking file '" << Libraries[i] << "'\n";
591 if (LinkInFile (HeadModule, Pathname, ErrorMessage, Verbose))
593 PrintAndReturn(progname, ErrorMessage,
594 ": error linking in '" + Libraries[i] + "'");