6b27a6ed72ccf2e86b24163c64ba6c506229bcbb
[oota-llvm.git] / tools / llvm-config-2 / llvm-config.cpp
1 //===-- llvm-config.cpp - LLVM project configuration utility --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tool encapsulates information about an LLVM project configuration for
11 // use by other project's build environments (to determine installed path,
12 // available features, required libraries, etc.).
13 //
14 // Note that although this tool *may* be used by some parts of LLVM's build
15 // itself (i.e., the Makefiles use it to compute required libraries when linking
16 // tools), this tool is primarily designed to support external projects.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <cstdlib>
31 #include <set>
32 #include <vector>
33
34 using namespace llvm;
35
36 // Include the build time variables we can report to the user. This is generated
37 // at build time from the BuildVariables.inc.in file by the build system.
38 #include "BuildVariables.inc"
39
40 // Include the component table. This creates an array of struct
41 // AvailableComponent entries, which record the component name, library name,
42 // and required components for all of the available libraries.
43 //
44 // Not all components define a library, we also use "library groups" as a way to
45 // create entries for pseudo groups like x86 or all-targets.
46 #include "LibraryDependencies.inc"
47
48 /// \brief Traverse a single component adding to the topological ordering in
49 /// \arg RequiredLibs.
50 ///
51 /// \param Name - The component to traverse.
52 /// \param ComponentMap - A prebuilt map of component names to descriptors.
53 /// \param VisitedComponents [in] [out] - The set of already visited components.
54 /// \param RequiredLibs [out] - The ordered list of required libraries.
55 static void VisitComponent(StringRef Name,
56                            const StringMap<AvailableComponent*> &ComponentMap,
57                            std::set<StringRef> &VisitedComponents,
58                            std::vector<StringRef> &RequiredLibs) {
59   // Add to the visited table.
60   if (!VisitedComponents.insert(Name).second) {
61     // We are done if the component has already been visited.
62     return;
63   }
64
65   // Otherwise, visit all the dependencies.
66   AvailableComponent *AC = ComponentMap.lookup(Name);
67   assert(AC && "Invalid component name!");
68
69   for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
70     VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
71                    RequiredLibs);
72   }
73
74   // Add to the required library list.
75   if (AC->Library)
76     RequiredLibs.push_back(AC->Library);
77 }
78
79 /// \brief Compute the list of required libraries for a given list of
80 /// components, in an order suitable for passing to a linker (that is, libraries
81 /// appear prior to their dependencies).
82 ///
83 /// \param Components - The names of the components to find libraries for.
84 /// \param RequiredLibs [out] - On return, the ordered list of libraries that
85 /// are required to link the given components.
86 void ComputeLibsForComponents(const std::vector<StringRef> &Components,
87                               std::vector<StringRef> &RequiredLibs) {
88   std::set<StringRef> VisitedComponents;
89   std::vector<StringRef> ToVisit = Components;
90
91   // Build a map of component names to information.
92   StringMap<AvailableComponent*> ComponentMap;
93   for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
94     AvailableComponent *AC = &AvailableComponents[i];
95     ComponentMap[AC->Name] = AC;
96   }
97
98   // Visit the components.
99   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
100     // Validate that the user supplied a valid component name.
101     if (!ComponentMap.count(Components[i])) {
102       llvm::errs() << "llvm-config: unknown component name: " << Components[i]
103                    << "\n";
104       exit(1);
105     }
106
107     VisitComponent(Components[i], ComponentMap, VisitedComponents,
108                    RequiredLibs);
109   }
110
111   // The list is now ordered with leafs first, we want the libraries to printed
112   // in the reverse order of dependency.
113   std::reverse(RequiredLibs.begin(), RequiredLibs.end());
114 }
115
116 /* *** */
117
118 void usage() {
119   errs() << "\
120 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
121 \n\
122 Get various configuration information needed to compile programs which use\n\
123 LLVM.  Typically called from 'configure' scripts.  Examples:\n\
124   llvm-config --cxxflags\n\
125   llvm-config --ldflags\n\
126   llvm-config --libs engine bcreader scalaropts\n\
127 \n\
128 Options:\n\
129   --version         Print LLVM version.\n\
130   --prefix          Print the installation prefix.\n\
131   --src-root        Print the source root LLVM was built from.\n\
132   --obj-root        Print the object root used to build LLVM.\n\
133   --bindir          Directory containing LLVM executables.\n\
134   --includedir      Directory containing LLVM headers.\n\
135   --libdir          Directory containing LLVM libraries.\n\
136   --cppflags        C preprocessor flags for files that include LLVM headers.\n\
137   --cflags          C compiler flags for files that include LLVM headers.\n\
138   --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
139   --ldflags         Print Linker flags.\n\
140   --libs            Libraries needed to link against LLVM components.\n\
141   --libnames        Bare library names for in-tree builds.\n\
142   --libfiles        Fully qualified library filenames for makefile depends.\n\
143   --components      List of all possible components.\n\
144   --targets-built   List of all targets currently built.\n\
145   --host-target     Target triple used to configure LLVM.\n\
146   --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
147 Typical components:\n\
148   all               All LLVM libraries (default).\n\
149   backend           Either a native backend or the C backend.\n\
150   engine            Either a native JIT or a bitcode interpreter.\n";
151   exit(1);
152 }
153
154 /// \brief Compute the path to the main executable.
155 llvm::sys::Path GetExecutablePath(const char *Argv0) {
156   // This just needs to be some symbol in the binary; C++ doesn't
157   // allow taking the address of ::main however.
158   void *P = (void*) (intptr_t) GetExecutablePath;
159   return llvm::sys::Path::GetMainExecutable(Argv0, P);
160 }
161
162 int main(int argc, char **argv) {
163   std::vector<StringRef> Components;
164   bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
165   bool HasAnyOption = false;
166
167   // llvm-config is designed to support being run both from a development tree
168   // and from an installed path. We try and auto-detect which case we are in so
169   // that we can report the correct information when run from a development
170   // tree.
171   bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;
172   llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());
173   std::string CurrentExecPrefix;
174
175   // Create an absolute path, and pop up one directory (we expect to be inside a
176   // bin dir).
177   sys::fs::make_absolute(CurrentPath);
178   CurrentExecPrefix = sys::path::parent_path(
179     sys::path::parent_path(CurrentPath)).str();
180
181   // Check to see if we are inside a development tree by comparing to possible
182   // locations (prefix style or CMake style). This could be wrong in the face of
183   // symbolic links, but is good enough.
184   if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/" + LLVM_BUILDMODE) {
185     IsInDevelopmentTree = true;
186     DevelopmentTreeLayoutIsCMakeStyle = false;
187   } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/bin") {
188     IsInDevelopmentTree = true;
189     DevelopmentTreeLayoutIsCMakeStyle = true;
190   } else {
191     IsInDevelopmentTree = false;
192   }
193
194   // Compute various directory locations based on the derived location
195   // information.
196   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
197   std::string ActiveIncludeOption;
198   if (IsInDevelopmentTree) {
199     ActivePrefix = CurrentExecPrefix;
200
201     // CMake organizes the products differently than a normal prefix style
202     // layout.
203     if (DevelopmentTreeLayoutIsCMakeStyle) {
204       ActiveIncludeDir = std::string(LLVM_OBJ_ROOT) + "/include";
205       ActiveBinDir = std::string(LLVM_OBJ_ROOT) + "/bin/" + LLVM_BUILDMODE;
206       ActiveLibDir = std::string(LLVM_OBJ_ROOT) + "/lib/" + LLVM_BUILDMODE;
207     } else {
208         ActiveIncludeDir = std::string(LLVM_OBJ_ROOT) + "/include";
209       ActiveBinDir = std::string(LLVM_OBJ_ROOT) + "/" + LLVM_BUILDMODE + "/bin";
210       ActiveLibDir = std::string(LLVM_OBJ_ROOT) + "/" + LLVM_BUILDMODE + "/lib";
211     }
212
213     // We need to include files from both the source and object trees.
214     ActiveIncludeOption = ("-I" + ActiveIncludeDir + " " +
215                            "-I" + LLVM_OBJ_ROOT + "/include");
216   } else {
217     ActivePrefix = CurrentExecPrefix;
218     ActiveIncludeDir = ActivePrefix + "/include";
219     ActiveBinDir = ActivePrefix + "/bin";
220     ActiveLibDir = ActivePrefix + "/lib";
221     ActiveIncludeOption = "-I" + ActiveIncludeDir;
222   }
223
224   raw_ostream &OS = outs();
225   for (int i = 1; i != argc; ++i) {
226     StringRef Arg = argv[i];
227
228     if (Arg.startswith("-")) {
229       HasAnyOption = true;
230       if (Arg == "--version") {
231         OS << PACKAGE_VERSION << '\n';
232       } else if (Arg == "--prefix") {
233         OS << ActivePrefix << '\n';
234       } else if (Arg == "--bindir") {
235         OS << ActiveBinDir << '\n';
236       } else if (Arg == "--includedir") {
237         OS << ActiveIncludeDir << '\n';
238       } else if (Arg == "--libdir") {
239         OS << ActiveLibDir << '\n';
240       } else if (Arg == "--cppflags") {
241         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
242       } else if (Arg == "--cflags") {
243         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
244       } else if (Arg == "--cxxflags") {
245         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
246       } else if (Arg == "--ldflags") {
247         OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS
248            << ' ' << LLVM_SYSTEM_LIBS << '\n';
249       } else if (Arg == "--libs") {
250         PrintLibs = true;
251       } else if (Arg == "--libnames") {
252         PrintLibNames = true;
253       } else if (Arg == "--libfiles") {
254         PrintLibFiles = true;
255       } else if (Arg == "--components") {
256         for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
257           OS << ' ';
258           OS << AvailableComponents[j].Name;
259         }
260         OS << '\n';
261       } else if (Arg == "--targets-built") {
262         bool First = true;
263         for (TargetRegistry::iterator I = TargetRegistry::begin(),
264                E = TargetRegistry::end(); I != E; First = false, ++I) {
265           if (!First)
266             OS << ' ';
267           OS << I->getName();
268         }
269         OS << '\n';
270       } else if (Arg == "--host-target") {
271         OS << LLVM_DEFAULT_TARGET_TRIPLE << '\n';
272       } else if (Arg == "--build-mode") {
273         OS << LLVM_BUILDMODE << '\n';
274       } else if (Arg == "--obj-root") {
275         OS << LLVM_OBJ_ROOT << '\n';
276       } else if (Arg == "--src-root") {
277         OS << LLVM_SRC_ROOT << '\n';
278       } else {
279         usage();
280       }
281     } else {
282       Components.push_back(Arg);
283     }
284   }
285
286   if (!HasAnyOption)
287     usage();
288
289   if (PrintLibs || PrintLibNames || PrintLibFiles) {
290     // Construct the list of all the required libraries.
291     std::vector<StringRef> RequiredLibs;
292     ComputeLibsForComponents(Components, RequiredLibs);
293
294     for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
295       StringRef Lib = RequiredLibs[i];
296       if (i)
297         OS << ' ';
298
299       if (PrintLibNames) {
300         OS << Lib;
301       } else if (PrintLibFiles) {
302         OS << ActiveLibDir << '/' << Lib;
303       } else if (PrintLibs) {
304         // If this is a typical library name, include it using -l.
305         if (Lib.startswith("lib") && Lib.endswith(".a")) {
306           OS << "-l" << Lib.slice(3, Lib.size()-2);
307           continue;
308         }
309
310         // Otherwise, print the full path.
311         OS << ActiveLibDir << '/' << Lib;
312       }
313     }
314     OS << '\n';
315   } else if (!Components.empty()) {
316     errs() << "llvm-config: error: components given, but unused\n\n";
317     usage();
318   }
319
320   return 0;
321 }