0d0dc9fabaa2dc178096de7a085d8d02de5cff50
[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 //
28 // Function: FileExists ()
29 //
30 // Description:
31 //  Determine if the specified filename exists and is readable.
32 //
33 // Inputs:
34 //  FN - The name of the file.
35 //
36 // Outputs:
37 //  None.
38 //
39 // Return Value:
40 //  TRUE - The file exists and is readable.
41 //  FALSE - The file does not exist or is unreadable.
42 //
43 static inline bool FileExists(const std::string &FN) {
44   return access(FN.c_str(), R_OK | F_OK) != -1;
45 }
46
47 //
48 // Function: IsArchive ()
49 //
50 // Description:
51 //  Determine if the specified file is an ar archive.  It determines this by
52 //  checking the magic string at the beginning of the file.
53 //
54 // Inputs:
55 //  filename - A C++ string containing the name of the file.
56 //
57 // Outputs:
58 //  None.
59 //
60 // Return value:
61 //  TRUE  - The file is an archive.
62 //  FALSE - The file is not an archive.
63 //
64 static inline bool IsArchive(const std::string &filename)
65 {
66   std::string ArchiveMagic("!<arch>\012");
67   char buf[1 + ArchiveMagic.size()];
68   std::ifstream f(filename.c_str());
69   f.read(buf, ArchiveMagic.size());
70   buf[ArchiveMagic.size()] = '\0';
71   return ArchiveMagic == buf;
72 }
73
74 //
75 // Function: FindLib ()
76 //
77 // Description:
78 //  This function locates a particular library.  It will prepend and append
79 //  various directories, prefixes, and suffixes until it can find the library.
80 //
81 // Inputs:
82 //  Filename  - Name of the file to find.
83 //  Paths     - List of directories to search.
84 //
85 // Outputs:
86 //  None.
87 //
88 // Return value:
89 //  The name of the file is returned.
90 //  If the file is not found, an empty string is returned.
91 //
92 static std::string
93 FindLib(const std::string &Filename, const std::vector<std::string> &Paths)
94 {
95   // Determine if the pathname can be found as it stands.
96   if (FileExists(Filename))
97     return Filename;
98
99   // If that doesn't work, convert the name into a library name.
100   std::string LibName = "lib" + Filename;
101
102   // Iterate over the directories in Paths to see if we can find the library
103   // there.
104   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
105     std::string Directory = Paths[Index] + "/";
106
107     if (FileExists(Directory + LibName + ".bc"))
108       return Directory + LibName + ".bc";
109
110     if (FileExists(Directory + LibName + ".so"))
111       return Directory + LibName + ".so";
112
113     if (FileExists(Directory + LibName + ".a"))
114       return Directory + LibName + ".a";
115   }
116
117   // One last hope: Check LLVM_LIB_SEARCH_PATH.
118   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
119   if (SearchPath == NULL)
120     return std::string();
121
122   LibName = std::string(SearchPath) + "/" + LibName;
123   if (FileExists(LibName))
124     return LibName;
125
126   return std::string();
127 }
128
129 //
130 // Function: GetAllDefinedSymbols ()
131 //
132 // Description:
133 //  Find all of the defined symbols in the specified module.
134 //
135 // Inputs:
136 //  M - The module in which to find defined symbols.
137 //
138 // Outputs:
139 //  DefinedSymbols - A set of C++ strings that will contain the name of all
140 //                   defined symbols.
141 //
142 // Return value:
143 //  None.
144 //
145 void
146 GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols)
147 {
148   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
149     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
150       DefinedSymbols.insert(I->getName());
151   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
152     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
153       DefinedSymbols.insert(I->getName());
154 }
155
156 //
157 // Function: GetAllUndefinedSymbols ()
158 //
159 // Description:
160 //  This calculates the set of undefined symbols that still exist in an LLVM
161 //  module.  This is a bit tricky because there may be two symbols with the
162 //  same name but different LLVM types that will be resolved to each other but
163 //  aren't currently (thus we need to treat it as resolved).
164 //
165 // Inputs:
166 //  M - The module in which to find undefined symbols.
167 //
168 // Outputs:
169 //  UndefinedSymbols - A set of C++ strings containing the name of all
170 //                     undefined symbols.
171 //
172 // Return value:
173 //  None.
174 //
175 void
176 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols)
177 {
178   std::set<std::string> DefinedSymbols;
179   UndefinedSymbols.clear();   // Start out empty
180   
181   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
182     if (I->hasName()) {
183       if (I->isExternal())
184         UndefinedSymbols.insert(I->getName());
185       else if (!I->hasInternalLinkage())
186         DefinedSymbols.insert(I->getName());
187     }
188   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
189     if (I->hasName()) {
190       if (I->isExternal())
191         UndefinedSymbols.insert(I->getName());
192       else if (!I->hasInternalLinkage())
193         DefinedSymbols.insert(I->getName());
194     }
195   
196   // Prune out any defined symbols from the undefined symbols set...
197   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
198        I != UndefinedSymbols.end(); )
199     if (DefinedSymbols.count(*I))
200       UndefinedSymbols.erase(I++);  // This symbol really is defined!
201     else
202       ++I; // Keep this symbol in the undefined symbols list
203 }
204
205
206 //
207 // Function: LoadObject ()
208 //
209 // Description:
210 //  Read the specified bytecode object file.
211 //
212 // Inputs:
213 //  FN - The name of the file to load.
214 //
215 // Outputs:
216 //  OutErrorMessage - The error message to give back to the caller.
217 //
218 // Return Value:
219 //  A pointer to a module represening the bytecode file is returned.
220 //  If an error occurs, the pointer is 0.
221 //
222 std::auto_ptr<Module>
223 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
224   std::string ErrorMessage;
225   Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
226   if (Result) return std::auto_ptr<Module>(Result);
227   OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
228   if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
229   return std::auto_ptr<Module>();
230 }
231
232 //
233 // Function: LinkInArchive ()
234 //
235 // Description:
236 //  This function will open an archive library and link in all objects which
237 //  provide symbols that are currently undefined.
238 //
239 // Inputs:
240 //  M        - The module in which to link the archives.
241 //  Filename - The pathname of the archive.
242 //  Verbose  - Flags whether verbose messages should be printed.
243 //
244 // Outputs:
245 //  ErrorMessage - A C++ string detailing what error occurred, if any.
246 //
247 // Return Value:
248 //  TRUE  - An error occurred.
249 //  FALSE - No errors.
250 //
251 static bool LinkInArchive(Module *M,
252                           const std::string &Filename,
253                           std::string &ErrorMessage,
254                           bool Verbose)
255 {
256   //
257   // Find all of the symbols currently undefined in the bytecode program.
258   // If all the symbols are defined, the program is complete, and there is
259   // no reason to link in any archive files.
260   //
261   std::set<std::string> UndefinedSymbols;
262   GetAllUndefinedSymbols(M, UndefinedSymbols);
263   if (UndefinedSymbols.empty()) {
264     if (Verbose) std::cerr << "  No symbols undefined, don't link library!\n";
265     return false;  // No need to link anything in!
266   }
267
268   //
269   // Load in the archive objects.
270   //
271   if (Verbose) std::cerr << "  Loading '" << Filename << "'\n";
272   std::vector<Module*> Objects;
273   if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
274     return true;
275
276   //
277   // Figure out which symbols are defined by all of the modules in the archive.
278   //
279   std::vector<std::set<std::string> > DefinedSymbols;
280   DefinedSymbols.resize(Objects.size());
281   for (unsigned i = 0; i != Objects.size(); ++i) {
282     GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
283   }
284
285   // While we are linking in object files, loop.
286   bool Linked = true;
287   while (Linked) {     
288     Linked = false;
289
290     for (unsigned i = 0; i != Objects.size(); ++i) {
291       // Consider whether we need to link in this module...  we only need to
292       // link it in if it defines some symbol which is so far undefined.
293       //
294       const std::set<std::string> &DefSymbols = DefinedSymbols[i];
295
296       bool ObjectRequired = false;
297       for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
298              E = UndefinedSymbols.end(); I != E; ++I)
299         if (DefSymbols.count(*I)) {
300           if (Verbose)
301             std::cerr << "  Found object providing symbol '" << *I << "'...\n";
302           ObjectRequired = true;
303           break;
304         }
305       
306       // We DO need to link this object into the program...
307       if (ObjectRequired) {
308         if (LinkModules(M, Objects[i], &ErrorMessage))
309           return true;   // Couldn't link in the right object file...        
310         
311         // Since we have linked in this object, delete it from the list of
312         // objects to consider in this archive file.
313         std::swap(Objects[i], Objects.back());
314         std::swap(DefinedSymbols[i], DefinedSymbols.back());
315         Objects.pop_back();
316         DefinedSymbols.pop_back();
317         --i;   // Do not skip an entry
318         
319         // The undefined symbols set should have shrunk.
320         GetAllUndefinedSymbols(M, UndefinedSymbols);
321         Linked = true;  // We have linked something in!
322       }
323     }
324   }
325   
326   return false;
327 }
328
329 //
330 // Function: LinkInFile ()
331 //
332 // Description:
333 //  This function will open an archive library and link in all objects which
334 //  provide symbols that are currently undefined.
335 //
336 // Inputs:
337 //  HeadModule - The module in which to link the archives.
338 //  Filename   - The pathname of the archive.
339 //  Verbose    - Flags whether verbose messages should be printed.
340 //
341 // Outputs:
342 //  ErrorMessage - A C++ string detailing what error occurred, if any.
343 //
344 // Return Value:
345 //  TRUE  - An error occurred.
346 //  FALSE - No errors.
347 //
348 static bool LinkInFile(Module *HeadModule,
349                        const std::string &Filename,
350                        std::string &ErrorMessage,
351                        bool Verbose)
352 {
353   std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
354   if (M.get() == 0) return true;
355   if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
356   return LinkModules(HeadModule, M.get(), &ErrorMessage);
357 }
358
359 //
360 // Function: LinkFiles ()
361 //
362 // Description:
363 //  This function takes a module and a list of files and links them all
364 //  together.  It locates the file either in the current directory, as it's
365 //  absolute or relative pathname, or as a file somewhere in
366 //  LLVM_LIB_SEARCH_PATH.
367 //
368 // Inputs:
369 //  progname   - The name of the program (infamous argv[0]).
370 //  HeadModule - The module under which all files will be linked.
371 //  Files      - A vector of C++ strings indicating the LLVM bytecode filenames
372 //               to be linked.  The names can refer to a mixture of pure LLVM
373 //               bytecode files and archive (ar) formatted files.
374 //  Verbose    - Flags whether verbose output should be printed while linking.
375 //
376 // Outputs:
377 //  HeadModule - The module will have the specified LLVM bytecode files linked
378 //               in.
379 //
380 // Return value:
381 //  FALSE - No errors.
382 //  TRUE  - Some error occurred.
383 //
384 bool LinkFiles(const char *progname,
385                Module *HeadModule,
386                const std::vector<std::string> &Files,
387                bool Verbose)
388 {
389   // String in which to receive error messages.
390   std::string ErrorMessage;
391
392   // Full pathname of the file
393   std::string Pathname;
394
395   // Get the library search path from the environment
396   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
397
398   for (unsigned i = 1; i < Files.size(); ++i) {
399     // Determine where this file lives.
400     if (FileExists(Files[i])) {
401       Pathname = Files[i];
402     } else {
403       if (SearchPath == NULL) {
404         std::cerr << "Cannot find " << Files[i];
405         return true;
406       }
407
408       Pathname = std::string(SearchPath)+"/"+Files[i];
409       if (!FileExists(Pathname)) {
410         std::cerr << "Cannot find " << Files[i];
411         return true;
412       }
413     }
414
415     // A user may specify an ar archive without -l, perhaps because it
416     // is not installed as a library. Detect that and link the library.
417     if (IsArchive(Pathname)) {
418       if (Verbose)
419         std::cerr << "Linking archive '" << Files[i] << "'\n";
420
421       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
422         PrintAndReturn(progname, ErrorMessage,
423                        ": Error linking in '" + Files[i] + "'");
424         return true;
425       }
426     } else {
427       if (Verbose)
428         std::cerr << "Linking file '" << Files[i] << "'\n";
429
430       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
431         PrintAndReturn(progname, ErrorMessage,
432                        ": error linking in '" + Files[i] + "'");
433         return true;
434       }
435     }
436   }
437
438   return false;
439 }
440
441 //
442 // Function: LinkLibraries ()
443 //
444 // Description:
445 //  This function takes the specified library files and links them into the
446 //  main bytecode object file.
447 //
448 // Inputs:
449 //  progname   - The name of the program (infamous argv[0]).
450 //  HeadModule - The module into which all necessary libraries will be linked.
451 //  Libraries  - The list of libraries to link into the module.
452 //  LibPaths   - The list of library paths in which to find libraries.
453 //  Verbose    - Flags whether verbose messages should be printed.
454 //  Native     - Flags whether native code is being generated.
455 //
456 // Outputs:
457 //  HeadModule - The module will have all necessary libraries linked in.
458 //
459 // Return value:
460 //  FALSE - No error.
461 //  TRUE  - Error.
462 //
463 bool LinkLibraries(const char *progname,
464                    Module *HeadModule,
465                    const std::vector<std::string> &Libraries,
466                    const std::vector<std::string> &LibPaths,
467                    bool Verbose,
468                    bool Native)
469 {
470   // String in which to receive error messages.
471   std::string ErrorMessage;
472
473   for (unsigned i = 1; i < Libraries.size(); ++i) {
474     // Determine where this library lives.
475     std::string Pathname = FindLib(Libraries[i], LibPaths);
476     if (Pathname.empty()) {
477       // If the pathname does not exist, then continue to the next one if
478       // we're doing a native link and give an error if we're doing a bytecode
479       // link.
480       if (!Native) {
481         PrintAndReturn(progname, "Cannot find " + Libraries[i]);
482         return true;
483       }
484     }
485
486     // A user may specify an ar archive without -l, perhaps because it
487     // is not installed as a library. Detect that and link the library.
488     if (IsArchive(Pathname)) {
489       if (Verbose)
490         std::cerr << "Linking archive '" << Libraries[i] << "'\n";
491
492       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
493         PrintAndReturn(progname, ErrorMessage,
494                        ": Error linking in '" + Libraries[i] + "'");
495         return true;
496       }
497     } else {
498       if (Verbose)
499         std::cerr << "Linking file '" << Libraries[i] << "'\n";
500
501       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
502         PrintAndReturn(progname, ErrorMessage,
503                        ": error linking in '" + Libraries[i] + "'");
504         return true;
505       }
506     }
507   }
508
509   return false;
510 }