cfae2b9cbeb201bce5f5b007c0581fb652d5dd1f
[oota-llvm.git] / lib / Linker / LinkArchives.cpp
1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 //
11 // This file contains routines to handle linking together LLVM bytecode files,
12 // and to handle annoying things like static libraries.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "gccld.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 "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"
29 #include <algorithm>
30 #include <fstream>
31 #include <memory>
32 #include <set>
33
34 /// FileExists - determines if the specified filename exists and is readable.
35 ///
36 /// Inputs:
37 ///  FN - The name of the file.
38 ///
39 /// Outputs:
40 ///  None.
41 ///
42 /// Return Value:
43 ///  TRUE - The file exists and is readable.
44 ///  FALSE - The file does not exist or is unreadable.
45 ///
46 static inline bool FileExists(const std::string &FN) {
47   return access(FN.c_str(), R_OK | F_OK) != -1;
48 }
49
50 /// IsArchive - determines if the specified file is an ar archive
51 /// by checking the magic string at the beginning of the file.
52 ///
53 /// Inputs:
54 ///  filename - A C++ string containing the name of the file.
55 ///
56 /// Outputs:
57 ///  None.
58 ///
59 /// Return value:
60 ///  TRUE  - The file is an archive.
61 ///  FALSE - The file is not an archive.
62 ///
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;
70 }
71
72 /// FindLib - locates a particular library.  It will prepend and append
73 /// various directories, prefixes, and suffixes until it can find the library.
74 ///
75 /// Inputs:
76 ///  Filename  - Name of the file to find.
77 ///  Paths     - List of directories to search.
78 ///
79 /// Outputs:
80 ///  None.
81 ///
82 /// Return value:
83 ///  The name of the file is returned.
84 ///  If the file is not found, an empty string is returned.
85 ///
86 static std::string
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))
90     return Filename;
91
92   // If that doesn't work, convert the name into a library name.
93   std::string LibName = "lib" + Filename;
94
95   // Iterate over the directories in Paths to see if we can find the library
96   // there.
97   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
98     std::string Directory = Paths[Index] + "/";
99
100     if (FileExists(Directory + LibName + ".bc"))
101       return Directory + LibName + ".bc";
102
103     if (FileExists(Directory + LibName + ".so"))
104       return Directory + LibName + ".so";
105
106     if (FileExists(Directory + LibName + ".a"))
107       return Directory + LibName + ".a";
108   }
109
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();
114
115   LibName = std::string(SearchPath) + "/" + LibName;
116   if (FileExists(LibName))
117     return LibName;
118
119   return std::string();
120 }
121
122 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified 
123 /// module.
124 ///
125 /// Inputs:
126 ///  M - The module in which to find defined symbols.
127 ///
128 /// Outputs:
129 ///  DefinedSymbols - A set of C++ strings that will contain the name of all
130 ///                   defined symbols.
131 ///
132 /// Return value:
133 ///  None.
134 ///
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());
142 }
143
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).
148 ///
149 /// Inputs:
150 ///  M - The module in which to find undefined symbols.
151 ///
152 /// Outputs:
153 ///  UndefinedSymbols - A set of C++ strings containing the name of all
154 ///                     undefined symbols.
155 ///
156 /// Return value:
157 ///  None.
158 ///
159 void
160 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
161   std::set<std::string> DefinedSymbols;
162   UndefinedSymbols.clear();   // Start out empty
163   
164   for (Module::iterator I = M->begin(), E = M->end(); 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   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
172     if (I->hasName()) {
173       if (I->isExternal())
174         UndefinedSymbols.insert(I->getName());
175       else if (!I->hasInternalLinkage())
176         DefinedSymbols.insert(I->getName());
177     }
178   
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!
184     else
185       ++I; // Keep this symbol in the undefined symbols list
186 }
187
188
189 /// LoadObject - reads the specified bytecode object file.
190 ///
191 /// Inputs:
192 ///  FN - The name of the file to load.
193 ///
194 /// Outputs:
195 ///  OutErrorMessage - The error message to give back to the caller.
196 ///
197 /// Return Value:
198 ///  A pointer to a module represening the bytecode file is returned.
199 ///  If an error occurs, the pointer is 0.
200 ///
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>();
209 }
210
211 /// LinkInArchive - opens an archive library and link in all objects which
212 /// provide symbols that are currently undefined.
213 ///
214 /// Inputs:
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.
218 ///
219 /// Outputs:
220 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
221 ///
222 /// Return Value:
223 ///  TRUE  - An error occurred.
224 ///  FALSE - No errors.
225 ///
226 static bool LinkInArchive(Module *M,
227                           const std::string &Filename,
228                           std::string &ErrorMessage,
229                           bool Verbose)
230 {
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!
239   }
240
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))
245     return true;
246
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]);
252   }
253
254   // While we are linking in object files, loop.
255   bool Linked = true;
256   while (Linked) {     
257     Linked = false;
258
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.
262       //
263       const std::set<std::string> &DefSymbols = DefinedSymbols[i];
264
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)) {
269           if (Verbose)
270             std::cerr << "  Found object providing symbol '" << *I << "'...\n";
271           ObjectRequired = true;
272           break;
273         }
274       
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...        
279         
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());
284         Objects.pop_back();
285         DefinedSymbols.pop_back();
286         --i;   // Do not skip an entry
287         
288         // The undefined symbols set should have shrunk.
289         GetAllUndefinedSymbols(M, UndefinedSymbols);
290         Linked = true;  // We have linked something in!
291       }
292     }
293   }
294   
295   return false;
296 }
297
298 /// LinkInFile - opens an archive library and link in all objects which
299 /// provide symbols that are currently undefined.
300 ///
301 /// Inputs:
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.
305 ///
306 /// Outputs:
307 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
308 ///
309 /// Return Value:
310 ///  TRUE  - An error occurred.
311 ///  FALSE - No errors.
312 ///
313 static bool LinkInFile(Module *HeadModule,
314                        const std::string &Filename,
315                        std::string &ErrorMessage,
316                        bool Verbose)
317 {
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);
322 }
323
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.
327 ///
328 /// Inputs:
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.
335 ///
336 /// Outputs:
337 ///  HeadModule - The module will have the specified LLVM bytecode files linked
338 ///               in.
339 ///
340 /// Return value:
341 ///  FALSE - No errors.
342 ///  TRUE  - Some error occurred.
343 ///
344 bool LinkFiles(const char *progname,
345                Module *HeadModule,
346                const std::vector<std::string> &Files,
347                bool Verbose)
348 {
349   // String in which to receive error messages.
350   std::string ErrorMessage;
351
352   // Full pathname of the file
353   std::string Pathname;
354
355   // Get the library search path from the environment
356   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
357
358   for (unsigned i = 1; i < Files.size(); ++i) {
359     // Determine where this file lives.
360     if (FileExists(Files[i])) {
361       Pathname = Files[i];
362     } else {
363       if (SearchPath == NULL) {
364         std::cerr << progname << ": Cannot find linker input file '"
365                   << Files[i] << "'\n";
366         return true;
367       }
368
369       Pathname = std::string(SearchPath)+"/"+Files[i];
370       if (!FileExists(Pathname)) {
371         std::cerr << progname << ": Cannot find linker input file '"
372                   << Files[i] << "'\n";
373         return true;
374       }
375     }
376
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)) {
380       if (Verbose)
381         std::cerr << "Linking archive '" << Files[i] << "'\n";
382
383       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
384         PrintAndReturn(progname, ErrorMessage,
385                        ": Error linking in '" + Files[i] + "'");
386         return true;
387       }
388     } else {
389       if (Verbose)
390         std::cerr << "Linking file '" << Files[i] << "'\n";
391
392       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
393         PrintAndReturn(progname, ErrorMessage,
394                        ": Error linking in '" + Files[i] + "'");
395         return true;
396       }
397     }
398   }
399
400   return false;
401 }
402
403 /// LinkLibraries - takes the specified library files and links them into the
404 /// main bytecode object file.
405 ///
406 /// Inputs:
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.
413 ///
414 /// Outputs:
415 ///  HeadModule - The module will have all necessary libraries linked in.
416 ///
417 /// Return value:
418 ///  FALSE - No error.
419 ///  TRUE  - Error.
420 ///
421 bool LinkLibraries(const char *progname,
422                    Module *HeadModule,
423                    const std::vector<std::string> &Libraries,
424                    const std::vector<std::string> &LibPaths,
425                    bool Verbose,
426                    bool Native)
427 {
428   // String in which to receive error messages.
429   std::string ErrorMessage;
430
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
437       // link.
438       if (!Native) {
439         PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
440         return true;
441       }
442     }
443
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)) {
447       if (Verbose)
448         std::cerr << "Linking archive '" << Libraries[i] << "'\n";
449
450       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
451         PrintAndReturn(progname, ErrorMessage,
452                        ": Error linking in '" + Libraries[i] + "'");
453         return true;
454       }
455     } else {
456       if (Verbose)
457         std::cerr << "Linking file '" << Libraries[i] << "'\n";
458
459       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
460         PrintAndReturn(progname, ErrorMessage,
461                        ": error linking in '" + Libraries[i] + "'");
462         return true;
463       }
464     }
465   }
466
467   return false;
468 }