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