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