5989925d04a221af7e08e91f3509cc233a8b9a62
[oota-llvm.git] / tools / gccld / Linker.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 << progname << ": Cannot find linker input file '"
358                   << Files[i] << "'\n";
359         return true;
360       }
361
362       Pathname = std::string(SearchPath)+"/"+Files[i];
363       if (!FileExists(Pathname)) {
364         std::cerr << progname << ": Cannot find linker input file '"
365                   << Files[i] << "'\n";
366         return true;
367       }
368     }
369
370     // A user may specify an ar archive without -l, perhaps because it
371     // is not installed as a library. Detect that and link the library.
372     if (IsArchive(Pathname)) {
373       if (Verbose)
374         std::cerr << "Linking archive '" << Files[i] << "'\n";
375
376       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
377         PrintAndReturn(progname, ErrorMessage,
378                        ": Error linking in '" + Files[i] + "'");
379         return true;
380       }
381     } else {
382       if (Verbose)
383         std::cerr << "Linking file '" << Files[i] << "'\n";
384
385       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
386         PrintAndReturn(progname, ErrorMessage,
387                        ": Error linking in '" + Files[i] + "'");
388         return true;
389       }
390     }
391   }
392
393   return false;
394 }
395
396 /// LinkLibraries - takes the specified library files and links them into the
397 /// main bytecode object file.
398 ///
399 /// Inputs:
400 ///  progname   - The name of the program (infamous argv[0]).
401 ///  HeadModule - The module into which all necessary libraries will be linked.
402 ///  Libraries  - The list of libraries to link into the module.
403 ///  LibPaths   - The list of library paths in which to find libraries.
404 ///  Verbose    - Flags whether verbose messages should be printed.
405 ///  Native     - Flags whether native code is being generated.
406 ///
407 /// Outputs:
408 ///  HeadModule - The module will have all necessary libraries linked in.
409 ///
410 /// Return value:
411 ///  FALSE - No error.
412 ///  TRUE  - Error.
413 ///
414 bool LinkLibraries(const char *progname,
415                    Module *HeadModule,
416                    const std::vector<std::string> &Libraries,
417                    const std::vector<std::string> &LibPaths,
418                    bool Verbose,
419                    bool Native)
420 {
421   // String in which to receive error messages.
422   std::string ErrorMessage;
423
424   for (unsigned i = 1; i < Libraries.size(); ++i) {
425     // Determine where this library lives.
426     std::string Pathname = FindLib(Libraries[i], LibPaths);
427     if (Pathname.empty()) {
428       // If the pathname does not exist, then continue to the next one if
429       // we're doing a native link and give an error if we're doing a bytecode
430       // link.
431       if (!Native) {
432         PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
433         return true;
434       }
435     }
436
437     // A user may specify an ar archive without -l, perhaps because it
438     // is not installed as a library. Detect that and link the library.
439     if (IsArchive(Pathname)) {
440       if (Verbose)
441         std::cerr << "Linking archive '" << Libraries[i] << "'\n";
442
443       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
444         PrintAndReturn(progname, ErrorMessage,
445                        ": Error linking in '" + Libraries[i] + "'");
446         return true;
447       }
448     } else {
449       if (Verbose)
450         std::cerr << "Linking file '" << Libraries[i] << "'\n";
451
452       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
453         PrintAndReturn(progname, ErrorMessage,
454                        ": error linking in '" + Libraries[i] + "'");
455         return true;
456       }
457     }
458   }
459
460   return false;
461 }