xref: /openbsd-src/gnu/llvm/llvm/tools/llvm-config/llvm-config.cpp (revision a96b36398fcfb4953e8190127da8bf074c7552f1)
1 //===-- llvm-config.cpp - LLVM project configuration utility --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tool encapsulates information about an LLVM project configuration for
10 // use by other project's build environments (to determine installed path,
11 // available features, required libraries, etc.).
12 //
13 // Note that although this tool *may* be used by some parts of LLVM's build
14 // itself (i.e., the Makefiles use it to compute required libraries when linking
15 // tools), this tool is primarily designed to support external projects.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/WithColor.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <cstdlib>
31 #include <set>
32 #include <unordered_set>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 // Include the build time variables we can report to the user. This is generated
38 // at build time from the BuildVariables.inc.in file by the build system.
39 #include "BuildVariables.inc"
40 
41 // Include the component table. This creates an array of struct
42 // AvailableComponent entries, which record the component name, library name,
43 // and required components for all of the available libraries.
44 //
45 // Not all components define a library, we also use "library groups" as a way to
46 // create entries for pseudo groups like x86 or all-targets.
47 #include "LibraryDependencies.inc"
48 
49 // Built-in extensions also register their dependencies, but in a separate file,
50 // later in the process.
51 #include "ExtensionDependencies.inc"
52 
53 // LinkMode determines what libraries and flags are returned by llvm-config.
54 enum LinkMode {
55   // LinkModeAuto will link with the default link mode for the installation,
56   // which is dependent on the value of LLVM_LINK_LLVM_DYLIB, and fall back
57   // to the alternative if the required libraries are not available.
58   LinkModeAuto = 0,
59 
60   // LinkModeShared will link with the dynamic component libraries if they
61   // exist, and return an error otherwise.
62   LinkModeShared = 1,
63 
64   // LinkModeStatic will link with the static component libraries if they
65   // exist, and return an error otherwise.
66   LinkModeStatic = 2,
67 };
68 
69 /// Traverse a single component adding to the topological ordering in
70 /// \arg RequiredLibs.
71 ///
72 /// \param Name - The component to traverse.
73 /// \param ComponentMap - A prebuilt map of component names to descriptors.
74 /// \param VisitedComponents [in] [out] - The set of already visited components.
75 /// \param RequiredLibs [out] - The ordered list of required
76 /// libraries.
77 /// \param GetComponentNames - Get the component names instead of the
78 /// library name.
VisitComponent(const std::string & Name,const StringMap<AvailableComponent * > & ComponentMap,std::set<AvailableComponent * > & VisitedComponents,std::vector<std::string> & RequiredLibs,bool IncludeNonInstalled,bool GetComponentNames,const std::function<std::string (const StringRef &)> * GetComponentLibraryPath,std::vector<std::string> * Missing,const std::string & DirSep)79 static void VisitComponent(const std::string &Name,
80                            const StringMap<AvailableComponent *> &ComponentMap,
81                            std::set<AvailableComponent *> &VisitedComponents,
82                            std::vector<std::string> &RequiredLibs,
83                            bool IncludeNonInstalled, bool GetComponentNames,
84                            const std::function<std::string(const StringRef &)>
85                                *GetComponentLibraryPath,
86                            std::vector<std::string> *Missing,
87                            const std::string &DirSep) {
88   // Lookup the component.
89   AvailableComponent *AC = ComponentMap.lookup(Name);
90   if (!AC) {
91     errs() << "Can't find component: '" << Name << "' in the map. Available components are: ";
92     for (const auto &Component : ComponentMap) {
93       errs() << "'" << Component.first() << "' ";
94     }
95     errs() << "\n";
96     report_fatal_error("abort");
97   }
98   assert(AC && "Invalid component name!");
99 
100   // Add to the visited table.
101   if (!VisitedComponents.insert(AC).second) {
102     // We are done if the component has already been visited.
103     return;
104   }
105 
106   // Only include non-installed components if requested.
107   if (!AC->IsInstalled && !IncludeNonInstalled)
108     return;
109 
110   // Otherwise, visit all the dependencies.
111   for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
112     VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
113                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
114                    GetComponentLibraryPath, Missing, DirSep);
115   }
116 
117   // Special handling for the special 'extensions' component. Its content is
118   // not populated by llvm-build, but later in the process and loaded from
119   // ExtensionDependencies.inc.
120   if (Name == "extensions") {
121     for (auto const &AvailableExtension : AvailableExtensions) {
122       for (const char *const *Iter = &AvailableExtension.RequiredLibraries[0];
123            *Iter; ++Iter) {
124         AvailableComponent *AC = ComponentMap.lookup(*Iter);
125         if (!AC) {
126           RequiredLibs.push_back(*Iter);
127         } else {
128           VisitComponent(*Iter, ComponentMap, VisitedComponents, RequiredLibs,
129                          IncludeNonInstalled, GetComponentNames,
130                          GetComponentLibraryPath, Missing, DirSep);
131         }
132       }
133     }
134   }
135 
136   if (GetComponentNames) {
137     RequiredLibs.push_back(Name);
138     return;
139   }
140 
141   // Add to the required library list.
142   if (AC->Library) {
143     if (Missing && GetComponentLibraryPath) {
144       std::string path = (*GetComponentLibraryPath)(AC->Library);
145       if (DirSep == "\\") {
146         std::replace(path.begin(), path.end(), '/', '\\');
147       }
148       if (!sys::fs::exists(path))
149         Missing->push_back(path);
150     }
151     RequiredLibs.push_back(AC->Library);
152   }
153 }
154 
155 /// Compute the list of required libraries for a given list of
156 /// components, in an order suitable for passing to a linker (that is, libraries
157 /// appear prior to their dependencies).
158 ///
159 /// \param Components - The names of the components to find libraries for.
160 /// \param IncludeNonInstalled - Whether non-installed components should be
161 /// reported.
162 /// \param GetComponentNames - True if one would prefer the component names.
ComputeLibsForComponents(const std::vector<StringRef> & Components,bool IncludeNonInstalled,bool GetComponentNames,const std::function<std::string (const StringRef &)> * GetComponentLibraryPath,std::vector<std::string> * Missing,const std::string & DirSep)163 static std::vector<std::string> ComputeLibsForComponents(
164     const std::vector<StringRef> &Components, bool IncludeNonInstalled,
165     bool GetComponentNames, const std::function<std::string(const StringRef &)>
166                                 *GetComponentLibraryPath,
167     std::vector<std::string> *Missing, const std::string &DirSep) {
168   std::vector<std::string> RequiredLibs;
169   std::set<AvailableComponent *> VisitedComponents;
170 
171   // Build a map of component names to information.
172   StringMap<AvailableComponent *> ComponentMap;
173   for (auto &AC : AvailableComponents)
174     ComponentMap[AC.Name] = &AC;
175 
176   // Visit the components.
177   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
178     // Users are allowed to provide mixed case component names.
179     std::string ComponentLower = Components[i].lower();
180 
181     // Validate that the user supplied a valid component name.
182     if (!ComponentMap.count(ComponentLower)) {
183       llvm::errs() << "llvm-config: unknown component name: " << Components[i]
184                    << "\n";
185       exit(1);
186     }
187 
188     VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
189                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
190                    GetComponentLibraryPath, Missing, DirSep);
191   }
192 
193   // The list is now ordered with leafs first, we want the libraries to printed
194   // in the reverse order of dependency.
195   std::reverse(RequiredLibs.begin(), RequiredLibs.end());
196 
197   return RequiredLibs;
198 }
199 
200 /* *** */
201 
usage(bool ExitWithFailure=true)202 static void usage(bool ExitWithFailure = true) {
203   errs() << "\
204 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
205 \n\
206 Get various configuration information needed to compile programs which use\n\
207 LLVM.  Typically called from 'configure' scripts.  Examples:\n\
208   llvm-config --cxxflags\n\
209   llvm-config --ldflags\n\
210   llvm-config --libs engine bcreader scalaropts\n\
211 \n\
212 Options:\n\
213   --assertion-mode  Print assertion mode of LLVM tree (ON or OFF).\n\
214   --bindir          Directory containing LLVM executables.\n\
215   --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
216   --build-system    Print the build system used to build LLVM (e.g. `cmake` or `gn`).\n\
217   --cflags          C compiler flags for files that include LLVM headers.\n\
218   --cmakedir        Directory containing LLVM CMake modules.\n\
219   --components      List of all possible components.\n\
220   --cppflags        C preprocessor flags for files that include LLVM headers.\n\
221   --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
222   --has-rtti        Print whether or not LLVM was built with rtti (YES or NO).\n\
223   --help            Print a summary of llvm-config arguments.\n\
224   --host-target     Target triple used to configure LLVM.\n\
225   --ignore-libllvm  Ignore libLLVM and link component libraries instead.\n\
226   --includedir      Directory containing LLVM headers.\n\
227   --ldflags         Print Linker flags.\n\
228   --libdir          Directory containing LLVM libraries.\n\
229   --libfiles        Fully qualified library filenames for makefile depends.\n\
230   --libnames        Bare library names for in-tree builds.\n\
231   --libs            Libraries needed to link against LLVM components.\n\
232   --link-shared     Link the components as shared libraries.\n\
233   --link-static     Link the component libraries statically.\n\
234   --obj-root        Print the object root used to build LLVM.\n\
235   --prefix          Print the installation prefix.\n\
236   --shared-mode     Print how the provided components can be collectively linked (`shared` or `static`).\n\
237   --system-libs     System Libraries needed to link against LLVM components.\n\
238   --targets-built   List of all targets currently built.\n\
239   --version         Print LLVM version.\n\
240 Typical components:\n\
241   all               All LLVM libraries (default).\n\
242   engine            Either a native JIT or a bitcode interpreter.\n";
243   if (ExitWithFailure)
244     exit(1);
245 }
246 
247 /// Compute the path to the main executable.
GetExecutablePath(const char * Argv0)248 std::string GetExecutablePath(const char *Argv0) {
249   // This just needs to be some symbol in the binary; C++ doesn't
250   // allow taking the address of ::main however.
251   void *P = (void *)(intptr_t)GetExecutablePath;
252   return llvm::sys::fs::getMainExecutable(Argv0, P);
253 }
254 
255 /// Expand the semi-colon delimited LLVM_DYLIB_COMPONENTS into
256 /// the full list of components.
GetAllDyLibComponents(const bool IsInDevelopmentTree,const bool GetComponentNames,const std::string & DirSep)257 std::vector<std::string> GetAllDyLibComponents(const bool IsInDevelopmentTree,
258                                                const bool GetComponentNames,
259                                                const std::string &DirSep) {
260   std::vector<StringRef> DyLibComponents;
261 
262   StringRef DyLibComponentsStr(LLVM_DYLIB_COMPONENTS);
263   size_t Offset = 0;
264   while (true) {
265     const size_t NextOffset = DyLibComponentsStr.find(';', Offset);
266     DyLibComponents.push_back(DyLibComponentsStr.substr(Offset, NextOffset-Offset));
267     if (NextOffset == std::string::npos) {
268       break;
269     }
270     Offset = NextOffset + 1;
271   }
272 
273   assert(!DyLibComponents.empty());
274 
275   return ComputeLibsForComponents(DyLibComponents,
276                                   /*IncludeNonInstalled=*/IsInDevelopmentTree,
277                                   GetComponentNames, nullptr, nullptr, DirSep);
278 }
279 
main(int argc,char ** argv)280 int main(int argc, char **argv) {
281   std::vector<StringRef> Components;
282   bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
283   bool PrintSystemLibs = false, PrintSharedMode = false;
284   bool HasAnyOption = false;
285 
286   // llvm-config is designed to support being run both from a development tree
287   // and from an installed path. We try and auto-detect which case we are in so
288   // that we can report the correct information when run from a development
289   // tree.
290   bool IsInDevelopmentTree;
291   enum { CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
292   llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
293   std::string CurrentExecPrefix;
294   std::string ActiveObjRoot;
295 
296   // If CMAKE_CFG_INTDIR is given, honor it as build mode.
297   char const *build_mode = LLVM_BUILDMODE;
298 #if defined(CMAKE_CFG_INTDIR)
299   if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
300     build_mode = CMAKE_CFG_INTDIR;
301 #endif
302 
303   // Create an absolute path, and pop up one directory (we expect to be inside a
304   // bin dir).
305   sys::fs::make_absolute(CurrentPath);
306   CurrentExecPrefix =
307       sys::path::parent_path(sys::path::parent_path(CurrentPath)).str();
308 
309   // Check to see if we are inside a development tree by comparing to possible
310   // locations (prefix style or CMake style).
311   if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
312     IsInDevelopmentTree = true;
313     DevelopmentTreeLayout = CMakeStyle;
314     ActiveObjRoot = LLVM_OBJ_ROOT;
315   } else if (sys::fs::equivalent(sys::path::parent_path(CurrentExecPrefix),
316                                  LLVM_OBJ_ROOT)) {
317     IsInDevelopmentTree = true;
318     DevelopmentTreeLayout = CMakeBuildModeStyle;
319     ActiveObjRoot = LLVM_OBJ_ROOT;
320   } else {
321     IsInDevelopmentTree = false;
322     DevelopmentTreeLayout = CMakeStyle; // Initialized to avoid warnings.
323   }
324 
325   // Compute various directory locations based on the derived location
326   // information.
327   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir,
328               ActiveCMakeDir;
329   std::string ActiveIncludeOption;
330   if (IsInDevelopmentTree) {
331     ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
332     ActivePrefix = CurrentExecPrefix;
333 
334     // CMake organizes the products differently than a normal prefix style
335     // layout.
336     switch (DevelopmentTreeLayout) {
337     case CMakeStyle:
338       ActiveBinDir = ActiveObjRoot + "/bin";
339       ActiveLibDir = ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX;
340       ActiveCMakeDir = ActiveLibDir + "/cmake/llvm";
341       break;
342     case CMakeBuildModeStyle:
343       // FIXME: Should we consider the build-mode-specific path as the prefix?
344       ActivePrefix = ActiveObjRoot;
345       ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
346       ActiveLibDir =
347           ActiveObjRoot + "/" + build_mode + "/lib" + LLVM_LIBDIR_SUFFIX;
348       // The CMake directory isn't separated by build mode.
349       ActiveCMakeDir =
350           ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX + "/cmake/llvm";
351       break;
352     }
353 
354     // We need to include files from both the source and object trees.
355     ActiveIncludeOption =
356         ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
357   } else {
358     ActivePrefix = CurrentExecPrefix;
359     {
360       SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR);
361       sys::fs::make_absolute(ActivePrefix, Path);
362       ActiveIncludeDir = std::string(Path.str());
363     }
364     {
365       SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR);
366       sys::fs::make_absolute(ActivePrefix, Path);
367       ActiveBinDir = std::string(Path.str());
368     }
369     ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
370     {
371       SmallString<256> Path(LLVM_INSTALL_PACKAGE_DIR);
372       sys::fs::make_absolute(ActivePrefix, Path);
373       ActiveCMakeDir = std::string(Path.str());
374     }
375     ActiveIncludeOption = "-I" + ActiveIncludeDir;
376   }
377 
378   /// We only use `shared library` mode in cases where the static library form
379   /// of the components provided are not available; note however that this is
380   /// skipped if we're run from within the build dir. However, once installed,
381   /// we still need to provide correct output when the static archives are
382   /// removed or, as in the case of CMake's `BUILD_SHARED_LIBS`, never present
383   /// in the first place. This can't be done at configure/build time.
384 
385   StringRef SharedExt, SharedVersionedExt, SharedDir, SharedPrefix, StaticExt,
386       StaticPrefix, StaticDir = "lib";
387   std::string DirSep = "/";
388   const Triple HostTriple(Triple::normalize(LLVM_HOST_TRIPLE));
389   if (HostTriple.isOSWindows()) {
390     SharedExt = "dll";
391     SharedVersionedExt = LLVM_DYLIB_VERSION ".dll";
392     if (HostTriple.isOSCygMing()) {
393       SharedPrefix = "lib";
394       StaticExt = "a";
395       StaticPrefix = "lib";
396     } else {
397       StaticExt = "lib";
398       DirSep = "\\";
399       std::replace(ActiveObjRoot.begin(), ActiveObjRoot.end(), '/', '\\');
400       std::replace(ActivePrefix.begin(), ActivePrefix.end(), '/', '\\');
401       std::replace(ActiveBinDir.begin(), ActiveBinDir.end(), '/', '\\');
402       std::replace(ActiveLibDir.begin(), ActiveLibDir.end(), '/', '\\');
403       std::replace(ActiveCMakeDir.begin(), ActiveCMakeDir.end(), '/', '\\');
404       std::replace(ActiveIncludeOption.begin(), ActiveIncludeOption.end(), '/',
405                    '\\');
406     }
407     SharedDir = ActiveBinDir;
408     StaticDir = ActiveLibDir;
409   } else if (HostTriple.isOSDarwin()) {
410     SharedExt = "dylib";
411     SharedVersionedExt = LLVM_DYLIB_VERSION ".dylib";
412     StaticExt = "a";
413     StaticDir = SharedDir = ActiveLibDir;
414     StaticPrefix = SharedPrefix = "lib";
415   } else if (HostTriple.isOSOpenBSD()) {
416     SharedExt = "so";
417     SharedVersionedExt = ".so" ;
418     StaticExt = "a";
419     StaticDir = SharedDir = ActiveLibDir;
420     StaticPrefix = SharedPrefix = "lib";
421   } else {
422     // default to the unix values:
423     SharedExt = "so";
424     SharedVersionedExt = LLVM_DYLIB_VERSION ".so";
425     StaticExt = "a";
426     StaticDir = SharedDir = ActiveLibDir;
427     StaticPrefix = SharedPrefix = "lib";
428   }
429 
430   const bool BuiltDyLib = !!LLVM_ENABLE_DYLIB;
431 
432   /// CMake style shared libs, ie each component is in a shared library.
433   const bool BuiltSharedLibs = !!LLVM_ENABLE_SHARED;
434 
435   bool DyLibExists = false;
436   const std::string DyLibName =
437       (SharedPrefix + "LLVM" + SharedVersionedExt).str();
438 
439   // If LLVM_LINK_DYLIB is ON, the single shared library will be returned
440   // for "--libs", etc, if they exist. This behaviour can be overridden with
441   // --link-static or --link-shared.
442   bool LinkDyLib = !!LLVM_LINK_DYLIB;
443 
444   if (BuiltDyLib) {
445     std::string path((SharedDir + DirSep + DyLibName).str());
446     if (DirSep == "\\") {
447       std::replace(path.begin(), path.end(), '/', '\\');
448     }
449     // path does not include major.minor
450     if (HostTriple.isOSOpenBSD()) {
451       DyLibExists = true;
452     } else {
453       DyLibExists = sys::fs::exists(path);
454     }
455     if (!DyLibExists) {
456       // The shared library does not exist: don't error unless the user
457       // explicitly passes --link-shared.
458       LinkDyLib = false;
459     }
460   }
461   LinkMode LinkMode =
462       (LinkDyLib || BuiltSharedLibs) ? LinkModeShared : LinkModeAuto;
463 
464   /// Get the component's library name without the lib prefix and the
465   /// extension. Returns true if Lib is in a recognized format.
466   auto GetComponentLibraryNameSlice = [&](const StringRef &Lib,
467                                           StringRef &Out) {
468     if (Lib.startswith("lib")) {
469       unsigned FromEnd;
470       if (Lib.endswith(StaticExt)) {
471         FromEnd = StaticExt.size() + 1;
472       } else if (Lib.endswith(SharedExt)) {
473         FromEnd = SharedExt.size() + 1;
474       } else {
475         FromEnd = 0;
476       }
477 
478       if (FromEnd != 0) {
479         Out = Lib.slice(3, Lib.size() - FromEnd);
480         return true;
481       }
482     }
483 
484     return false;
485   };
486   /// Maps Unixizms to the host platform.
487   auto GetComponentLibraryFileName = [&](const StringRef &Lib,
488                                          const bool Shared) {
489     std::string LibFileName;
490     if (Shared) {
491       if (Lib == DyLibName) {
492         // Treat the DyLibName specially. It is not a component library and
493         // already has the necessary prefix and suffix (e.g. `.so`) added so
494         // just return it unmodified.
495         assert(Lib.endswith(SharedExt) && "DyLib is missing suffix");
496         LibFileName = std::string(Lib);
497       } else {
498         LibFileName = (SharedPrefix + Lib + "." + SharedExt).str();
499       }
500     } else {
501       // default to static
502       LibFileName = (StaticPrefix + Lib + "." + StaticExt).str();
503     }
504 
505     return LibFileName;
506   };
507   /// Get the full path for a possibly shared component library.
508   auto GetComponentLibraryPath = [&](const StringRef &Name, const bool Shared) {
509     auto LibFileName = GetComponentLibraryFileName(Name, Shared);
510     if (Shared) {
511       return (SharedDir + DirSep + LibFileName).str();
512     } else {
513       return (StaticDir + DirSep + LibFileName).str();
514     }
515   };
516 
517   raw_ostream &OS = outs();
518   for (int i = 1; i != argc; ++i) {
519     StringRef Arg = argv[i];
520 
521     if (Arg.startswith("-")) {
522       HasAnyOption = true;
523       if (Arg == "--version") {
524         OS << PACKAGE_VERSION << '\n';
525       } else if (Arg == "--prefix") {
526         OS << ActivePrefix << '\n';
527       } else if (Arg == "--bindir") {
528         OS << ActiveBinDir << '\n';
529       } else if (Arg == "--includedir") {
530         OS << ActiveIncludeDir << '\n';
531       } else if (Arg == "--libdir") {
532         OS << ActiveLibDir << '\n';
533       } else if (Arg == "--cmakedir") {
534         OS << ActiveCMakeDir << '\n';
535       } else if (Arg == "--cppflags") {
536         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
537       } else if (Arg == "--cflags") {
538         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
539       } else if (Arg == "--cxxflags") {
540         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
541       } else if (Arg == "--ldflags") {
542         OS << ((HostTriple.isWindowsMSVCEnvironment()) ? "-LIBPATH:" : "-L")
543            << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
544       } else if (Arg == "--system-libs") {
545         PrintSystemLibs = true;
546       } else if (Arg == "--libs") {
547         PrintLibs = true;
548       } else if (Arg == "--libnames") {
549         PrintLibNames = true;
550       } else if (Arg == "--libfiles") {
551         PrintLibFiles = true;
552       } else if (Arg == "--components") {
553         /// If there are missing static archives and a dylib was
554         /// built, print LLVM_DYLIB_COMPONENTS instead of everything
555         /// in the manifest.
556         std::vector<std::string> Components;
557         for (const auto &AC : AvailableComponents) {
558           // Only include non-installed components when in a development tree.
559           if (!AC.IsInstalled && !IsInDevelopmentTree)
560             continue;
561 
562           Components.push_back(AC.Name);
563           if (AC.Library && !IsInDevelopmentTree) {
564             std::string path(GetComponentLibraryPath(AC.Library, false));
565             if (DirSep == "\\") {
566               std::replace(path.begin(), path.end(), '/', '\\');
567             }
568             if (DyLibExists && !sys::fs::exists(path)) {
569               Components =
570                   GetAllDyLibComponents(IsInDevelopmentTree, true, DirSep);
571               llvm::sort(Components);
572               break;
573             }
574           }
575         }
576 
577         for (unsigned I = 0; I < Components.size(); ++I) {
578           if (I) {
579             OS << ' ';
580           }
581 
582           OS << Components[I];
583         }
584         OS << '\n';
585       } else if (Arg == "--targets-built") {
586         OS << LLVM_TARGETS_BUILT << '\n';
587       } else if (Arg == "--host-target") {
588         OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
589       } else if (Arg == "--build-mode") {
590         OS << build_mode << '\n';
591       } else if (Arg == "--assertion-mode") {
592 #if defined(NDEBUG)
593         OS << "OFF\n";
594 #else
595         OS << "ON\n";
596 #endif
597       } else if (Arg == "--build-system") {
598         OS << LLVM_BUILD_SYSTEM << '\n';
599       } else if (Arg == "--has-rtti") {
600         OS << (LLVM_HAS_RTTI ? "YES" : "NO") << '\n';
601       } else if (Arg == "--shared-mode") {
602         PrintSharedMode = true;
603       } else if (Arg == "--obj-root") {
604         OS << ActivePrefix << '\n';
605       } else if (Arg == "--ignore-libllvm") {
606         LinkDyLib = false;
607         LinkMode = BuiltSharedLibs ? LinkModeShared : LinkModeAuto;
608       } else if (Arg == "--link-shared") {
609         LinkMode = LinkModeShared;
610       } else if (Arg == "--link-static") {
611         LinkMode = LinkModeStatic;
612       } else if (Arg == "--help") {
613         usage(false);
614       } else {
615         usage();
616       }
617     } else {
618       Components.push_back(Arg);
619     }
620   }
621 
622   if (!HasAnyOption)
623     usage();
624 
625   if (LinkMode == LinkModeShared && !DyLibExists && !BuiltSharedLibs) {
626     WithColor::error(errs(), "llvm-config") << DyLibName << " is missing\n";
627     return 1;
628   }
629 
630   if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs ||
631       PrintSharedMode) {
632 
633     if (PrintSharedMode && BuiltSharedLibs) {
634       OS << "shared\n";
635       return 0;
636     }
637 
638     // If no components were specified, default to "all".
639     if (Components.empty())
640       Components.push_back("all");
641 
642     // Construct the list of all the required libraries.
643     std::function<std::string(const StringRef &)>
644         GetComponentLibraryPathFunction = [&](const StringRef &Name) {
645           return GetComponentLibraryPath(Name, LinkMode == LinkModeShared);
646         };
647     std::vector<std::string> MissingLibs;
648     std::vector<std::string> RequiredLibs = ComputeLibsForComponents(
649         Components,
650         /*IncludeNonInstalled=*/IsInDevelopmentTree, false,
651         &GetComponentLibraryPathFunction, &MissingLibs, DirSep);
652     if (!MissingLibs.empty()) {
653       switch (LinkMode) {
654       case LinkModeShared:
655         if (LinkDyLib && !BuiltSharedLibs)
656           break;
657         // Using component shared libraries.
658         for (auto &Lib : MissingLibs)
659           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
660         return 1;
661       case LinkModeAuto:
662         if (DyLibExists) {
663           LinkMode = LinkModeShared;
664           break;
665         }
666         WithColor::error(errs(), "llvm-config")
667             << "component libraries and shared library\n\n";
668         [[fallthrough]];
669       case LinkModeStatic:
670         for (auto &Lib : MissingLibs)
671           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
672         return 1;
673       }
674     } else if (LinkMode == LinkModeAuto) {
675       LinkMode = LinkModeStatic;
676     }
677 
678     if (PrintSharedMode) {
679       std::unordered_set<std::string> FullDyLibComponents;
680       std::vector<std::string> DyLibComponents =
681           GetAllDyLibComponents(IsInDevelopmentTree, false, DirSep);
682 
683       for (auto &Component : DyLibComponents) {
684         FullDyLibComponents.insert(Component);
685       }
686       DyLibComponents.clear();
687 
688       for (auto &Lib : RequiredLibs) {
689         if (!FullDyLibComponents.count(Lib)) {
690           OS << "static\n";
691           return 0;
692         }
693       }
694       FullDyLibComponents.clear();
695 
696       if (LinkMode == LinkModeShared) {
697         OS << "shared\n";
698         return 0;
699       } else {
700         OS << "static\n";
701         return 0;
702       }
703     }
704 
705     if (PrintLibs || PrintLibNames || PrintLibFiles) {
706 
707       auto PrintForLib = [&](const StringRef &Lib) {
708         const bool Shared = LinkMode == LinkModeShared;
709         if (PrintLibNames) {
710           OS << GetComponentLibraryFileName(Lib, Shared);
711         } else if (PrintLibFiles) {
712           OS << GetComponentLibraryPath(Lib, Shared);
713         } else if (PrintLibs) {
714           // On Windows, output full path to library without parameters.
715           // Elsewhere, if this is a typical library name, include it using -l.
716           if (HostTriple.isWindowsMSVCEnvironment()) {
717             OS << GetComponentLibraryPath(Lib, Shared);
718           } else {
719             StringRef LibName;
720             if (GetComponentLibraryNameSlice(Lib, LibName)) {
721               // Extract library name (remove prefix and suffix).
722               OS << "-l" << LibName;
723             } else {
724               // Lib is already a library name without prefix and suffix.
725               OS << "-l" << Lib;
726             }
727           }
728         }
729       };
730 
731       if (LinkMode == LinkModeShared && LinkDyLib) {
732         PrintForLib(DyLibName);
733       } else {
734         for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
735           auto Lib = RequiredLibs[i];
736           if (i)
737             OS << ' ';
738 
739           PrintForLib(Lib);
740         }
741       }
742       OS << '\n';
743     }
744 
745     // Print SYSTEM_LIBS after --libs.
746     // FIXME: Each LLVM component may have its dependent system libs.
747     if (PrintSystemLibs) {
748       // Output system libraries only if linking against a static
749       // library (since the shared library links to all system libs
750       // already)
751       OS << (LinkMode == LinkModeStatic ? LLVM_SYSTEM_LIBS : "") << '\n';
752     }
753   } else if (!Components.empty()) {
754     WithColor::error(errs(), "llvm-config")
755         << "components given, but unused\n\n";
756     usage();
757   }
758 
759   return 0;
760 }
761