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