d668b510cd464e1f1c57605fbf13bfadf3196a24
[oota-llvm.git] / lib / Linker / LinkArchives.cpp
1 //===- lib/Linker/LinkArchives.cpp - Link 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 "llvm/Linker.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/Archive.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/SystemUtils.h"
30 #include <algorithm>
31 #include <fstream>
32 #include <memory>
33 #include <set>
34 using namespace llvm;
35
36 /// FindLib - Try to convert Filename into the name of a file that we can open,
37 /// if it does not already name a file we can open, by first trying to open
38 /// Filename, then libFilename.[suffix] for each of a set of several common
39 /// library suffixes, in each of the directories in Paths and the directory
40 /// named by the value of the environment variable LLVM_LIB_SEARCH_PATH. Returns
41 /// an empty string if no matching file can be found.
42 ///
43 std::string llvm::FindLib(const std::string &Filename,
44                           const std::vector<std::string> &Paths,
45                           bool SharedObjectOnly) {
46   // Determine if the pathname can be found as it stands.
47   if (FileOpenable(Filename))
48     return Filename;
49
50   // If that doesn't work, convert the name into a library name.
51   std::string LibName = "lib" + Filename;
52
53   // Iterate over the directories in Paths to see if we can find the library
54   // there.
55   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
56     std::string Directory = Paths[Index] + "/";
57
58     if (!SharedObjectOnly && FileOpenable(Directory + LibName + ".bc"))
59       return Directory + LibName + ".bc";
60
61     if (FileOpenable(Directory + LibName + SHLIBEXT))
62       return Directory + LibName + SHLIBEXT;
63
64     if (!SharedObjectOnly && FileOpenable(Directory + LibName + ".a"))
65       return Directory + LibName + ".a";
66   }
67
68   // One last hope: Check LLVM_LIB_SEARCH_PATH.
69   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
70   if (SearchPath == NULL)
71     return std::string();
72
73   LibName = std::string(SearchPath) + "/" + LibName;
74   if (FileOpenable(LibName))
75     return LibName;
76
77   return std::string();
78 }
79
80 /// GetAllDefinedSymbols - Modifies its parameter DefinedSymbols to contain the
81 /// name of each externally-visible symbol defined in M.
82 ///
83 void llvm::GetAllDefinedSymbols(Module *M,
84                                 std::set<std::string> &DefinedSymbols) {
85   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
86     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
87       DefinedSymbols.insert(I->getName());
88   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
89     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
90       DefinedSymbols.insert(I->getName());
91 }
92
93 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
94 /// exist in an LLVM module. This is a bit tricky because there may be two
95 /// symbols with the same name but different LLVM types that will be resolved to
96 /// each other but aren't currently (thus we need to treat it as resolved).
97 ///
98 /// Inputs:
99 ///  M - The module in which to find undefined symbols.
100 ///
101 /// Outputs:
102 ///  UndefinedSymbols - A set of C++ strings containing the name of all
103 ///                     undefined symbols.
104 ///
105 void
106 llvm::GetAllUndefinedSymbols(Module *M,
107                              std::set<std::string> &UndefinedSymbols) {
108   std::set<std::string> DefinedSymbols;
109   UndefinedSymbols.clear();   // Start out empty
110   
111   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
112     if (I->hasName()) {
113       if (I->isExternal())
114         UndefinedSymbols.insert(I->getName());
115       else if (!I->hasInternalLinkage())
116         DefinedSymbols.insert(I->getName());
117     }
118   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
119     if (I->hasName()) {
120       if (I->isExternal())
121         UndefinedSymbols.insert(I->getName());
122       else if (!I->hasInternalLinkage())
123         DefinedSymbols.insert(I->getName());
124     }
125   
126   // Prune out any defined symbols from the undefined symbols set...
127   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
128        I != UndefinedSymbols.end(); )
129     if (DefinedSymbols.count(*I))
130       UndefinedSymbols.erase(I++);  // This symbol really is defined!
131     else
132       ++I; // Keep this symbol in the undefined symbols list
133 }
134
135
136 /// LoadObject - Read in and parse the bytecode file named by FN and return the
137 /// module it contains (wrapped in an auto_ptr), or 0 and set ErrorMessage if an
138 /// error occurs.
139 ///
140 static std::auto_ptr<Module> LoadObject(const std::string &FN,
141                                        std::string &ErrorMessage) {
142   std::string ParserErrorMessage;
143   Module *Result = ParseBytecodeFile(FN, &ParserErrorMessage);
144   if (Result) return std::auto_ptr<Module>(Result);
145   ErrorMessage = "Bytecode file '" + FN + "' could not be loaded";
146   if (ParserErrorMessage.size()) ErrorMessage += ": " + ParserErrorMessage;
147   return std::auto_ptr<Module>();
148 }
149
150 /// LinkInArchive - opens an archive library and link in all objects which
151 /// provide symbols that are currently undefined.
152 ///
153 /// Inputs:
154 ///  M        - The module in which to link the archives.
155 ///  Filename - The pathname of the archive.
156 ///  Verbose  - Flags whether verbose messages should be printed.
157 ///
158 /// Outputs:
159 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
160 ///
161 /// Return Value:
162 ///  TRUE  - An error occurred.
163 ///  FALSE - No errors.
164 ///
165 bool llvm::LinkInArchive(Module *M,
166                           const std::string &Filename,
167                           std::string* ErrorMessage,
168                           bool Verbose)
169 {
170   // Find all of the symbols currently undefined in the bytecode program.
171   // If all the symbols are defined, the program is complete, and there is
172   // no reason to link in any archive files.
173   std::set<std::string> UndefinedSymbols;
174   GetAllUndefinedSymbols(M, UndefinedSymbols);
175   if (UndefinedSymbols.empty()) {
176     if (Verbose) std::cerr << "  No symbols undefined, don't link library!\n";
177     return false;  // No need to link anything in!
178   }
179
180   // Open the archive file
181   if (Verbose) std::cerr << "  Loading archive file '" << Filename << "'\n";
182   Archive* arch = Archive::OpenAndLoadSymbols(sys::Path(Filename));
183
184   // While we are linking in object files, loop.
185   while (true) {     
186     std::set<ModuleProvider*> Modules;
187     // Find the modules we need to link
188     arch->findModulesDefiningSymbols(UndefinedSymbols,Modules);
189
190     // If we didn't find any more modules to link this time, we are done.
191     if (Modules.empty())
192       break;
193
194     // Loop over all the ModuleProviders that we got back from the archive
195     for (std::set<ModuleProvider*>::iterator I=Modules.begin(), E=Modules.end();
196          I != E; ++I) {
197       // Get the module we must link in.
198       Module* aModule = (*I)->releaseModule();
199       std::cout << "Linked: " << aModule->getModuleIdentifier() << "\n";
200
201       // Link it in
202       if (LinkModules(M, aModule, ErrorMessage)) {
203         // don't create a memory leak
204         delete aModule;
205         delete arch;
206         return true;   // Couldn't link in the right object file...        
207       }
208         
209       // Since we have linked in this object, throw it away now.
210       delete aModule;
211     }
212
213     // We have linked in a set of modules determined by the archive to satisfy
214     // our missing symbols. Linking in the new modules will have satisfied some
215     // symbols but may introduce additional missing symbols. We need to update
216     // the list of undefined symbols and try again until the archive doesn't
217     // have any modules that satisfy our symbols. 
218     GetAllUndefinedSymbols(M, UndefinedSymbols);
219   }
220   
221   return false;
222 }
223
224 /// LinkInFile - opens a bytecode file and links in all objects which
225 /// provide symbols that are currently undefined.
226 ///
227 /// Inputs:
228 ///  HeadModule - The module in which to link the bytecode file.
229 ///  Filename   - The pathname of the bytecode file.
230 ///  Verbose    - Flags whether verbose messages should be printed.
231 ///
232 /// Outputs:
233 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
234 ///
235 /// Return Value:
236 ///  TRUE  - An error occurred.
237 ///  FALSE - No errors.
238 ///
239 static bool LinkInFile(Module *HeadModule,
240                        const std::string &Filename,
241                        std::string &ErrorMessage,
242                        bool Verbose)
243 {
244   std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
245   if (M.get() == 0) return true;
246   bool Result = LinkModules(HeadModule, M.get(), &ErrorMessage);
247   if (Verbose) std::cerr << "Linked in bytecode file '" << Filename << "'\n";
248   return Result;
249 }
250
251 /// LinkFiles - takes a module and a list of files and links them all together.
252 /// It locates the file either in the current directory, as its absolute
253 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
254 ///
255 /// Inputs:
256 ///  progname   - The name of the program (infamous argv[0]).
257 ///  HeadModule - The module under which all files will be linked.
258 ///  Files      - A vector of C++ strings indicating the LLVM bytecode filenames
259 ///               to be linked.  The names can refer to a mixture of pure LLVM
260 ///               bytecode files and archive (ar) formatted files.
261 ///  Verbose    - Flags whether verbose output should be printed while linking.
262 ///
263 /// Outputs:
264 ///  HeadModule - The module will have the specified LLVM bytecode files linked
265 ///               in.
266 ///
267 /// Return value:
268 ///  FALSE - No errors.
269 ///  TRUE  - Some error occurred.
270 ///
271 bool llvm::LinkFiles(const char *progname, Module *HeadModule,
272                      const std::vector<std::string> &Files, bool Verbose) {
273   // String in which to receive error messages.
274   std::string ErrorMessage;
275
276   // Full pathname of the file
277   std::string Pathname;
278
279   // Get the library search path from the environment
280   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
281
282   for (unsigned i = 0; i < Files.size(); ++i) {
283     // Determine where this file lives.
284     if (FileOpenable(Files[i])) {
285       Pathname = Files[i];
286     } else {
287       if (SearchPath == NULL) {
288         std::cerr << progname << ": Cannot find linker input file '"
289                   << Files[i] << "'\n";
290         std::cerr << progname
291                   << ": Warning: Your LLVM_LIB_SEARCH_PATH is unset.\n";
292         return true;
293       }
294
295       Pathname = std::string(SearchPath)+"/"+Files[i];
296       if (!FileOpenable(Pathname)) {
297         std::cerr << progname << ": Cannot find linker input file '"
298                   << Files[i] << "'\n";
299         return true;
300       }
301     }
302
303     // A user may specify an ar archive without -l, perhaps because it
304     // is not installed as a library. Detect that and link the library.
305     if (IsArchive(Pathname)) {
306       if (Verbose)
307         std::cerr << "Trying to link archive '" << Pathname << "'\n";
308
309       if (LinkInArchive(HeadModule, Pathname, &ErrorMessage, Verbose)) {
310         std::cerr << progname << ": Error linking in archive '" << Pathname 
311                   << "': " << ErrorMessage << "\n";
312         return true;
313       }
314     } else if (IsBytecode(Pathname)) {
315       if (Verbose)
316         std::cerr << "Trying to link bytecode file '" << Pathname << "'\n";
317
318       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
319         std::cerr << progname << ": Error linking in bytecode file '"
320                   << Pathname << "': " << ErrorMessage << "\n";
321         return true;
322       }
323     } else {
324       std::cerr << progname << ": Warning: invalid file `" << Pathname 
325                 << "' ignored.\n";
326     }
327   }
328
329   return false;
330 }
331
332 /// LinkLibraries - takes the specified library files and links them into the
333 /// main bytecode object file.
334 ///
335 /// Inputs:
336 ///  progname   - The name of the program (infamous argv[0]).
337 ///  HeadModule - The module into which all necessary libraries will be linked.
338 ///  Libraries  - The list of libraries to link into the module.
339 ///  LibPaths   - The list of library paths in which to find libraries.
340 ///  Verbose    - Flags whether verbose messages should be printed.
341 ///  Native     - Flags whether native code is being generated.
342 ///
343 /// Outputs:
344 ///  HeadModule - The module will have all necessary libraries linked in.
345 ///
346 /// Return value:
347 ///  FALSE - No error.
348 ///  TRUE  - Error.
349 ///
350 void llvm::LinkLibraries(const char *progname, Module *HeadModule,
351                          const std::vector<std::string> &Libraries,
352                          const std::vector<std::string> &LibPaths,
353                          bool Verbose, bool Native) {
354   // String in which to receive error messages.
355   std::string ErrorMessage;
356
357   for (unsigned i = 0; i < Libraries.size(); ++i) {
358     // Determine where this library lives.
359     std::string Pathname = FindLib(Libraries[i], LibPaths);
360     if (Pathname.empty()) {
361       // If the pathname does not exist, then continue to the next one if
362       // we're doing a native link and give an error if we're doing a bytecode
363       // link.
364       if (!Native) {
365         std::cerr << progname << ": WARNING: Cannot find library -l"
366                   << Libraries[i] << "\n";
367         continue;
368       }
369     }
370
371     // A user may specify an ar archive without -l, perhaps because it
372     // is not installed as a library. Detect that and link the library.
373     if (IsArchive(Pathname)) {
374       if (Verbose)
375         std::cerr << "Trying to link archive '" << Pathname << "' (-l"
376                   << Libraries[i] << ")\n";
377
378       if (LinkInArchive(HeadModule, Pathname, &ErrorMessage, Verbose)) {
379         std::cerr << progname << ": " << ErrorMessage
380                   << ": Error linking in archive '" << Pathname << "' (-l"
381                   << Libraries[i] << ")\n";
382         exit(1);
383       }
384     } else if (IsBytecode(Pathname)) {
385       if (Verbose)
386         std::cerr << "Trying to link bytecode file '" << Pathname
387                   << "' (-l" << Libraries[i] << ")\n";
388
389       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
390         std::cerr << progname << ": " << ErrorMessage
391                   << ": error linking in bytecode file '" << Pathname << "' (-l"
392                   << Libraries[i] << ")\n";
393         exit(1);
394       }
395     }
396   }
397 }