Doxygen-ified comments.
[oota-llvm.git] / lib / Linker / LinkArchives.cpp
1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
2 //
3 // This file contains routines to handle linking together LLVM bytecode files,
4 // and to handle annoying things like static libraries.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "gccld.h"
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"
22 #include <algorithm>
23 #include <fstream>
24 #include <memory>
25 #include <set>
26
27 /// FileExists - determines if the specified filename exists and is readable.
28 ///
29 /// Inputs:
30 ///  FN - The name of the file.
31 ///
32 /// Outputs:
33 ///  None.
34 ///
35 /// Return Value:
36 ///  TRUE - The file exists and is readable.
37 ///  FALSE - The file does not exist or is unreadable.
38 ///
39 static inline bool FileExists(const std::string &FN) {
40   return access(FN.c_str(), R_OK | F_OK) != -1;
41 }
42
43 /// IsArchive - determines if the specified file is an ar archive
44 /// by checking the magic string at the beginning of the file.
45 ///
46 /// Inputs:
47 ///  filename - A C++ string containing the name of the file.
48 ///
49 /// Outputs:
50 ///  None.
51 ///
52 /// Return value:
53 ///  TRUE  - The file is an archive.
54 ///  FALSE - The file is not an archive.
55 ///
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;
63 }
64
65 /// FindLib - locates a particular library.  It will prepend and append
66 /// various directories, prefixes, and suffixes until it can find the library.
67 ///
68 /// Inputs:
69 ///  Filename  - Name of the file to find.
70 ///  Paths     - List of directories to search.
71 ///
72 /// Outputs:
73 ///  None.
74 ///
75 /// Return value:
76 ///  The name of the file is returned.
77 ///  If the file is not found, an empty string is returned.
78 ///
79 static std::string
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))
83     return Filename;
84
85   // If that doesn't work, convert the name into a library name.
86   std::string LibName = "lib" + Filename;
87
88   // Iterate over the directories in Paths to see if we can find the library
89   // there.
90   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
91     std::string Directory = Paths[Index] + "/";
92
93     if (FileExists(Directory + LibName + ".bc"))
94       return Directory + LibName + ".bc";
95
96     if (FileExists(Directory + LibName + ".so"))
97       return Directory + LibName + ".so";
98
99     if (FileExists(Directory + LibName + ".a"))
100       return Directory + LibName + ".a";
101   }
102
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();
107
108   LibName = std::string(SearchPath) + "/" + LibName;
109   if (FileExists(LibName))
110     return LibName;
111
112   return std::string();
113 }
114
115 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified 
116 /// module.
117 ///
118 /// Inputs:
119 ///  M - The module in which to find defined symbols.
120 ///
121 /// Outputs:
122 ///  DefinedSymbols - A set of C++ strings that will contain the name of all
123 ///                   defined symbols.
124 ///
125 /// Return value:
126 ///  None.
127 ///
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());
135 }
136
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).
141 ///
142 /// Inputs:
143 ///  M - The module in which to find undefined symbols.
144 ///
145 /// Outputs:
146 ///  UndefinedSymbols - A set of C++ strings containing the name of all
147 ///                     undefined symbols.
148 ///
149 /// Return value:
150 ///  None.
151 ///
152 void
153 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
154   std::set<std::string> DefinedSymbols;
155   UndefinedSymbols.clear();   // Start out empty
156   
157   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
158     if (I->hasName()) {
159       if (I->isExternal())
160         UndefinedSymbols.insert(I->getName());
161       else if (!I->hasInternalLinkage())
162         DefinedSymbols.insert(I->getName());
163     }
164   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
165     if (I->hasName()) {
166       if (I->isExternal())
167         UndefinedSymbols.insert(I->getName());
168       else if (!I->hasInternalLinkage())
169         DefinedSymbols.insert(I->getName());
170     }
171   
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!
177     else
178       ++I; // Keep this symbol in the undefined symbols list
179 }
180
181
182 /// LoadObject - reads the specified bytecode object file.
183 ///
184 /// Inputs:
185 ///  FN - The name of the file to load.
186 ///
187 /// Outputs:
188 ///  OutErrorMessage - The error message to give back to the caller.
189 ///
190 /// Return Value:
191 ///  A pointer to a module represening the bytecode file is returned.
192 ///  If an error occurs, the pointer is 0.
193 ///
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>();
202 }
203
204 /// LinkInArchive - opens an archive library and link in all objects which
205 /// provide symbols that are currently undefined.
206 ///
207 /// Inputs:
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.
211 ///
212 /// Outputs:
213 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
214 ///
215 /// Return Value:
216 ///  TRUE  - An error occurred.
217 ///  FALSE - No errors.
218 ///
219 static bool LinkInArchive(Module *M,
220                           const std::string &Filename,
221                           std::string &ErrorMessage,
222                           bool Verbose)
223 {
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!
232   }
233
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))
238     return true;
239
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]);
245   }
246
247   // While we are linking in object files, loop.
248   bool Linked = true;
249   while (Linked) {     
250     Linked = false;
251
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.
255       //
256       const std::set<std::string> &DefSymbols = DefinedSymbols[i];
257
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)) {
262           if (Verbose)
263             std::cerr << "  Found object providing symbol '" << *I << "'...\n";
264           ObjectRequired = true;
265           break;
266         }
267       
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...        
272         
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());
277         Objects.pop_back();
278         DefinedSymbols.pop_back();
279         --i;   // Do not skip an entry
280         
281         // The undefined symbols set should have shrunk.
282         GetAllUndefinedSymbols(M, UndefinedSymbols);
283         Linked = true;  // We have linked something in!
284       }
285     }
286   }
287   
288   return false;
289 }
290
291 /// LinkInFile - opens an archive library and link in all objects which
292 /// provide symbols that are currently undefined.
293 ///
294 /// Inputs:
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.
298 ///
299 /// Outputs:
300 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
301 ///
302 /// Return Value:
303 ///  TRUE  - An error occurred.
304 ///  FALSE - No errors.
305 ///
306 static bool LinkInFile(Module *HeadModule,
307                        const std::string &Filename,
308                        std::string &ErrorMessage,
309                        bool Verbose)
310 {
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);
315 }
316
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.
320 ///
321 /// Inputs:
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.
328 ///
329 /// Outputs:
330 ///  HeadModule - The module will have the specified LLVM bytecode files linked
331 ///               in.
332 ///
333 /// Return value:
334 ///  FALSE - No errors.
335 ///  TRUE  - Some error occurred.
336 ///
337 bool LinkFiles(const char *progname,
338                Module *HeadModule,
339                const std::vector<std::string> &Files,
340                bool Verbose)
341 {
342   // String in which to receive error messages.
343   std::string ErrorMessage;
344
345   // Full pathname of the file
346   std::string Pathname;
347
348   // Get the library search path from the environment
349   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
350
351   for (unsigned i = 1; i < Files.size(); ++i) {
352     // Determine where this file lives.
353     if (FileExists(Files[i])) {
354       Pathname = Files[i];
355     } else {
356       if (SearchPath == NULL) {
357         std::cerr << "Cannot find linker input file '" << Files[i] << "'";
358         return true;
359       }
360
361       Pathname = std::string(SearchPath)+"/"+Files[i];
362       if (!FileExists(Pathname)) {
363         std::cerr << "Cannot find linker input file '" << Files[i] << "'";
364         return true;
365       }
366     }
367
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)) {
371       if (Verbose)
372         std::cerr << "Linking archive '" << Files[i] << "'\n";
373
374       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
375         PrintAndReturn(progname, ErrorMessage,
376                        ": Error linking in '" + Files[i] + "'");
377         return true;
378       }
379     } else {
380       if (Verbose)
381         std::cerr << "Linking file '" << Files[i] << "'\n";
382
383       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
384         PrintAndReturn(progname, ErrorMessage,
385                        ": error linking in '" + Files[i] + "'");
386         return true;
387       }
388     }
389   }
390
391   return false;
392 }
393
394 /// LinkLibraries - takes the specified library files and links them into the
395 /// main bytecode object file.
396 ///
397 /// Inputs:
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.
404 ///
405 /// Outputs:
406 ///  HeadModule - The module will have all necessary libraries linked in.
407 ///
408 /// Return value:
409 ///  FALSE - No error.
410 ///  TRUE  - Error.
411 ///
412 bool LinkLibraries(const char *progname,
413                    Module *HeadModule,
414                    const std::vector<std::string> &Libraries,
415                    const std::vector<std::string> &LibPaths,
416                    bool Verbose,
417                    bool Native)
418 {
419   // String in which to receive error messages.
420   std::string ErrorMessage;
421
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
428       // link.
429       if (!Native) {
430         PrintAndReturn(progname, "Cannot find " + Libraries[i]);
431         return true;
432       }
433     }
434
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)) {
438       if (Verbose)
439         std::cerr << "Linking archive '" << Libraries[i] << "'\n";
440
441       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
442         PrintAndReturn(progname, ErrorMessage,
443                        ": Error linking in '" + Libraries[i] + "'");
444         return true;
445       }
446     } else {
447       if (Verbose)
448         std::cerr << "Linking file '" << Libraries[i] << "'\n";
449
450       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
451         PrintAndReturn(progname, ErrorMessage,
452                        ": error linking in '" + Libraries[i] + "'");
453         return true;
454       }
455     }
456   }
457
458   return false;
459 }