add bitcode support
[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/ADT/SetOperations.h"
19 #include "llvm/Bytecode/Archive.h"
20 #include "llvm/Config/config.h"
21 #include <memory>
22 #include <set>
23 using namespace llvm;
24
25 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
26 /// exist in an LLVM module. This is a bit tricky because there may be two
27 /// symbols with the same name but different LLVM types that will be resolved to
28 /// each other but aren't currently (thus we need to treat it as resolved).
29 ///
30 /// Inputs:
31 ///  M - The module in which to find undefined symbols.
32 ///
33 /// Outputs:
34 ///  UndefinedSymbols - A set of C++ strings containing the name of all
35 ///                     undefined symbols.
36 ///
37 static void
38 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
39   std::set<std::string> DefinedSymbols;
40   UndefinedSymbols.clear();
41
42   // If the program doesn't define a main, try pulling one in from a .a file.
43   // This is needed for programs where the main function is defined in an
44   // archive, such f2c'd programs.
45   Function *Main = M->getFunction("main");
46   if (Main == 0 || Main->isDeclaration())
47     UndefinedSymbols.insert("main");
48
49   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
50     if (I->hasName()) {
51       if (I->isDeclaration())
52         UndefinedSymbols.insert(I->getName());
53       else if (!I->hasInternalLinkage()) {
54         assert(!I->hasDLLImportLinkage()
55                && "Found dllimported non-external symbol!");
56         DefinedSymbols.insert(I->getName());
57       }      
58     }
59   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
60        I != E; ++I)
61     if (I->hasName()) {
62       if (I->isDeclaration())
63         UndefinedSymbols.insert(I->getName());
64       else if (!I->hasInternalLinkage()) {
65         assert(!I->hasDLLImportLinkage()
66                && "Found dllimported non-external symbol!");
67         DefinedSymbols.insert(I->getName());
68       }      
69     }
70
71   // Prune out any defined symbols from the undefined symbols set...
72   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
73        I != UndefinedSymbols.end(); )
74     if (DefinedSymbols.count(*I))
75       UndefinedSymbols.erase(I++);  // This symbol really is defined!
76     else
77       ++I; // Keep this symbol in the undefined symbols list
78 }
79
80 /// LinkInArchive - opens an archive library and link in all objects which
81 /// provide symbols that are currently undefined.
82 ///
83 /// Inputs:
84 ///  Filename - The pathname of the archive.
85 ///
86 /// Return Value:
87 ///  TRUE  - An error occurred.
88 ///  FALSE - No errors.
89 bool
90 Linker::LinkInArchive(const sys::Path &Filename, bool &is_native) {
91
92   // Make sure this is an archive file we're dealing with
93   if (!Filename.isArchive())
94     return error("File '" + Filename.toString() + "' is not an archive.");
95
96   // Open the archive file
97   verbose("Linking archive file '" + Filename.toString() + "'");
98
99   // Find all of the symbols currently undefined in the bytecode program.
100   // If all the symbols are defined, the program is complete, and there is
101   // no reason to link in any archive files.
102   std::set<std::string> UndefinedSymbols;
103   GetAllUndefinedSymbols(Composite, UndefinedSymbols);
104
105   if (UndefinedSymbols.empty()) {
106     verbose("No symbols undefined, skipping library '" +
107             Filename.toString() + "'");
108     return false;  // No need to link anything in!
109   }
110
111   std::string ErrMsg;
112   std::auto_ptr<Archive> AutoArch (
113     Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
114
115   Archive* arch = AutoArch.get();
116
117   if (!arch)
118     return error("Cannot read archive '" + Filename.toString() +
119                  "': " + ErrMsg);
120   if (!arch->isBytecodeArchive()) {
121     is_native = true;
122     return false;
123   }
124   is_native = false;
125
126   // Save a set of symbols that are not defined by the archive. Since we're
127   // entering a loop, there's no point searching for these multiple times. This
128   // variable is used to "set_subtract" from the set of undefined symbols.
129   std::set<std::string> NotDefinedByArchive;
130
131   // Save the current set of undefined symbols, because we may have to make
132   // multiple passes over the archive:
133   std::set<std::string> CurrentlyUndefinedSymbols;
134
135   do {
136     CurrentlyUndefinedSymbols = UndefinedSymbols;
137
138     // Find the modules we need to link into the target module
139     std::set<ModuleProvider*> Modules;
140     if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
141       return error("Cannot find symbols in '" + Filename.toString() + 
142                    "': " + ErrMsg);
143
144     // If we didn't find any more modules to link this time, we are done
145     // searching this archive.
146     if (Modules.empty())
147       break;
148
149     // Any symbols remaining in UndefinedSymbols after
150     // findModulesDefiningSymbols are ones that the archive does not define. So
151     // we add them to the NotDefinedByArchive variable now.
152     NotDefinedByArchive.insert(UndefinedSymbols.begin(),
153         UndefinedSymbols.end());
154
155     // Loop over all the ModuleProviders that we got back from the archive
156     for (std::set<ModuleProvider*>::iterator I=Modules.begin(), E=Modules.end();
157          I != E; ++I) {
158
159       // Get the module we must link in.
160       std::string moduleErrorMsg;
161       std::auto_ptr<Module> AutoModule((*I)->releaseModule( &moduleErrorMsg ));
162       Module* aModule = AutoModule.get();
163
164       if (aModule != NULL) {
165         verbose("  Linking in module: " + aModule->getModuleIdentifier());
166
167         // Link it in
168         if (LinkInModule(aModule, &moduleErrorMsg)) {
169           return error("Cannot link in module '" +
170                        aModule->getModuleIdentifier() + "': " + moduleErrorMsg);
171         }
172       } 
173     }
174     
175     // Get the undefined symbols from the aggregate module. This recomputes the
176     // symbols we still need after the new modules have been linked in.
177     GetAllUndefinedSymbols(Composite, UndefinedSymbols);
178
179     // At this point we have two sets of undefined symbols: UndefinedSymbols
180     // which holds the undefined symbols from all the modules, and
181     // NotDefinedByArchive which holds symbols we know the archive doesn't
182     // define. There's no point searching for symbols that we won't find in the
183     // archive so we subtract these sets.
184     set_subtract(UndefinedSymbols, NotDefinedByArchive);
185
186     // If there's no symbols left, no point in continuing to search the
187     // archive.
188     if (UndefinedSymbols.empty())
189       break;
190   } while (CurrentlyUndefinedSymbols != UndefinedSymbols);
191
192   return false;
193 }