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