xref: /llvm-project/llvm/tools/llvm-config/llvm-config.cpp (revision f7a33090a91015836497c75f173775392ab0304d)
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.
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.
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 (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
174     AvailableComponent *AC = &AvailableComponents[i];
175     ComponentMap[AC->Name] = AC;
176   }
177 
178   // Visit the components.
179   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
180     // Users are allowed to provide mixed case component names.
181     std::string ComponentLower = Components[i].lower();
182 
183     // Validate that the user supplied a valid component name.
184     if (!ComponentMap.count(ComponentLower)) {
185       llvm::errs() << "llvm-config: unknown component name: " << Components[i]
186                    << "\n";
187       exit(1);
188     }
189 
190     VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
191                    RequiredLibs, IncludeNonInstalled, GetComponentNames,
192                    GetComponentLibraryPath, Missing, DirSep);
193   }
194 
195   // The list is now ordered with leafs first, we want the libraries to printed
196   // in the reverse order of dependency.
197   std::reverse(RequiredLibs.begin(), RequiredLibs.end());
198 
199   return RequiredLibs;
200 }
201 
202 /* *** */
203 
204 static void usage(bool ExitWithFailure = true) {
205   errs() << "\
206 usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
207 \n\
208 Get various configuration information needed to compile programs which use\n\
209 LLVM.  Typically called from 'configure' scripts.  Examples:\n\
210   llvm-config --cxxflags\n\
211   llvm-config --ldflags\n\
212   llvm-config --libs engine bcreader scalaropts\n\
213 \n\
214 Options:\n\
215   --assertion-mode  Print assertion mode of LLVM tree (ON or OFF).\n\
216   --bindir          Directory containing LLVM executables.\n\
217   --build-mode      Print build mode of LLVM tree (e.g. Debug or Release).\n\
218   --build-system    Print the build system used to build LLVM (e.g. `cmake` or `gn`).\n\
219   --cflags          C compiler flags for files that include LLVM headers.\n\
220   --cmakedir        Directory containing LLVM CMake modules.\n\
221   --components      List of all possible components.\n\
222   --cppflags        C preprocessor flags for files that include LLVM headers.\n\
223   --cxxflags        C++ compiler flags for files that include LLVM headers.\n\
224   --has-rtti        Print whether or not LLVM was built with rtti (YES or NO).\n\
225   --help            Print a summary of llvm-config arguments.\n\
226   --host-target     Target triple used to configure LLVM.\n\
227   --ignore-libllvm  Ignore libLLVM and link component libraries instead.\n\
228   --includedir      Directory containing LLVM headers.\n\
229   --ldflags         Print Linker flags.\n\
230   --libdir          Directory containing LLVM libraries.\n\
231   --libfiles        Fully qualified library filenames for makefile depends.\n\
232   --libnames        Bare library names for in-tree builds.\n\
233   --libs            Libraries needed to link against LLVM components.\n\
234   --link-shared     Link the components as shared libraries.\n\
235   --link-static     Link the component libraries statically.\n\
236   --obj-root        Print the object root used to build LLVM.\n\
237   --prefix          Print the installation prefix.\n\
238   --shared-mode     Print how the provided components can be collectively linked (`shared` or `static`).\n\
239   --src-root        Print the source root LLVM was built from.\n\
240   --system-libs     System Libraries needed to link against LLVM components.\n\
241   --targets-built   List of all targets currently built.\n\
242   --version         Print LLVM version.\n\
243 Typical components:\n\
244   all               All LLVM libraries (default).\n\
245   engine            Either a native JIT or a bitcode interpreter.\n";
246   if (ExitWithFailure)
247     exit(1);
248 }
249 
250 /// Compute the path to the main executable.
251 std::string GetExecutablePath(const char *Argv0) {
252   // This just needs to be some symbol in the binary; C++ doesn't
253   // allow taking the address of ::main however.
254   void *P = (void *)(intptr_t)GetExecutablePath;
255   return llvm::sys::fs::getMainExecutable(Argv0, P);
256 }
257 
258 /// Expand the semi-colon delimited LLVM_DYLIB_COMPONENTS into
259 /// the full list of components.
260 std::vector<std::string> GetAllDyLibComponents(const bool IsInDevelopmentTree,
261                                                const bool GetComponentNames,
262                                                const std::string &DirSep) {
263   std::vector<StringRef> DyLibComponents;
264 
265   StringRef DyLibComponentsStr(LLVM_DYLIB_COMPONENTS);
266   size_t Offset = 0;
267   while (true) {
268     const size_t NextOffset = DyLibComponentsStr.find(';', Offset);
269     DyLibComponents.push_back(DyLibComponentsStr.substr(Offset, NextOffset-Offset));
270     if (NextOffset == std::string::npos) {
271       break;
272     }
273     Offset = NextOffset + 1;
274   }
275 
276   assert(!DyLibComponents.empty());
277 
278   return ComputeLibsForComponents(DyLibComponents,
279                                   /*IncludeNonInstalled=*/IsInDevelopmentTree,
280                                   GetComponentNames, nullptr, nullptr, DirSep);
281 }
282 
283 int main(int argc, char **argv) {
284   std::vector<StringRef> Components;
285   bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
286   bool PrintSystemLibs = false, PrintSharedMode = false;
287   bool HasAnyOption = false;
288 
289   // llvm-config is designed to support being run both from a development tree
290   // and from an installed path. We try and auto-detect which case we are in so
291   // that we can report the correct information when run from a development
292   // tree.
293   bool IsInDevelopmentTree;
294   enum { CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
295   llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
296   std::string CurrentExecPrefix;
297   std::string ActiveObjRoot;
298 
299   // If CMAKE_CFG_INTDIR is given, honor it as build mode.
300   char const *build_mode = LLVM_BUILDMODE;
301 #if defined(CMAKE_CFG_INTDIR)
302   if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
303     build_mode = CMAKE_CFG_INTDIR;
304 #endif
305 
306   // Create an absolute path, and pop up one directory (we expect to be inside a
307   // bin dir).
308   sys::fs::make_absolute(CurrentPath);
309   CurrentExecPrefix =
310       sys::path::parent_path(sys::path::parent_path(CurrentPath)).str();
311 
312   // Check to see if we are inside a development tree by comparing to possible
313   // locations (prefix style or CMake style).
314   if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
315     IsInDevelopmentTree = true;
316     DevelopmentTreeLayout = CMakeStyle;
317     ActiveObjRoot = LLVM_OBJ_ROOT;
318   } else if (sys::fs::equivalent(sys::path::parent_path(CurrentExecPrefix),
319                                  LLVM_OBJ_ROOT)) {
320     IsInDevelopmentTree = true;
321     DevelopmentTreeLayout = CMakeBuildModeStyle;
322     ActiveObjRoot = LLVM_OBJ_ROOT;
323   } else {
324     IsInDevelopmentTree = false;
325     DevelopmentTreeLayout = CMakeStyle; // Initialized to avoid warnings.
326   }
327 
328   // Compute various directory locations based on the derived location
329   // information.
330   std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir,
331               ActiveCMakeDir;
332   std::string ActiveIncludeOption;
333   if (IsInDevelopmentTree) {
334     ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
335     ActivePrefix = CurrentExecPrefix;
336 
337     // CMake organizes the products differently than a normal prefix style
338     // layout.
339     switch (DevelopmentTreeLayout) {
340     case CMakeStyle:
341       ActiveBinDir = ActiveObjRoot + "/bin";
342       ActiveLibDir = ActiveObjRoot + "/lib";
343       ActiveCMakeDir = ActiveLibDir + "/cmake/llvm";
344       break;
345     case CMakeBuildModeStyle:
346       // FIXME: Should we consider the build-mode-specific path as the prefix?
347       ActivePrefix = ActiveObjRoot;
348       ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
349       ActiveLibDir = ActiveObjRoot + "/" + build_mode + "/lib";
350       // The CMake directory isn't separated by build mode.
351       ActiveCMakeDir = ActivePrefix + "/lib/cmake/llvm";
352       break;
353     }
354 
355     // We need to include files from both the source and object trees.
356     ActiveIncludeOption =
357         ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
358   } else {
359     ActivePrefix = CurrentExecPrefix;
360     {
361       SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR);
362       sys::fs::make_absolute(ActivePrefix, Path);
363       ActiveIncludeDir = std::string(Path.str());
364     }
365     {
366       SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR);
367       sys::fs::make_absolute(ActivePrefix, Path);
368       ActiveBinDir = std::string(Path.str());
369     }
370     {
371       SmallString<256> Path(LLVM_INSTALL_LIBDIR);
372       sys::fs::make_absolute(ActivePrefix, Path);
373       ActiveLibDir = std::string(Path.str());
374     }
375     {
376       SmallString<256> Path(LLVM_INSTALL_PACKAGE_DIR);
377       sys::fs::make_absolute(ActivePrefix, Path);
378       ActiveCMakeDir = std::string(Path.str());
379     }
380     ActiveIncludeOption = "-I" + ActiveIncludeDir;
381   }
382 
383   /// We only use `shared library` mode in cases where the static library form
384   /// of the components provided are not available; note however that this is
385   /// skipped if we're run from within the build dir. However, once installed,
386   /// we still need to provide correct output when the static archives are
387   /// removed or, as in the case of CMake's `BUILD_SHARED_LIBS`, never present
388   /// in the first place. This can't be done at configure/build time.
389 
390   StringRef SharedExt, SharedVersionedExt, SharedDir, SharedPrefix, StaticExt,
391       StaticPrefix, StaticDir = "lib";
392   std::string DirSep = "/";
393   const Triple HostTriple(Triple::normalize(LLVM_HOST_TRIPLE));
394   if (HostTriple.isOSWindows()) {
395     SharedExt = "dll";
396     SharedVersionedExt = LLVM_DYLIB_VERSION ".dll";
397     if (HostTriple.isOSCygMing()) {
398       SharedPrefix = "lib";
399       StaticExt = "a";
400       StaticPrefix = "lib";
401     } else {
402       StaticExt = "lib";
403       DirSep = "\\";
404       std::replace(ActiveObjRoot.begin(), ActiveObjRoot.end(), '/', '\\');
405       std::replace(ActivePrefix.begin(), ActivePrefix.end(), '/', '\\');
406       std::replace(ActiveBinDir.begin(), ActiveBinDir.end(), '/', '\\');
407       std::replace(ActiveLibDir.begin(), ActiveLibDir.end(), '/', '\\');
408       std::replace(ActiveCMakeDir.begin(), ActiveCMakeDir.end(), '/', '\\');
409       std::replace(ActiveIncludeOption.begin(), ActiveIncludeOption.end(), '/',
410                    '\\');
411     }
412     SharedDir = ActiveBinDir;
413     StaticDir = ActiveLibDir;
414   } else if (HostTriple.isOSDarwin()) {
415     SharedExt = "dylib";
416     SharedVersionedExt = LLVM_DYLIB_VERSION ".dylib";
417     StaticExt = "a";
418     StaticDir = SharedDir = ActiveLibDir;
419     StaticPrefix = SharedPrefix = "lib";
420   } else {
421     // default to the unix values:
422     SharedExt = "so";
423     SharedVersionedExt = LLVM_DYLIB_VERSION ".so";
424     StaticExt = "a";
425     StaticDir = SharedDir = ActiveLibDir;
426     StaticPrefix = SharedPrefix = "lib";
427   }
428 
429   const bool BuiltDyLib = !!LLVM_ENABLE_DYLIB;
430 
431   /// CMake style shared libs, ie each component is in a shared library.
432   const bool BuiltSharedLibs = !!LLVM_ENABLE_SHARED;
433 
434   bool DyLibExists = false;
435   const std::string DyLibName =
436       (SharedPrefix + "LLVM-" + SharedVersionedExt).str();
437 
438   // If LLVM_LINK_DYLIB is ON, the single shared library will be returned
439   // for "--libs", etc, if they exist. This behaviour can be overridden with
440   // --link-static or --link-shared.
441   bool LinkDyLib = !!LLVM_LINK_DYLIB;
442 
443   if (BuiltDyLib) {
444     std::string path((SharedDir + DirSep + DyLibName).str());
445     if (DirSep == "\\") {
446       std::replace(path.begin(), path.end(), '/', '\\');
447     }
448     DyLibExists = sys::fs::exists(path);
449     if (!DyLibExists) {
450       // The shared library does not exist: don't error unless the user
451       // explicitly passes --link-shared.
452       LinkDyLib = false;
453     }
454   }
455   LinkMode LinkMode =
456       (LinkDyLib || BuiltSharedLibs) ? LinkModeShared : LinkModeAuto;
457 
458   /// Get the component's library name without the lib prefix and the
459   /// extension. Returns true if Lib is in a recognized format.
460   auto GetComponentLibraryNameSlice = [&](const StringRef &Lib,
461                                           StringRef &Out) {
462     if (Lib.startswith("lib")) {
463       unsigned FromEnd;
464       if (Lib.endswith(StaticExt)) {
465         FromEnd = StaticExt.size() + 1;
466       } else if (Lib.endswith(SharedExt)) {
467         FromEnd = SharedExt.size() + 1;
468       } else {
469         FromEnd = 0;
470       }
471 
472       if (FromEnd != 0) {
473         Out = Lib.slice(3, Lib.size() - FromEnd);
474         return true;
475       }
476     }
477 
478     return false;
479   };
480   /// Maps Unixizms to the host platform.
481   auto GetComponentLibraryFileName = [&](const StringRef &Lib,
482                                          const bool Shared) {
483     std::string LibFileName;
484     if (Shared) {
485       if (Lib == DyLibName) {
486         // Treat the DyLibName specially. It is not a component library and
487         // already has the necessary prefix and suffix (e.g. `.so`) added so
488         // just return it unmodified.
489         assert(Lib.endswith(SharedExt) && "DyLib is missing suffix");
490         LibFileName = std::string(Lib);
491       } else {
492         LibFileName = (SharedPrefix + Lib + "." + SharedExt).str();
493       }
494     } else {
495       // default to static
496       LibFileName = (StaticPrefix + Lib + "." + StaticExt).str();
497     }
498 
499     return LibFileName;
500   };
501   /// Get the full path for a possibly shared component library.
502   auto GetComponentLibraryPath = [&](const StringRef &Name, const bool Shared) {
503     auto LibFileName = GetComponentLibraryFileName(Name, Shared);
504     if (Shared) {
505       return (SharedDir + DirSep + LibFileName).str();
506     } else {
507       return (StaticDir + DirSep + LibFileName).str();
508     }
509   };
510 
511   raw_ostream &OS = outs();
512   for (int i = 1; i != argc; ++i) {
513     StringRef Arg = argv[i];
514 
515     if (Arg.startswith("-")) {
516       HasAnyOption = true;
517       if (Arg == "--version") {
518         OS << PACKAGE_VERSION << '\n';
519       } else if (Arg == "--prefix") {
520         OS << ActivePrefix << '\n';
521       } else if (Arg == "--bindir") {
522         OS << ActiveBinDir << '\n';
523       } else if (Arg == "--includedir") {
524         OS << ActiveIncludeDir << '\n';
525       } else if (Arg == "--libdir") {
526         OS << ActiveLibDir << '\n';
527       } else if (Arg == "--cmakedir") {
528         OS << ActiveCMakeDir << '\n';
529       } else if (Arg == "--cppflags") {
530         OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
531       } else if (Arg == "--cflags") {
532         OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
533       } else if (Arg == "--cxxflags") {
534         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
535       } else if (Arg == "--ldflags") {
536         OS << ((HostTriple.isWindowsMSVCEnvironment()) ? "-LIBPATH:" : "-L")
537            << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
538       } else if (Arg == "--system-libs") {
539         PrintSystemLibs = true;
540       } else if (Arg == "--libs") {
541         PrintLibs = true;
542       } else if (Arg == "--libnames") {
543         PrintLibNames = true;
544       } else if (Arg == "--libfiles") {
545         PrintLibFiles = true;
546       } else if (Arg == "--components") {
547         /// If there are missing static archives and a dylib was
548         /// built, print LLVM_DYLIB_COMPONENTS instead of everything
549         /// in the manifest.
550         std::vector<std::string> Components;
551         for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
552           // Only include non-installed components when in a development tree.
553           if (!AvailableComponents[j].IsInstalled && !IsInDevelopmentTree)
554             continue;
555 
556           Components.push_back(AvailableComponents[j].Name);
557           if (AvailableComponents[j].Library && !IsInDevelopmentTree) {
558             std::string path(
559                 GetComponentLibraryPath(AvailableComponents[j].Library, false));
560             if (DirSep == "\\") {
561               std::replace(path.begin(), path.end(), '/', '\\');
562             }
563             if (DyLibExists && !sys::fs::exists(path)) {
564               Components =
565                   GetAllDyLibComponents(IsInDevelopmentTree, true, DirSep);
566               llvm::sort(Components);
567               break;
568             }
569           }
570         }
571 
572         for (unsigned I = 0; I < Components.size(); ++I) {
573           if (I) {
574             OS << ' ';
575           }
576 
577           OS << Components[I];
578         }
579         OS << '\n';
580       } else if (Arg == "--targets-built") {
581         OS << LLVM_TARGETS_BUILT << '\n';
582       } else if (Arg == "--host-target") {
583         OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
584       } else if (Arg == "--build-mode") {
585         OS << build_mode << '\n';
586       } else if (Arg == "--assertion-mode") {
587 #if defined(NDEBUG)
588         OS << "OFF\n";
589 #else
590         OS << "ON\n";
591 #endif
592       } else if (Arg == "--build-system") {
593         OS << LLVM_BUILD_SYSTEM << '\n';
594       } else if (Arg == "--has-rtti") {
595         OS << (LLVM_HAS_RTTI ? "YES" : "NO") << '\n';
596       } else if (Arg == "--shared-mode") {
597         PrintSharedMode = true;
598       } else if (Arg == "--obj-root") {
599         OS << ActivePrefix << '\n';
600       } else if (Arg == "--src-root") {
601         OS << LLVM_SRC_ROOT << '\n';
602       } else if (Arg == "--ignore-libllvm") {
603         LinkDyLib = false;
604         LinkMode = BuiltSharedLibs ? LinkModeShared : LinkModeAuto;
605       } else if (Arg == "--link-shared") {
606         LinkMode = LinkModeShared;
607       } else if (Arg == "--link-static") {
608         LinkMode = LinkModeStatic;
609       } else if (Arg == "--help") {
610         usage(false);
611       } else {
612         usage();
613       }
614     } else {
615       Components.push_back(Arg);
616     }
617   }
618 
619   if (!HasAnyOption)
620     usage();
621 
622   if (LinkMode == LinkModeShared && !DyLibExists && !BuiltSharedLibs) {
623     WithColor::error(errs(), "llvm-config") << DyLibName << " is missing\n";
624     return 1;
625   }
626 
627   if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs ||
628       PrintSharedMode) {
629 
630     if (PrintSharedMode && BuiltSharedLibs) {
631       OS << "shared\n";
632       return 0;
633     }
634 
635     // If no components were specified, default to "all".
636     if (Components.empty())
637       Components.push_back("all");
638 
639     // Construct the list of all the required libraries.
640     std::function<std::string(const StringRef &)>
641         GetComponentLibraryPathFunction = [&](const StringRef &Name) {
642           return GetComponentLibraryPath(Name, LinkMode == LinkModeShared);
643         };
644     std::vector<std::string> MissingLibs;
645     std::vector<std::string> RequiredLibs = ComputeLibsForComponents(
646         Components,
647         /*IncludeNonInstalled=*/IsInDevelopmentTree, false,
648         &GetComponentLibraryPathFunction, &MissingLibs, DirSep);
649     if (!MissingLibs.empty()) {
650       switch (LinkMode) {
651       case LinkModeShared:
652         if (LinkDyLib && !BuiltSharedLibs)
653           break;
654         // Using component shared libraries.
655         for (auto &Lib : MissingLibs)
656           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
657         return 1;
658       case LinkModeAuto:
659         if (DyLibExists) {
660           LinkMode = LinkModeShared;
661           break;
662         }
663         WithColor::error(errs(), "llvm-config")
664             << "component libraries and shared library\n\n";
665         [[fallthrough]];
666       case LinkModeStatic:
667         for (auto &Lib : MissingLibs)
668           WithColor::error(errs(), "llvm-config") << "missing: " << Lib << "\n";
669         return 1;
670       }
671     } else if (LinkMode == LinkModeAuto) {
672       LinkMode = LinkModeStatic;
673     }
674 
675     if (PrintSharedMode) {
676       std::unordered_set<std::string> FullDyLibComponents;
677       std::vector<std::string> DyLibComponents =
678           GetAllDyLibComponents(IsInDevelopmentTree, false, DirSep);
679 
680       for (auto &Component : DyLibComponents) {
681         FullDyLibComponents.insert(Component);
682       }
683       DyLibComponents.clear();
684 
685       for (auto &Lib : RequiredLibs) {
686         if (!FullDyLibComponents.count(Lib)) {
687           OS << "static\n";
688           return 0;
689         }
690       }
691       FullDyLibComponents.clear();
692 
693       if (LinkMode == LinkModeShared) {
694         OS << "shared\n";
695         return 0;
696       } else {
697         OS << "static\n";
698         return 0;
699       }
700     }
701 
702     if (PrintLibs || PrintLibNames || PrintLibFiles) {
703 
704       auto PrintForLib = [&](const StringRef &Lib) {
705         const bool Shared = LinkMode == LinkModeShared;
706         if (PrintLibNames) {
707           OS << GetComponentLibraryFileName(Lib, Shared);
708         } else if (PrintLibFiles) {
709           OS << GetComponentLibraryPath(Lib, Shared);
710         } else if (PrintLibs) {
711           // On Windows, output full path to library without parameters.
712           // Elsewhere, if this is a typical library name, include it using -l.
713           if (HostTriple.isWindowsMSVCEnvironment()) {
714             OS << GetComponentLibraryPath(Lib, Shared);
715           } else {
716             StringRef LibName;
717             if (GetComponentLibraryNameSlice(Lib, LibName)) {
718               // Extract library name (remove prefix and suffix).
719               OS << "-l" << LibName;
720             } else {
721               // Lib is already a library name without prefix and suffix.
722               OS << "-l" << Lib;
723             }
724           }
725         }
726       };
727 
728       if (LinkMode == LinkModeShared && LinkDyLib) {
729         PrintForLib(DyLibName);
730       } else {
731         for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
732           auto Lib = RequiredLibs[i];
733           if (i)
734             OS << ' ';
735 
736           PrintForLib(Lib);
737         }
738       }
739       OS << '\n';
740     }
741 
742     // Print SYSTEM_LIBS after --libs.
743     // FIXME: Each LLVM component may have its dependent system libs.
744     if (PrintSystemLibs) {
745       // Output system libraries only if linking against a static
746       // library (since the shared library links to all system libs
747       // already)
748       OS << (LinkMode == LinkModeStatic ? LLVM_SYSTEM_LIBS : "") << '\n';
749     }
750   } else if (!Components.empty()) {
751     WithColor::error(errs(), "llvm-config")
752         << "components given, but unused\n\n";
753     usage();
754   }
755 
756   return 0;
757 }
758