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