Linker.h revision 226633
1240116Smarcel//===- llvm/Linker.h - Module Linker Interface ------------------*- C++ -*-===//
2240116Smarcel//
3240116Smarcel//                     The LLVM Compiler Infrastructure
4240116Smarcel//
5240116Smarcel// This file is distributed under the University of Illinois Open Source
6240116Smarcel// License. See LICENSE.TXT for details.
7240116Smarcel//
8240116Smarcel//===----------------------------------------------------------------------===//
9240116Smarcel//
10240116Smarcel// This file defines the interface to the module/file/archive linker.
11240116Smarcel//
12240116Smarcel//===----------------------------------------------------------------------===//
13240116Smarcel
14240116Smarcel#ifndef LLVM_LINKER_H
15240116Smarcel#define LLVM_LINKER_H
16240116Smarcel
17240116Smarcel#include <memory>
18240116Smarcel#include <vector>
19240116Smarcel#include "llvm/ADT/StringRef.h"
20240116Smarcel
21240116Smarcelnamespace llvm {
22240116Smarcel  namespace sys { class Path; }
23240116Smarcel
24240116Smarcelclass Module;
25240116Smarcelclass LLVMContext;
26275988Sngie
27275988Sngie/// This class provides the core functionality of linking in LLVM. It retains a
28240116Smarcel/// Module object which is the composite of the modules and libraries linked
29260029Sjmmv/// into it. The composite Module can be retrieved via the getModule() method.
30260029Sjmmv/// In this case the Linker still retains ownership of the Module. If the
31260029Sjmmv/// releaseModule() method is used, the ownership of the Module is transferred
32240116Smarcel/// to the caller and the Linker object is only suitable for destruction.
33260029Sjmmv/// The Linker can link Modules from memory, bitcode files, or bitcode
34260029Sjmmv/// archives.  It retains a set of search paths in which to find any libraries
35240116Smarcel/// presented to it. By default, the linker will generate error and warning
36240116Smarcel/// messages to stderr but this capability can be turned off with the
37240116Smarcel/// QuietWarnings and QuietErrors flags. It can also be instructed to verbosely
38260029Sjmmv/// print out the linking actions it is taking with the Verbose flag.
39260029Sjmmv/// @brief The LLVM Linker.
40260029Sjmmvclass Linker {
41260029Sjmmv
42260029Sjmmv  /// @name Types
43260029Sjmmv  /// @{
44260029Sjmmv  public:
45260029Sjmmv    /// This type is used to pass the linkage items (libraries and files) to
46260029Sjmmv    /// the LinkItems function. It is composed of string/bool pairs. The string
47260029Sjmmv    /// provides the name of the file or library (as with the -l option). The
48240116Smarcel    /// bool should be true for libraries and false for files, signifying
49260029Sjmmv    /// "isLibrary".
50260029Sjmmv    /// @brief A list of linkage items
51260029Sjmmv    typedef std::vector<std::pair<std::string,bool> > ItemList;
52240116Smarcel
53260029Sjmmv    /// This enumeration is used to control various optional features of the
54260029Sjmmv    /// linker.
55260029Sjmmv    enum ControlFlags {
56260029Sjmmv      Verbose       = 1, ///< Print to stderr what steps the linker is taking
57240116Smarcel      QuietWarnings = 2, ///< Don't print warnings to stderr.
58260029Sjmmv      QuietErrors   = 4  ///< Don't print errors to stderr.
59240116Smarcel    };
60240116Smarcel
61240116Smarcel    enum LinkerMode {
62240116Smarcel      DestroySource = 0, // Allow source module to be destroyed.
63240116Smarcel      PreserveSource = 1 // Preserve the source module.
64275988Sngie    };
65
66  /// @}
67  /// @name Constructors
68  /// @{
69  public:
70    /// Construct the Linker with an empty module which will be given the
71    /// name \p progname. \p progname will also be used for error messages.
72    /// @brief Construct with empty module
73    Linker(StringRef progname, ///< name of tool running linker
74           StringRef modulename, ///< name of linker's end-result module
75           LLVMContext &C, ///< Context for global info
76           unsigned Flags = 0  ///< ControlFlags (one or more |'d together)
77    );
78
79    /// Construct the Linker with a previously defined module, \p aModule. Use
80    /// \p progname for the name of the program in error messages.
81    /// @brief Construct with existing module
82    Linker(StringRef progname, Module* aModule, unsigned Flags = 0);
83
84    /// Destruct the Linker.
85    /// @brief Destructor
86    ~Linker();
87
88  /// @}
89  /// @name Accessors
90  /// @{
91  public:
92    /// This method gets the composite module into which linking is being
93    /// done. The Composite module starts out empty and accumulates modules
94    /// linked into it via the various LinkIn* methods. This method does not
95    /// release the Module to the caller. The Linker retains ownership and will
96    /// destruct the Module when the Linker is destructed.
97    /// @see releaseModule
98    /// @brief Get the linked/composite module.
99    Module* getModule() const { return Composite; }
100
101    /// This method releases the composite Module into which linking is being
102    /// done. Ownership of the composite Module is transferred to the caller who
103    /// must arrange for its destruct. After this method is called, the Linker
104    /// terminates the linking session for the returned Module. It will no
105    /// longer utilize the returned Module but instead resets itself for
106    /// subsequent linking as if the constructor had been called. The Linker's
107    /// LibPaths and flags to be reset, and memory will be released.
108    /// @brief Release the linked/composite module.
109    Module* releaseModule();
110
111    /// This method gets the list of libraries that form the path that the
112    /// Linker will search when it is presented with a library name.
113    /// @brief Get the Linkers library path
114    const std::vector<sys::Path>& getLibPaths() const { return LibPaths; }
115
116    /// This method returns an error string suitable for printing to the user.
117    /// The return value will be empty unless an error occurred in one of the
118    /// LinkIn* methods. In those cases, the LinkIn* methods will have returned
119    /// true, indicating an error occurred. At most one error is retained so
120    /// this function always returns the last error that occurred. Note that if
121    /// the Quiet control flag is not set, the error string will have already
122    /// been printed to stderr.
123    /// @brief Get the text of the last error that occurred.
124    const std::string &getLastError() const { return Error; }
125
126  /// @}
127  /// @name Mutators
128  /// @{
129  public:
130    /// Add a path to the list of paths that the Linker will search. The Linker
131    /// accumulates the set of libraries added
132    /// library paths for the target platform. The standard libraries will
133    /// always be searched last. The added libraries will be searched in the
134    /// order added.
135    /// @brief Add a path.
136    void addPath(const sys::Path& path);
137
138    /// Add a set of paths to the list of paths that the linker will search. The
139    /// Linker accumulates the set of libraries added. The \p paths will be
140    /// added to the end of the Linker's list. Order will be retained.
141    /// @brief Add a set of paths.
142    void addPaths(const std::vector<std::string>& paths);
143
144    /// This method augments the Linker's list of library paths with the system
145    /// paths of the host operating system, include LLVM_LIB_SEARCH_PATH.
146    /// @brief Add the system paths.
147    void addSystemPaths();
148
149    /// Control optional linker behavior by setting a group of flags. The flags
150    /// are defined in the ControlFlags enumeration.
151    /// @see ControlFlags
152    /// @brief Set control flags.
153    void setFlags(unsigned flags) { Flags = flags; }
154
155    /// This method is the main interface to the linker. It can be used to
156    /// link a set of linkage items into a module. A linkage item is either a
157    /// file name with fully qualified path, or a library for which the Linker's
158    /// LibraryPath will be utilized to locate the library. The bool value in
159    /// the LinkItemKind should be set to true for libraries.  This function
160    /// allows linking to preserve the order of specification associated with
161    /// the command line, or for other purposes. Each item will be linked in
162    /// turn as it occurs in \p Items.
163    /// @returns true if an error occurred, false otherwise
164    /// @see LinkItemKind
165    /// @see getLastError
166    bool LinkInItems (
167      const ItemList& Items, ///< Set of libraries/files to link in
168      ItemList& NativeItems  ///< Output list of native files/libs
169    );
170
171    /// This function links the bitcode \p Files into the composite module.
172    /// Note that this does not do any linking of unresolved symbols. The \p
173    /// Files are all completely linked into \p HeadModule regardless of
174    /// unresolved symbols. This function just loads each bitcode file and
175    /// calls LinkInModule on them.
176    /// @returns true if an error occurs, false otherwise
177    /// @see getLastError
178    /// @brief Link in multiple files.
179    bool LinkInFiles (
180      const std::vector<sys::Path> & Files ///< Files to link in
181    );
182
183    /// This function links a single bitcode file, \p File, into the composite
184    /// module. Note that this does not attempt to resolve symbols. This method
185    /// just loads the bitcode file and calls LinkInModule on it. If an error
186    /// occurs, the Linker's error string is set.
187    /// @returns true if an error occurs, false otherwise
188    /// @see getLastError
189    /// @brief Link in a single file.
190    bool LinkInFile(
191      const sys::Path& File, ///< File to link in.
192      bool &is_native        ///< Indicates if the file is native object file
193    );
194
195    /// This function provides a way to selectively link in a set of modules,
196    /// found in libraries, based on the unresolved symbols in the composite
197    /// module. Each item in \p Libraries should be the base name of a library,
198    /// as if given with the -l option of a linker tool.  The Linker's LibPaths
199    /// are searched for the \p Libraries and any found will be linked in with
200    /// LinkInArchive.  If an error occurs, the Linker's error string is set.
201    /// @see LinkInArchive
202    /// @see getLastError
203    /// @returns true if an error occurs, false otherwise
204    /// @brief Link libraries into the module
205    bool LinkInLibraries (
206      const std::vector<std::string> & Libraries ///< Libraries to link in
207    );
208
209    /// This function provides a way to selectively link in a set of modules,
210    /// found in one library, based on the unresolved symbols in the composite
211    /// module.The \p Library should be the base name of a library, as if given
212    /// with the -l option of a linker tool. The Linker's LibPaths are searched
213    /// for the \p Library and if found, it will be linked in with via the
214    /// LinkInArchive method. If an error occurs, the Linker's error string is
215    /// set.
216    /// @see LinkInArchive
217    /// @see getLastError
218    /// @returns true if an error occurs, false otherwise
219    /// @brief Link one library into the module
220    bool LinkInLibrary (
221      StringRef Library, ///< The library to link in
222      bool& is_native    ///< Indicates if lib a native library
223    );
224
225    /// This function links one bitcode archive, \p Filename, into the module.
226    /// The archive is searched to resolve outstanding symbols. Any modules in
227    /// the archive that resolve outstanding symbols will be linked in. The
228    /// library is searched repeatedly until no more modules that resolve
229    /// symbols can be found. If an error occurs, the error string is  set.
230    /// To speed up this function, ensure the archive has been processed
231    /// llvm-ranlib or the S option was given to llvm-ar when the archive was
232    /// created. These tools add a symbol table to the archive which makes the
233    /// search for undefined symbols much faster.
234    /// @see getLastError
235    /// @returns true if an error occurs, otherwise false.
236    /// @brief Link in one archive.
237    bool LinkInArchive(
238      const sys::Path& Filename, ///< Filename of the archive to link
239      bool& is_native            ///<  Indicates if archive is a native archive
240    );
241
242    /// This method links the \p Src module into the Linker's Composite module
243    /// by calling LinkModules.  All the other LinkIn* methods eventually
244    /// result in calling this method to link a Module into the Linker's
245    /// composite.
246    /// @see LinkModules
247    /// @returns True if an error occurs, false otherwise.
248    /// @brief Link in a module.
249    bool LinkInModule(
250      Module* Src,              ///< Module linked into \p Dest
251      std::string* ErrorMsg = 0 /// Error/diagnostic string
252    ) {
253      return LinkModules(Composite, Src, Linker::DestroySource, ErrorMsg );
254    }
255
256    /// This is the heart of the linker. This method will take unconditional
257    /// control of the \p Src module and link it into the \p Dest module. The
258    /// \p Src module will be destructed or subsumed by this method. In either
259    /// case it is not usable by the caller after this method is invoked. Only
260    /// the \p Dest module will remain. The \p Src module is linked into the
261    /// Linker's composite module such that types, global variables, functions,
262    /// and etc. are matched and resolved.  If an error occurs, this function
263    /// returns true and ErrorMsg is set to a descriptive message about the
264    /// error.
265    /// @returns True if an error occurs, false otherwise.
266    /// @brief Generically link two modules together.
267    static bool LinkModules(Module* Dest, Module* Src, unsigned Mode,
268                            std::string* ErrorMsg);
269
270    /// This function looks through the Linker's LibPaths to find a library with
271    /// the name \p Filename. If the library cannot be found, the returned path
272    /// will be empty (i.e. sys::Path::isEmpty() will return true).
273    /// @returns A sys::Path to the found library
274    /// @brief Find a library from its short name.
275    sys::Path FindLib(StringRef Filename);
276
277  /// @}
278  /// @name Implementation
279  /// @{
280  private:
281    /// Read in and parse the bitcode file named by FN and return the
282    /// Module it contains (wrapped in an auto_ptr), or 0 if an error occurs.
283    std::auto_ptr<Module> LoadObject(const sys::Path& FN);
284
285    bool warning(StringRef message);
286    bool error(StringRef message);
287    void verbose(StringRef message);
288
289  /// @}
290  /// @name Data
291  /// @{
292  private:
293    LLVMContext& Context; ///< The context for global information
294    Module* Composite; ///< The composite module linked together
295    std::vector<sys::Path> LibPaths; ///< The library search paths
296    unsigned Flags;    ///< Flags to control optional behavior.
297    std::string Error; ///< Text of error that occurred.
298    std::string ProgramName; ///< Name of the program being linked
299  /// @}
300
301};
302
303} // End llvm namespace
304
305#endif
306