1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ToolChains.h"
11 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/SanitizerArgs.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Option/Arg.h"
24 #include "llvm/Option/ArgList.h"
25 #include "llvm/Option/OptTable.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cstdlib> // ::getenv
34 #include <system_error>
36 using namespace clang::driver;
37 using namespace clang::driver::toolchains;
38 using namespace clang;
39 using namespace llvm::opt;
41 MachO::MachO(const Driver &D, const llvm::Triple &Triple,
43 : ToolChain(D, Triple, Args) {
44 getProgramPaths().push_back(getDriver().getInstalledDir());
45 if (getDriver().getInstalledDir() != getDriver().Dir)
46 getProgramPaths().push_back(getDriver().Dir);
48 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
49 getProgramPaths().push_back(getDriver().getInstalledDir());
50 if (getDriver().getInstalledDir() != getDriver().Dir)
51 getProgramPaths().push_back(getDriver().Dir);
54 /// Darwin - Darwin tool chain for i386 and x86_64.
55 Darwin::Darwin(const Driver & D, const llvm::Triple & Triple,
57 : MachO(D, Triple, Args), TargetInitialized(false) {
58 // Compute the initial Darwin version from the triple
59 unsigned Major, Minor, Micro;
60 if (!Triple.getMacOSXVersion(Major, Minor, Micro))
61 getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
63 llvm::raw_string_ostream(MacosxVersionMin)
64 << Major << '.' << Minor << '.' << Micro;
66 // FIXME: DarwinVersion is only used to find GCC's libexec directory.
67 // It should be removed when we stop supporting that.
68 DarwinVersion[0] = Minor + 4;
69 DarwinVersion[1] = Micro;
72 // Compute the initial iOS version from the triple
73 Triple.getiOSVersion(Major, Minor, Micro);
74 llvm::raw_string_ostream(iOSVersionMin)
75 << Major << '.' << Minor << '.' << Micro;
78 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
79 types::ID Ty = types::lookupTypeForExtension(Ext);
81 // Darwin always preprocesses assembly files (unless -x is used explicitly).
82 if (Ty == types::TY_PP_Asm)
88 bool MachO::HasNativeLLVMSupport() const {
92 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
93 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
94 if (isTargetIOSBased())
95 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
97 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
98 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
101 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
102 bool Darwin::hasBlocksRuntime() const {
103 if (isTargetIOSBased())
104 return !isIPhoneOSVersionLT(3, 2);
106 assert(isTargetMacOS() && "unexpected darwin target");
107 return !isMacosxVersionLT(10, 6);
111 static const char *GetArmArchForMArch(StringRef Value) {
112 return llvm::StringSwitch<const char*>(Value)
113 .Case("armv6k", "armv6")
114 .Case("armv6m", "armv6m")
115 .Case("armv5tej", "armv5")
116 .Case("xscale", "xscale")
117 .Case("armv4t", "armv4t")
118 .Case("armv7", "armv7")
119 .Cases("armv7a", "armv7-a", "armv7")
120 .Cases("armv7r", "armv7-r", "armv7")
121 .Cases("armv7em", "armv7e-m", "armv7em")
122 .Cases("armv7k", "armv7-k", "armv7k")
123 .Cases("armv7m", "armv7-m", "armv7m")
124 .Cases("armv7s", "armv7-s", "armv7s")
128 static const char *GetArmArchForMCpu(StringRef Value) {
129 return llvm::StringSwitch<const char *>(Value)
130 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
131 .Cases("arm10e", "arm10tdmi", "armv5")
132 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
133 .Case("xscale", "xscale")
134 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
135 .Case("cortex-m0", "armv6m")
136 .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
137 .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7")
138 .Cases("cortex-r4", "cortex-r5", "armv7r")
139 .Case("cortex-m3", "armv7m")
140 .Cases("cortex-m4", "cortex-m7", "armv7em")
141 .Case("swift", "armv7s")
145 static bool isSoftFloatABI(const ArgList &Args) {
146 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
147 options::OPT_mfloat_abi_EQ);
151 return A->getOption().matches(options::OPT_msoft_float) ||
152 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
153 A->getValue() == StringRef("soft"));
156 StringRef MachO::getMachOArchName(const ArgList &Args) const {
157 switch (getTriple().getArch()) {
159 return getDefaultUniversalArchName();
161 case llvm::Triple::aarch64:
164 case llvm::Triple::thumb:
165 case llvm::Triple::arm: {
166 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
167 if (const char *Arch = GetArmArchForMArch(A->getValue()))
170 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
171 if (const char *Arch = GetArmArchForMCpu(A->getValue()))
186 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
187 types::ID InputType) const {
188 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
190 return Triple.getTriple();
193 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
194 types::ID InputType) const {
195 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
197 // If the target isn't initialized (e.g., an unknown Darwin platform, return
198 // the default triple).
199 if (!isTargetInitialized())
200 return Triple.getTriple();
203 Str += isTargetIOSBased() ? "ios" : "macosx";
204 Str += getTargetVersion().getAsString();
205 Triple.setOSName(Str);
207 return Triple.getTriple();
210 void Generic_ELF::anchor() {}
212 Tool *MachO::getTool(Action::ActionClass AC) const {
214 case Action::LipoJobClass:
216 Lipo.reset(new tools::darwin::Lipo(*this));
218 case Action::DsymutilJobClass:
220 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
221 return Dsymutil.get();
222 case Action::VerifyDebugInfoJobClass:
224 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
225 return VerifyDebug.get();
227 return ToolChain::getTool(AC);
231 Tool *MachO::buildLinker() const {
232 return new tools::darwin::Link(*this);
235 Tool *MachO::buildAssembler() const {
236 return new tools::darwin::Assemble(*this);
239 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
241 : Darwin(D, Triple, Args) {
244 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
245 // For iOS, 64-bit, promote certain warnings to errors.
246 if (!isTargetMacOS() && getTriple().isArch64Bit()) {
247 // Always enable -Wdeprecated-objc-isa-usage and promote it
249 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
250 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
252 // Also error about implicit function declarations, as that
253 // can impact calling conventions.
254 CC1Args.push_back("-Werror=implicit-function-declaration");
258 /// \brief Determine whether Objective-C automated reference counting is
260 static bool isObjCAutoRefCount(const ArgList &Args) {
261 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
264 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
265 ArgStringList &CmdArgs) const {
266 // Avoid linking compatibility stubs on i386 mac.
267 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
270 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
272 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
273 runtime.hasSubscripting())
276 CmdArgs.push_back("-force_load");
277 SmallString<128> P(getDriver().ClangExecutable);
278 llvm::sys::path::remove_filename(P); // 'clang'
279 llvm::sys::path::remove_filename(P); // 'bin'
280 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
281 // Mash in the platform.
282 if (isTargetIOSSimulator())
283 P += "iphonesimulator";
284 else if (isTargetIPhoneOS())
290 CmdArgs.push_back(Args.MakeArgString(P));
293 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
294 StringRef DarwinLibName, bool AlwaysLink,
295 bool IsEmbedded, bool AddRPath) const {
296 SmallString<128> Dir(getDriver().ResourceDir);
297 llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
299 SmallString<128> P(Dir);
300 llvm::sys::path::append(P, DarwinLibName);
302 // For now, allow missing resource libraries to support developers who may
303 // not have compiler-rt checked out or integrated into their build (unless
304 // we explicitly force linking with this library).
305 if (AlwaysLink || llvm::sys::fs::exists(P.str()))
306 CmdArgs.push_back(Args.MakeArgString(P.str()));
308 // Adding the rpaths might negatively interact when other rpaths are involved,
309 // so we should make sure we add the rpaths last, after all user-specified
310 // rpaths. This is currently true from this place, but we need to be
311 // careful if this function is ever called before user's rpaths are emitted.
313 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
315 // Add @executable_path to rpath to support having the dylib copied with
317 CmdArgs.push_back("-rpath");
318 CmdArgs.push_back("@executable_path");
320 // Add the path to the resource dir to rpath to support using the dylib
321 // from the default location without copying.
322 CmdArgs.push_back("-rpath");
323 CmdArgs.push_back(Args.MakeArgString(Dir.str()));
327 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
328 ArgStringList &CmdArgs) const {
329 // Darwin only supports the compiler-rt based runtime libraries.
330 switch (GetRuntimeLibType(Args)) {
331 case ToolChain::RLT_CompilerRT:
334 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
335 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
339 // Darwin doesn't support real static executables, don't link any runtime
340 // libraries with -static.
341 if (Args.hasArg(options::OPT_static) ||
342 Args.hasArg(options::OPT_fapple_kext) ||
343 Args.hasArg(options::OPT_mkernel))
346 // Reject -static-libgcc for now, we can deal with this when and if someone
347 // cares. This is useful in situations where someone wants to statically link
348 // something like libstdc++, and needs its runtime support routines.
349 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
350 getDriver().Diag(diag::err_drv_unsupported_opt)
351 << A->getAsString(Args);
355 // If we are building profile support, link that library in.
356 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
358 Args.hasArg(options::OPT_fprofile_generate) ||
359 Args.hasArg(options::OPT_fprofile_instr_generate) ||
360 Args.hasArg(options::OPT_fcreate_profile) ||
361 Args.hasArg(options::OPT_coverage)) {
362 // Select the appropriate runtime library for the target.
363 if (isTargetIOSBased())
364 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
366 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
369 const SanitizerArgs &Sanitize = getSanitizerArgs();
371 // Add Ubsan runtime library, if required.
372 if (Sanitize.needsUbsanRt()) {
373 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
374 if (isTargetIOSBased()) {
375 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
376 << "-fsanitize=undefined";
378 assert(isTargetMacOS() && "unexpected non OS X target");
379 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
381 // The Ubsan runtime library requires C++.
382 AddCXXStdlibLibArgs(Args, CmdArgs);
386 // Add ASAN runtime library, if required. Dynamic libraries and bundles
387 // should not be linked with the runtime library.
388 if (Sanitize.needsAsanRt()) {
389 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
390 if (isTargetIPhoneOS()) {
391 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
392 << "-fsanitize=address";
394 if (!Args.hasArg(options::OPT_dynamiclib) &&
395 !Args.hasArg(options::OPT_bundle)) {
396 // The ASAN runtime library requires C++.
397 AddCXXStdlibLibArgs(Args, CmdArgs);
399 if (isTargetMacOS()) {
400 AddLinkRuntimeLib(Args, CmdArgs,
401 "libclang_rt.asan_osx_dynamic.dylib",
402 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
405 if (isTargetIOSSimulator()) {
406 AddLinkRuntimeLib(Args, CmdArgs,
407 "libclang_rt.asan_iossim_dynamic.dylib",
408 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
415 // Otherwise link libSystem, then the dynamic runtime library, and finally any
416 // target specific static runtime library.
417 CmdArgs.push_back("-lSystem");
419 // Select the dynamic runtime library and the target specific static library.
420 if (isTargetIOSBased()) {
421 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
422 // it never went into the SDK.
423 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
424 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
425 getTriple().getArch() != llvm::Triple::aarch64)
426 CmdArgs.push_back("-lgcc_s.1");
428 // We currently always need a static runtime library for iOS.
429 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
431 assert(isTargetMacOS() && "unexpected non MacOS platform");
432 // The dynamic runtime library was merged with libSystem for 10.6 and
433 // beyond; only 10.4 and 10.5 need an additional runtime library.
434 if (isMacosxVersionLT(10, 5))
435 CmdArgs.push_back("-lgcc_s.10.4");
436 else if (isMacosxVersionLT(10, 6))
437 CmdArgs.push_back("-lgcc_s.10.5");
439 // For OS X, we thought we would only need a static runtime library when
440 // targeting 10.4, to provide versions of the static functions which were
441 // omitted from 10.4.dylib.
443 // Unfortunately, that turned out to not be true, because Darwin system
444 // headers can still use eprintf on i386, and it is not exported from
445 // libSystem. Therefore, we still must provide a runtime library just for
446 // the tiny tiny handful of projects that *might* use that symbol.
447 if (isMacosxVersionLT(10, 5)) {
448 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
450 if (getTriple().getArch() == llvm::Triple::x86)
451 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
452 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
457 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
458 const OptTable &Opts = getDriver().getOpts();
460 // Support allowing the SDKROOT environment variable used by xcrun and other
461 // Xcode tools to define the default sysroot, by making it the default for
463 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
464 // Warn if the path does not exist.
465 if (!llvm::sys::fs::exists(A->getValue()))
466 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
468 if (char *env = ::getenv("SDKROOT")) {
469 // We only use this value as the default if it is an absolute path,
470 // exists, and it is not the root path.
471 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
472 StringRef(env) != "/") {
473 Args.append(Args.MakeSeparateArg(
474 nullptr, Opts.getOption(options::OPT_isysroot), env));
479 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
480 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
482 if (OSXVersion && iOSVersion) {
483 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
484 << OSXVersion->getAsString(Args)
485 << iOSVersion->getAsString(Args);
486 iOSVersion = nullptr;
487 } else if (!OSXVersion && !iOSVersion) {
488 // If no deployment target was specified on the command line, check for
489 // environment defines.
492 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
494 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
497 // If no '-miphoneos-version-min' specified on the command line and
498 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
499 // based on -isysroot.
500 if (iOSTarget.empty()) {
501 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
502 StringRef first, second;
503 StringRef isysroot = A->getValue();
504 std::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
506 iOSTarget = second.substr(0,3);
510 // If no OSX or iOS target has been specified and we're compiling for armv7,
511 // go ahead as assume we're targeting iOS.
512 StringRef MachOArchName = getMachOArchName(Args);
513 if (OSXTarget.empty() && iOSTarget.empty() &&
514 (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
515 MachOArchName == "arm64"))
516 iOSTarget = iOSVersionMin;
518 // Allow conflicts among OSX and iOS for historical reasons, but choose the
520 if (!OSXTarget.empty() && !iOSTarget.empty()) {
521 if (getTriple().getArch() == llvm::Triple::arm ||
522 getTriple().getArch() == llvm::Triple::aarch64 ||
523 getTriple().getArch() == llvm::Triple::thumb)
529 if (!OSXTarget.empty()) {
530 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
531 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
532 Args.append(OSXVersion);
533 } else if (!iOSTarget.empty()) {
534 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
535 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
536 Args.append(iOSVersion);
537 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
538 MachOArchName != "armv7em") {
539 // Otherwise, assume we are targeting OS X.
540 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
541 OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin);
542 Args.append(OSXVersion);
546 DarwinPlatformKind Platform;
552 llvm_unreachable("Unable to infer Darwin variant");
554 // Set the tool chain target information.
555 unsigned Major, Minor, Micro;
557 if (Platform == MacOS) {
558 assert(!iOSVersion && "Unknown target platform!");
559 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
560 Micro, HadExtra) || HadExtra ||
561 Major != 10 || Minor >= 100 || Micro >= 100)
562 getDriver().Diag(diag::err_drv_invalid_version_number)
563 << OSXVersion->getAsString(Args);
564 } else if (Platform == IPhoneOS) {
565 assert(iOSVersion && "Unknown target platform!");
566 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor,
567 Micro, HadExtra) || HadExtra ||
568 Major >= 10 || Minor >= 100 || Micro >= 100)
569 getDriver().Diag(diag::err_drv_invalid_version_number)
570 << iOSVersion->getAsString(Args);
572 llvm_unreachable("unknown kind of Darwin platform");
574 // Recognize iOS targets with an x86 architecture as the iOS simulator.
575 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
576 getTriple().getArch() == llvm::Triple::x86_64))
577 Platform = IPhoneOSSimulator;
579 setTarget(Platform, Major, Minor, Micro);
582 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
583 ArgStringList &CmdArgs) const {
584 CXXStdlibType Type = GetCXXStdlibType(Args);
587 case ToolChain::CST_Libcxx:
588 CmdArgs.push_back("-lc++");
591 case ToolChain::CST_Libstdcxx: {
592 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
593 // it was previously found in the gcc lib dir. However, for all the Darwin
594 // platforms we care about it was -lstdc++.6, so we search for that
595 // explicitly if we can't see an obvious -lstdc++ candidate.
597 // Check in the sysroot first.
598 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
599 SmallString<128> P(A->getValue());
600 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
602 if (!llvm::sys::fs::exists(P.str())) {
603 llvm::sys::path::remove_filename(P);
604 llvm::sys::path::append(P, "libstdc++.6.dylib");
605 if (llvm::sys::fs::exists(P.str())) {
606 CmdArgs.push_back(Args.MakeArgString(P.str()));
612 // Otherwise, look in the root.
613 // FIXME: This should be removed someday when we don't have to care about
614 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
615 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
616 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
617 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
621 // Otherwise, let the linker search.
622 CmdArgs.push_back("-lstdc++");
628 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
629 ArgStringList &CmdArgs) const {
631 // For Darwin platforms, use the compiler-rt-based support library
632 // instead of the gcc-provided one (which is also incidentally
633 // only present in the gcc lib dir, which makes it hard to find).
635 SmallString<128> P(getDriver().ResourceDir);
636 llvm::sys::path::append(P, "lib", "darwin");
638 // Use the newer cc_kext for iOS ARM after 6.0.
639 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
640 getTriple().getArch() == llvm::Triple::aarch64 ||
641 !isIPhoneOSVersionLT(6, 0)) {
642 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
644 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
647 // For now, allow missing resource libraries to support developers who may
648 // not have compiler-rt checked out or integrated into their build.
649 if (llvm::sys::fs::exists(P.str()))
650 CmdArgs.push_back(Args.MakeArgString(P.str()));
653 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
654 const char *BoundArch) const {
655 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
656 const OptTable &Opts = getDriver().getOpts();
658 // FIXME: We really want to get out of the tool chain level argument
659 // translation business, as it makes the driver functionality much
660 // more opaque. For now, we follow gcc closely solely for the
661 // purpose of easily achieving feature parity & testability. Once we
662 // have something that works, we should reevaluate each translation
663 // and try to push it down into tool specific logic.
665 for (Arg *A : Args) {
666 if (A->getOption().matches(options::OPT_Xarch__)) {
667 // Skip this argument unless the architecture matches either the toolchain
668 // triple arch, or the arch being bound.
669 llvm::Triple::ArchType XarchArch =
670 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
671 if (!(XarchArch == getArch() ||
672 (BoundArch && XarchArch ==
673 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
676 Arg *OriginalArg = A;
677 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
678 unsigned Prev = Index;
679 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
681 // If the argument parsing failed or more than one argument was
682 // consumed, the -Xarch_ argument's parameter tried to consume
683 // extra arguments. Emit an error and ignore.
685 // We also want to disallow any options which would alter the
686 // driver behavior; that isn't going to work in our model. We
687 // use isDriverOption() as an approximation, although things
688 // like -O4 are going to slip through.
689 if (!XarchArg || Index > Prev + 1) {
690 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
691 << A->getAsString(Args);
693 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
694 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
695 << A->getAsString(Args);
699 XarchArg->setBaseArg(A);
701 A = XarchArg.release();
702 DAL->AddSynthesizedArg(A);
704 // Linker input arguments require custom handling. The problem is that we
705 // have already constructed the phase actions, so we can not treat them as
706 // "input arguments".
707 if (A->getOption().hasFlag(options::LinkerInput)) {
708 // Convert the argument into individual Zlinker_input_args.
709 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
710 DAL->AddSeparateArg(OriginalArg,
711 Opts.getOption(options::OPT_Zlinker_input),
719 // Sob. These is strictly gcc compatible for the time being. Apple
720 // gcc translates options twice, which means that self-expanding
721 // options add duplicates.
722 switch ((options::ID) A->getOption().getID()) {
727 case options::OPT_mkernel:
728 case options::OPT_fapple_kext:
730 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
733 case options::OPT_dependency_file:
734 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
738 case options::OPT_gfull:
739 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
741 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
744 case options::OPT_gused:
745 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
747 Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
750 case options::OPT_shared:
751 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
754 case options::OPT_fconstant_cfstrings:
755 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
758 case options::OPT_fno_constant_cfstrings:
759 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
762 case options::OPT_Wnonportable_cfstrings:
764 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
767 case options::OPT_Wno_nonportable_cfstrings:
769 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
772 case options::OPT_fpascal_strings:
773 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
776 case options::OPT_fno_pascal_strings:
777 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
782 if (getTriple().getArch() == llvm::Triple::x86 ||
783 getTriple().getArch() == llvm::Triple::x86_64)
784 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
785 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
788 // Add the arch options based on the particular spelling of -arch, to match
789 // how the driver driver works.
791 StringRef Name = BoundArch;
792 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
793 const Option MArch = Opts.getOption(options::OPT_march_EQ);
795 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
796 // which defines the list of which architectures we accept.
799 else if (Name == "ppc601")
800 DAL->AddJoinedArg(nullptr, MCpu, "601");
801 else if (Name == "ppc603")
802 DAL->AddJoinedArg(nullptr, MCpu, "603");
803 else if (Name == "ppc604")
804 DAL->AddJoinedArg(nullptr, MCpu, "604");
805 else if (Name == "ppc604e")
806 DAL->AddJoinedArg(nullptr, MCpu, "604e");
807 else if (Name == "ppc750")
808 DAL->AddJoinedArg(nullptr, MCpu, "750");
809 else if (Name == "ppc7400")
810 DAL->AddJoinedArg(nullptr, MCpu, "7400");
811 else if (Name == "ppc7450")
812 DAL->AddJoinedArg(nullptr, MCpu, "7450");
813 else if (Name == "ppc970")
814 DAL->AddJoinedArg(nullptr, MCpu, "970");
816 else if (Name == "ppc64" || Name == "ppc64le")
817 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
819 else if (Name == "i386")
821 else if (Name == "i486")
822 DAL->AddJoinedArg(nullptr, MArch, "i486");
823 else if (Name == "i586")
824 DAL->AddJoinedArg(nullptr, MArch, "i586");
825 else if (Name == "i686")
826 DAL->AddJoinedArg(nullptr, MArch, "i686");
827 else if (Name == "pentium")
828 DAL->AddJoinedArg(nullptr, MArch, "pentium");
829 else if (Name == "pentium2")
830 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
831 else if (Name == "pentpro")
832 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
833 else if (Name == "pentIIm3")
834 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
836 else if (Name == "x86_64")
837 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
838 else if (Name == "x86_64h") {
839 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
840 DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
843 else if (Name == "arm")
844 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
845 else if (Name == "armv4t")
846 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
847 else if (Name == "armv5")
848 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
849 else if (Name == "xscale")
850 DAL->AddJoinedArg(nullptr, MArch, "xscale");
851 else if (Name == "armv6")
852 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
853 else if (Name == "armv6m")
854 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
855 else if (Name == "armv7")
856 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
857 else if (Name == "armv7em")
858 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
859 else if (Name == "armv7k")
860 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
861 else if (Name == "armv7m")
862 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
863 else if (Name == "armv7s")
864 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
870 void MachO::AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args,
871 llvm::opt::ArgStringList &CmdArgs) const {
872 // Embedded targets are simple at the moment, not supporting sanitizers and
873 // with different libraries for each member of the product { static, PIC } x
874 // { hard-float, soft-float }
875 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
877 tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
880 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
882 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
886 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
887 const char *BoundArch) const {
888 // First get the generic Apple args, before moving onto Darwin-specific ones.
889 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
890 const OptTable &Opts = getDriver().getOpts();
892 // If no architecture is bound, none of the translations here are relevant.
896 // Add an explicit version min argument for the deployment target. We do this
897 // after argument translation because -Xarch_ arguments may add a version min
899 AddDeploymentTarget(*DAL);
901 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
902 // FIXME: It would be far better to avoid inserting those -static arguments,
903 // but we can't check the deployment target in the translation code until
905 if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
906 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
909 if (A->getOption().getID() != options::OPT_mkernel &&
910 A->getOption().getID() != options::OPT_fapple_kext)
912 assert(it != ie && "unexpected argument translation");
914 assert(A->getOption().getID() == options::OPT_static &&
915 "missing expected -static argument");
916 it = DAL->getArgs().erase(it);
920 // Default to use libc++ on OS X 10.9+ and iOS 7+.
921 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
922 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
923 !Args.getLastArg(options::OPT_stdlib_EQ))
924 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
927 // Validate the C++ standard library choice.
928 CXXStdlibType Type = GetCXXStdlibType(*DAL);
929 if (Type == ToolChain::CST_Libcxx) {
930 // Check whether the target provides libc++.
933 // Complain about targeting iOS < 5.0 in any way.
934 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
937 if (where != StringRef()) {
938 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
946 bool MachO::IsUnwindTablesDefault() const {
947 return getArch() == llvm::Triple::x86_64;
950 bool MachO::UseDwarfDebugFlags() const {
951 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
956 bool Darwin::UseSjLjExceptions() const {
957 // Darwin uses SjLj exceptions on ARM.
958 return (getTriple().getArch() == llvm::Triple::arm ||
959 getTriple().getArch() == llvm::Triple::thumb);
962 bool MachO::isPICDefault() const {
966 bool MachO::isPIEDefault() const {
970 bool MachO::isPICDefaultForced() const {
971 return (getArch() == llvm::Triple::x86_64 ||
972 getArch() == llvm::Triple::aarch64);
975 bool MachO::SupportsProfiling() const {
976 // Profiling instrumentation is only supported on x86.
977 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
980 void Darwin::addMinVersionArgs(const llvm::opt::ArgList &Args,
981 llvm::opt::ArgStringList &CmdArgs) const {
982 VersionTuple TargetVersion = getTargetVersion();
984 if (isTargetIOSSimulator())
985 CmdArgs.push_back("-ios_simulator_version_min");
986 else if (isTargetIOSBased())
987 CmdArgs.push_back("-iphoneos_version_min");
989 assert(isTargetMacOS() && "unexpected target");
990 CmdArgs.push_back("-macosx_version_min");
993 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
996 void Darwin::addStartObjectFileArgs(const llvm::opt::ArgList &Args,
997 llvm::opt::ArgStringList &CmdArgs) const {
998 // Derived from startfile spec.
999 if (Args.hasArg(options::OPT_dynamiclib)) {
1000 // Derived from darwin_dylib1 spec.
1001 if (isTargetIOSSimulator()) {
1002 ; // iOS simulator does not need dylib1.o.
1003 } else if (isTargetIPhoneOS()) {
1004 if (isIPhoneOSVersionLT(3, 1))
1005 CmdArgs.push_back("-ldylib1.o");
1007 if (isMacosxVersionLT(10, 5))
1008 CmdArgs.push_back("-ldylib1.o");
1009 else if (isMacosxVersionLT(10, 6))
1010 CmdArgs.push_back("-ldylib1.10.5.o");
1013 if (Args.hasArg(options::OPT_bundle)) {
1014 if (!Args.hasArg(options::OPT_static)) {
1015 // Derived from darwin_bundle1 spec.
1016 if (isTargetIOSSimulator()) {
1017 ; // iOS simulator does not need bundle1.o.
1018 } else if (isTargetIPhoneOS()) {
1019 if (isIPhoneOSVersionLT(3, 1))
1020 CmdArgs.push_back("-lbundle1.o");
1022 if (isMacosxVersionLT(10, 6))
1023 CmdArgs.push_back("-lbundle1.o");
1027 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1028 if (Args.hasArg(options::OPT_static) ||
1029 Args.hasArg(options::OPT_object) ||
1030 Args.hasArg(options::OPT_preload)) {
1031 CmdArgs.push_back("-lgcrt0.o");
1033 CmdArgs.push_back("-lgcrt1.o");
1035 // darwin_crt2 spec is empty.
1037 // By default on OS X 10.8 and later, we don't link with a crt1.o
1038 // file and the linker knows to use _main as the entry point. But,
1039 // when compiling with -pg, we need to link with the gcrt1.o file,
1040 // so pass the -no_new_main option to tell the linker to use the
1041 // "start" symbol as the entry point.
1042 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1043 CmdArgs.push_back("-no_new_main");
1045 if (Args.hasArg(options::OPT_static) ||
1046 Args.hasArg(options::OPT_object) ||
1047 Args.hasArg(options::OPT_preload)) {
1048 CmdArgs.push_back("-lcrt0.o");
1050 // Derived from darwin_crt1 spec.
1051 if (isTargetIOSSimulator()) {
1052 ; // iOS simulator does not need crt1.o.
1053 } else if (isTargetIPhoneOS()) {
1054 if (getArch() == llvm::Triple::aarch64)
1055 ; // iOS does not need any crt1 files for arm64
1056 else if (isIPhoneOSVersionLT(3, 1))
1057 CmdArgs.push_back("-lcrt1.o");
1058 else if (isIPhoneOSVersionLT(6, 0))
1059 CmdArgs.push_back("-lcrt1.3.1.o");
1061 if (isMacosxVersionLT(10, 5))
1062 CmdArgs.push_back("-lcrt1.o");
1063 else if (isMacosxVersionLT(10, 6))
1064 CmdArgs.push_back("-lcrt1.10.5.o");
1065 else if (isMacosxVersionLT(10, 8))
1066 CmdArgs.push_back("-lcrt1.10.6.o");
1068 // darwin_crt2 spec is empty.
1075 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1076 isMacosxVersionLT(10, 5)) {
1077 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1078 CmdArgs.push_back(Str);
1082 bool Darwin::SupportsObjCGC() const {
1083 return isTargetMacOS();
1086 void Darwin::CheckObjCARC() const {
1087 if (isTargetIOSBased()|| (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1089 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1092 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1093 /// all subcommands; this relies on gcc translating the majority of
1094 /// command line options.
1096 /// \brief Parse a GCCVersion object out of a string of text.
1098 /// This is the primary means of forming GCCVersion objects.
1100 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1101 const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1102 std::pair<StringRef, StringRef> First = VersionText.split('.');
1103 std::pair<StringRef, StringRef> Second = First.second.split('.');
1105 GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1106 if (First.first.getAsInteger(10, GoodVersion.Major) ||
1107 GoodVersion.Major < 0)
1109 GoodVersion.MajorStr = First.first.str();
1110 if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1111 GoodVersion.Minor < 0)
1113 GoodVersion.MinorStr = Second.first.str();
1115 // First look for a number prefix and parse that if present. Otherwise just
1116 // stash the entire patch string in the suffix, and leave the number
1117 // unspecified. This covers versions strings such as:
1123 // And retains any patch number it finds.
1124 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1125 if (!PatchText.empty()) {
1126 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1127 // Try to parse the number and any suffix.
1128 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1129 GoodVersion.Patch < 0)
1131 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1138 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1139 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1141 StringRef RHSPatchSuffix) const {
1142 if (Major != RHSMajor)
1143 return Major < RHSMajor;
1144 if (Minor != RHSMinor)
1145 return Minor < RHSMinor;
1146 if (Patch != RHSPatch) {
1147 // Note that versions without a specified patch sort higher than those with
1154 // Otherwise just sort on the patch itself.
1155 return Patch < RHSPatch;
1157 if (PatchSuffix != RHSPatchSuffix) {
1158 // Sort empty suffixes higher.
1159 if (RHSPatchSuffix.empty())
1161 if (PatchSuffix.empty())
1164 // Provide a lexicographic sort to make this a total ordering.
1165 return PatchSuffix < RHSPatchSuffix;
1168 // The versions are equal.
1172 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1173 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1175 return A->getValue();
1176 return GCC_INSTALL_PREFIX;
1179 /// \brief Initialize a GCCInstallationDetector from the driver.
1181 /// This performs all of the autodetection and sets up the various paths.
1182 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1184 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1185 /// should instead pull the target out of the driver. This is currently
1186 /// necessary because the driver doesn't store the final version of the target
1189 Generic_GCC::GCCInstallationDetector::init(
1190 const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
1191 llvm::Triple BiarchVariantTriple =
1192 TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1193 : TargetTriple.get32BitArchVariant();
1194 // The library directories which may contain GCC installations.
1195 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1196 // The compatible GCC triples for this particular architecture.
1197 SmallVector<StringRef, 16> CandidateTripleAliases;
1198 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1199 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1200 CandidateTripleAliases, CandidateBiarchLibDirs,
1201 CandidateBiarchTripleAliases);
1203 // Compute the set of prefixes for our search.
1204 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1205 D.PrefixDirs.end());
1207 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1208 if (GCCToolchainDir != "") {
1209 if (GCCToolchainDir.back() == '/')
1210 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1212 Prefixes.push_back(GCCToolchainDir);
1214 // If we have a SysRoot, try that first.
1215 if (!D.SysRoot.empty()) {
1216 Prefixes.push_back(D.SysRoot);
1217 Prefixes.push_back(D.SysRoot + "/usr");
1220 // Then look for gcc installed alongside clang.
1221 Prefixes.push_back(D.InstalledDir + "/..");
1223 // And finally in /usr.
1224 if (D.SysRoot.empty())
1225 Prefixes.push_back("/usr");
1228 // Loop over the various components which exist and select the best GCC
1229 // installation available. GCC installs are ranked by version number.
1230 Version = GCCVersion::Parse("0.0.0");
1231 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1232 if (!llvm::sys::fs::exists(Prefixes[i]))
1234 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1235 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1236 if (!llvm::sys::fs::exists(LibDir))
1238 for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1239 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1240 CandidateTripleAliases[k]);
1242 for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1243 const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1244 if (!llvm::sys::fs::exists(LibDir))
1246 for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1248 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1249 CandidateBiarchTripleAliases[k],
1250 /*NeedsBiarchSuffix=*/ true);
1255 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1256 for (const auto &InstallPath : CandidateGCCInstallPaths)
1257 OS << "Found candidate GCC installation: " << InstallPath << "\n";
1259 if (!GCCInstallPath.empty())
1260 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1262 for (const auto &Multilib : Multilibs)
1263 OS << "Candidate multilib: " << Multilib << "\n";
1265 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1266 OS << "Selected multilib: " << SelectedMultilib << "\n";
1269 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1270 if (BiarchSibling.hasValue()) {
1271 M = BiarchSibling.getValue();
1277 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1278 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1279 SmallVectorImpl<StringRef> &LibDirs,
1280 SmallVectorImpl<StringRef> &TripleAliases,
1281 SmallVectorImpl<StringRef> &BiarchLibDirs,
1282 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1283 // Declare a bunch of static data sets that we'll select between below. These
1284 // are specifically designed to always refer to string literals to avoid any
1285 // lifetime or initialization issues.
1286 static const char *const AArch64LibDirs[] = { "/lib64", "/lib" };
1287 static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1288 "aarch64-linux-gnu",
1289 "aarch64-linux-android",
1290 "aarch64-redhat-linux" };
1291 static const char *const AArch64beLibDirs[] = { "/lib" };
1292 static const char *const AArch64beTriples[] = { "aarch64_be-none-linux-gnu",
1293 "aarch64_be-linux-gnu" };
1295 static const char *const ARMLibDirs[] = { "/lib" };
1296 static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1297 "arm-linux-androideabi" };
1298 static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1299 "armv7hl-redhat-linux-gnueabi" };
1300 static const char *const ARMebLibDirs[] = { "/lib" };
1301 static const char *const ARMebTriples[] = { "armeb-linux-gnueabi",
1302 "armeb-linux-androideabi" };
1303 static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
1304 "armebv7hl-redhat-linux-gnueabi" };
1306 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1307 static const char *const X86_64Triples[] = {
1308 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1309 "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1310 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
1311 "x86_64-linux-android", "x86_64-unknown-linux"
1313 static const char *const X32LibDirs[] = { "/libx32" };
1314 static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1315 static const char *const X86Triples[] = {
1316 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1317 "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1318 "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1319 "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
1322 static const char *const MIPSLibDirs[] = { "/lib" };
1323 static const char *const MIPSTriples[] = { "mips-linux-gnu",
1324 "mips-mti-linux-gnu",
1325 "mips-img-linux-gnu" };
1326 static const char *const MIPSELLibDirs[] = { "/lib" };
1327 static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1328 "mipsel-linux-android",
1329 "mips-img-linux-gnu" };
1331 static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1332 static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
1333 "mips-mti-linux-gnu",
1334 "mips-img-linux-gnu",
1335 "mips64-linux-gnuabi64" };
1336 static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1337 static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
1338 "mips-mti-linux-gnu",
1339 "mips-img-linux-gnu",
1340 "mips64el-linux-android",
1341 "mips64el-linux-gnuabi64" };
1343 static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1344 static const char *const PPCTriples[] = {
1345 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1346 "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1348 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1349 static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1350 "powerpc64-unknown-linux-gnu",
1351 "powerpc64-suse-linux",
1352 "ppc64-redhat-linux" };
1353 static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
1354 static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
1355 "powerpc64le-unknown-linux-gnu",
1356 "powerpc64le-suse-linux",
1357 "ppc64le-redhat-linux" };
1359 static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
1360 static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
1361 "sparcv8-linux-gnu" };
1362 static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
1363 static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
1364 "sparcv9-linux-gnu" };
1366 static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1367 static const char *const SystemZTriples[] = {
1368 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1369 "s390x-suse-linux", "s390x-redhat-linux"
1375 switch (TargetTriple.getArch()) {
1376 case llvm::Triple::aarch64:
1377 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1378 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1379 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1380 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1382 case llvm::Triple::aarch64_be:
1383 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1384 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1385 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1386 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1388 case llvm::Triple::arm:
1389 case llvm::Triple::thumb:
1390 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1391 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1392 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1394 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1397 case llvm::Triple::armeb:
1398 case llvm::Triple::thumbeb:
1399 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1400 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1401 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1403 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1406 case llvm::Triple::x86_64:
1407 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1408 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1409 // x32 is always available when x86_64 is available, so adding it as
1410 // secondary arch with x86_64 triples
1411 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1412 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1413 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1415 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1416 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1419 case llvm::Triple::x86:
1420 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1421 TripleAliases.append(begin(X86Triples), end(X86Triples));
1422 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1423 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1425 case llvm::Triple::mips:
1426 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1427 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1428 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1429 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1431 case llvm::Triple::mipsel:
1432 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1433 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1434 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1435 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1436 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1438 case llvm::Triple::mips64:
1439 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1440 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1441 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1442 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1444 case llvm::Triple::mips64el:
1445 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1446 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1447 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1448 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1449 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1451 case llvm::Triple::ppc:
1452 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1453 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1454 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1455 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1457 case llvm::Triple::ppc64:
1458 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1459 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1460 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1461 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1463 case llvm::Triple::ppc64le:
1464 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1465 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1467 case llvm::Triple::sparc:
1468 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1469 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1470 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1471 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1473 case llvm::Triple::sparcv9:
1474 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1475 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1476 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1477 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1479 case llvm::Triple::systemz:
1480 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1481 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1485 // By default, just rely on the standard lib directories and the original
1490 // Always append the drivers target triple to the end, in case it doesn't
1491 // match any of our aliases.
1492 TripleAliases.push_back(TargetTriple.str());
1494 // Also include the multiarch variant if it's different.
1495 if (TargetTriple.str() != BiarchTriple.str())
1496 BiarchTripleAliases.push_back(BiarchTriple.str());
1500 // Filter to remove Multilibs that don't exist as a suffix to Path
1501 class FilterNonExistent : public MultilibSet::FilterCallback {
1504 FilterNonExistent(std::string Base) : Base(Base) {}
1505 bool operator()(const Multilib &M) const override {
1506 return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
1509 } // end anonymous namespace
1511 static void addMultilibFlag(bool Enabled, const char *const Flag,
1512 std::vector<std::string> &Flags) {
1514 Flags.push_back(std::string("+") + Flag);
1516 Flags.push_back(std::string("-") + Flag);
1519 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1520 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1521 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1524 static bool isMips32(llvm::Triple::ArchType Arch) {
1525 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1528 static bool isMips64(llvm::Triple::ArchType Arch) {
1529 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1532 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1533 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1536 static bool isMips16(const ArgList &Args) {
1537 Arg *A = Args.getLastArg(options::OPT_mips16,
1538 options::OPT_mno_mips16);
1539 return A && A->getOption().matches(options::OPT_mips16);
1542 static bool isMicroMips(const ArgList &Args) {
1543 Arg *A = Args.getLastArg(options::OPT_mmicromips,
1544 options::OPT_mno_micromips);
1545 return A && A->getOption().matches(options::OPT_mmicromips);
1548 struct DetectedMultilibs {
1549 /// The set of multilibs that the detected installation supports.
1550 MultilibSet Multilibs;
1552 /// The primary multilib appropriate for the given flags.
1553 Multilib SelectedMultilib;
1555 /// On Biarch systems, this corresponds to the default multilib when
1556 /// targeting the non-default multilib. Otherwise, it is empty.
1557 llvm::Optional<Multilib> BiarchSibling;
1560 static Multilib makeMultilib(StringRef commonSuffix) {
1561 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1564 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
1565 const llvm::opt::ArgList &Args,
1566 DetectedMultilibs &Result) {
1567 // Some MIPS toolchains put libraries and object files compiled
1568 // using different options in to the sub-directoris which names
1569 // reflects the flags used for compilation. For example sysroot
1570 // directory might looks like the following examples:
1573 // /lib <= crt*.o files compiled with '-mips32'
1576 // /lib <= crt*.o files compiled with '-mips16'
1579 // /lib <= crt*.o files compiled with '-mips16 -EL'
1584 // /lib <= crt*.o files compiled with '-mips32r2'
1587 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1590 // /lib <= crt*.o files compiled with '-mips32'
1592 FilterNonExistent NonExistent(Path);
1594 // Check for FSF toolchain multilibs
1595 MultilibSet FSFMipsMultilibs;
1597 auto MArchMips32 = makeMultilib("/mips32")
1598 .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32");
1600 auto MArchMicroMips = makeMultilib("/micromips")
1601 .flag("+m32").flag("-m64").flag("+mmicromips");
1603 auto MArchMips64r2 = makeMultilib("/mips64r2")
1604 .flag("-m32").flag("+m64").flag("+march=mips64r2");
1606 auto MArchMips64 = makeMultilib("/mips64")
1607 .flag("-m32").flag("+m64").flag("-march=mips64r2");
1609 auto MArchDefault = makeMultilib("")
1610 .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32r2");
1612 auto Mips16 = makeMultilib("/mips16")
1615 auto UCLibc = makeMultilib("/uclibc")
1618 auto MAbi64 = makeMultilib("/64")
1619 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1621 auto BigEndian = makeMultilib("")
1622 .flag("+EB").flag("-EL");
1624 auto LittleEndian = makeMultilib("/el")
1625 .flag("+EL").flag("-EB");
1627 auto SoftFloat = makeMultilib("/sof")
1628 .flag("+msoft-float");
1630 auto Nan2008 = makeMultilib("/nan2008")
1631 .flag("+mnan=2008");
1633 FSFMipsMultilibs = MultilibSet()
1634 .Either(MArchMips32, MArchMicroMips,
1635 MArchMips64r2, MArchMips64, MArchDefault)
1638 .FilterOut("/mips64/mips16")
1639 .FilterOut("/mips64r2/mips16")
1640 .FilterOut("/micromips/mips16")
1642 .FilterOut("/micromips/64")
1643 .FilterOut("/mips32/64")
1645 .FilterOut("/mips16/64")
1646 .Either(BigEndian, LittleEndian)
1649 .FilterOut(".*sof/nan2008")
1650 .FilterOut(NonExistent)
1651 .setIncludeDirsCallback([](
1652 StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1653 std::vector<std::string> Dirs;
1654 Dirs.push_back((InstallDir + "/include").str());
1655 std::string SysRootInc = InstallDir.str() + "/../../../../sysroot";
1656 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1657 Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1659 Dirs.push_back(SysRootInc + "/usr/include");
1664 // Check for Code Sourcery toolchain multilibs
1665 MultilibSet CSMipsMultilibs;
1667 auto MArchMips16 = makeMultilib("/mips16")
1668 .flag("+m32").flag("+mips16");
1670 auto MArchMicroMips = makeMultilib("/micromips")
1671 .flag("+m32").flag("+mmicromips");
1673 auto MArchDefault = makeMultilib("")
1674 .flag("-mips16").flag("-mmicromips");
1676 auto UCLibc = makeMultilib("/uclibc")
1679 auto SoftFloat = makeMultilib("/soft-float")
1680 .flag("+msoft-float");
1682 auto Nan2008 = makeMultilib("/nan2008")
1683 .flag("+mnan=2008");
1685 auto DefaultFloat = makeMultilib("")
1686 .flag("-msoft-float").flag("-mnan=2008");
1688 auto BigEndian = makeMultilib("")
1689 .flag("+EB").flag("-EL");
1691 auto LittleEndian = makeMultilib("/el")
1692 .flag("+EL").flag("-EB");
1694 // Note that this one's osSuffix is ""
1695 auto MAbi64 = makeMultilib("")
1697 .includeSuffix("/64")
1698 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1700 CSMipsMultilibs = MultilibSet()
1701 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1703 .Either(SoftFloat, Nan2008, DefaultFloat)
1704 .FilterOut("/micromips/nan2008")
1705 .FilterOut("/mips16/nan2008")
1706 .Either(BigEndian, LittleEndian)
1708 .FilterOut("/mips16.*/64")
1709 .FilterOut("/micromips.*/64")
1710 .FilterOut(NonExistent)
1711 .setIncludeDirsCallback([](
1712 StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1713 std::vector<std::string> Dirs;
1714 Dirs.push_back((InstallDir + "/include").str());
1715 std::string SysRootInc =
1716 InstallDir.str() + "/../../../../" + TripleStr.str();
1717 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1718 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1720 Dirs.push_back(SysRootInc + "/libc/usr/include");
1725 MultilibSet AndroidMipsMultilibs = MultilibSet()
1726 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1727 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1728 .FilterOut(NonExistent);
1730 MultilibSet DebianMipsMultilibs;
1732 Multilib MAbiN32 = Multilib()
1734 .includeSuffix("/n32")
1737 Multilib M64 = Multilib()
1739 .includeSuffix("/64")
1740 .flag("+m64").flag("-m32").flag("-mabi=n32");
1742 Multilib M32 = Multilib()
1743 .flag("-m64").flag("+m32").flag("-mabi=n32");
1745 DebianMipsMultilibs = MultilibSet()
1746 .Either(M32, M64, MAbiN32)
1747 .FilterOut(NonExistent);
1750 MultilibSet ImgMultilibs;
1752 auto Mips64r6 = makeMultilib("/mips64r6")
1753 .flag("+m64").flag("-m32");
1755 auto LittleEndian = makeMultilib("/el")
1756 .flag("+EL").flag("-EB");
1758 auto MAbi64 = makeMultilib("/64")
1759 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1761 ImgMultilibs = MultilibSet()
1764 .Maybe(LittleEndian)
1765 .FilterOut(NonExistent)
1766 .setIncludeDirsCallback([](
1767 StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1768 std::vector<std::string> Dirs;
1769 Dirs.push_back((InstallDir + "/include").str());
1770 Dirs.push_back((InstallDir + "/../../../../sysroot/usr/include").str());
1777 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1779 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1781 Multilib::flags_list Flags;
1782 addMultilibFlag(isMips32(TargetArch), "m32", Flags);
1783 addMultilibFlag(isMips64(TargetArch), "m64", Flags);
1784 addMultilibFlag(isMips16(Args), "mips16", Flags);
1785 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1786 addMultilibFlag(CPUName == "mips32r2", "march=mips32r2", Flags);
1787 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1788 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1789 addMultilibFlag(CPUName == "mips64r2" || CPUName == "octeon",
1790 "march=mips64r2", Flags);
1791 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1792 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1793 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1795 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1796 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1797 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1798 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1799 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1800 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1802 if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
1803 // Select Android toolchain. It's the only choice in that case.
1804 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1805 Result.Multilibs = AndroidMipsMultilibs;
1811 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1812 TargetTriple.getOS() == llvm::Triple::Linux &&
1813 TargetTriple.getEnvironment() == llvm::Triple::GNU) {
1814 // Select mips-img-linux-gnu toolchain.
1815 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
1816 Result.Multilibs = ImgMultilibs;
1822 // Sort candidates. Toolchain that best meets the directories goes first.
1823 // Then select the first toolchains matches command line flags.
1824 MultilibSet *candidates[] = { &DebianMipsMultilibs, &FSFMipsMultilibs,
1827 std::begin(candidates), std::end(candidates),
1828 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
1829 for (const auto &candidate : candidates) {
1830 if (candidate->select(Flags, Result.SelectedMultilib)) {
1831 if (candidate == &DebianMipsMultilibs)
1832 Result.BiarchSibling = Multilib();
1833 Result.Multilibs = *candidate;
1839 // Fallback to the regular toolchain-tree structure.
1841 Result.Multilibs.push_back(Default);
1842 Result.Multilibs.FilterOut(NonExistent);
1844 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1845 Result.BiarchSibling = Multilib();
1853 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
1854 StringRef Path, const ArgList &Args,
1855 bool NeedsBiarchSuffix,
1856 DetectedMultilibs &Result) {
1858 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1859 // in what would normally be GCCInstallPath and put the 64-bit
1860 // libs in a subdirectory named 64. The simple logic we follow is that
1861 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1862 // we use that. If not, and if not a biarch triple alias, we look for
1863 // crtbegin.o without the subdirectory.
1866 Multilib Alt64 = Multilib()
1868 .includeSuffix("/64")
1869 .flag("-m32").flag("+m64").flag("-mx32");
1870 Multilib Alt32 = Multilib()
1872 .includeSuffix("/32")
1873 .flag("+m32").flag("-m64").flag("-mx32");
1874 Multilib Altx32 = Multilib()
1876 .includeSuffix("/x32")
1877 .flag("-m32").flag("-m64").flag("+mx32");
1879 FilterNonExistent NonExistent(Path);
1881 // Determine default multilib from: 32, 64, x32
1882 // Also handle cases such as 64 on 32, 32 on 64, etc.
1883 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1884 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1885 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1887 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1889 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1892 if (TargetTriple.isArch32Bit())
1893 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1895 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1897 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1901 Default.flag("+m32").flag("-m64").flag("-mx32");
1902 else if (Want == WANT64)
1903 Default.flag("-m32").flag("+m64").flag("-mx32");
1904 else if (Want == WANTX32)
1905 Default.flag("-m32").flag("-m64").flag("+mx32");
1909 Result.Multilibs.push_back(Default);
1910 Result.Multilibs.push_back(Alt64);
1911 Result.Multilibs.push_back(Alt32);
1912 Result.Multilibs.push_back(Altx32);
1914 Result.Multilibs.FilterOut(NonExistent);
1916 Multilib::flags_list Flags;
1917 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1918 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1919 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1921 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1924 if (Result.SelectedMultilib == Alt64 ||
1925 Result.SelectedMultilib == Alt32 ||
1926 Result.SelectedMultilib == Altx32)
1927 Result.BiarchSibling = Default;
1932 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1933 const llvm::Triple &TargetTriple, const ArgList &Args,
1934 const std::string &LibDir, StringRef CandidateTriple,
1935 bool NeedsBiarchSuffix) {
1936 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1937 // There are various different suffixes involving the triple we
1938 // check for. We also record what is necessary to walk from each back
1939 // up to the lib directory.
1940 const std::string LibSuffixes[] = {
1941 "/gcc/" + CandidateTriple.str(),
1942 // Debian puts cross-compilers in gcc-cross
1943 "/gcc-cross/" + CandidateTriple.str(),
1944 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1946 // The Freescale PPC SDK has the gcc libraries in
1947 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1948 "/" + CandidateTriple.str(),
1950 // Ubuntu has a strange mis-matched pair of triples that this happens to
1952 // FIXME: It may be worthwhile to generalize this and look for a second
1954 "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1956 const std::string InstallSuffixes[] = {
1957 "/../../..", // gcc/
1958 "/../../..", // gcc-cross/
1959 "/../../../..", // <triple>/gcc/
1960 "/../..", // <triple>/
1961 "/../../../.." // i386-linux-gnu/gcc/<triple>/
1963 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1964 const unsigned NumLibSuffixes =
1965 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1966 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1967 StringRef LibSuffix = LibSuffixes[i];
1969 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1970 !EC && LI != LE; LI = LI.increment(EC)) {
1971 StringRef VersionText = llvm::sys::path::filename(LI->path());
1972 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1973 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1974 if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1975 continue; // Saw this path before; no need to look at it again.
1976 if (CandidateVersion.isOlderThan(4, 1, 1))
1978 if (CandidateVersion <= Version)
1981 DetectedMultilibs Detected;
1983 // Debian mips multilibs behave more like the rest of the biarch ones,
1984 // so handle them there
1985 if (isMipsArch(TargetArch)) {
1986 if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
1988 } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
1989 NeedsBiarchSuffix, Detected)) {
1993 Multilibs = Detected.Multilibs;
1994 SelectedMultilib = Detected.SelectedMultilib;
1995 BiarchSibling = Detected.BiarchSibling;
1996 Version = CandidateVersion;
1997 GCCTriple.setTriple(CandidateTriple);
1998 // FIXME: We hack together the directory name here instead of
1999 // using LI to ensure stable path separators across Windows and
2001 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
2002 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
2008 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
2009 const ArgList &Args)
2010 : ToolChain(D, Triple, Args), GCCInstallation() {
2011 getProgramPaths().push_back(getDriver().getInstalledDir());
2012 if (getDriver().getInstalledDir() != getDriver().Dir)
2013 getProgramPaths().push_back(getDriver().Dir);
2016 Generic_GCC::~Generic_GCC() {
2019 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2021 case Action::PreprocessJobClass:
2023 Preprocess.reset(new tools::gcc::Preprocess(*this));
2024 return Preprocess.get();
2025 case Action::CompileJobClass:
2027 Compile.reset(new tools::gcc::Compile(*this));
2028 return Compile.get();
2030 return ToolChain::getTool(AC);
2034 Tool *Generic_GCC::buildAssembler() const {
2035 return new tools::gnutools::Assemble(*this);
2038 Tool *Generic_GCC::buildLinker() const {
2039 return new tools::gcc::Link(*this);
2042 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2043 // Print the information about how we detected the GCC installation.
2044 GCCInstallation.print(OS);
2047 bool Generic_GCC::IsUnwindTablesDefault() const {
2048 return getArch() == llvm::Triple::x86_64;
2051 bool Generic_GCC::isPICDefault() const {
2055 bool Generic_GCC::isPIEDefault() const {
2059 bool Generic_GCC::isPICDefaultForced() const {
2063 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2064 return getTriple().getArch() == llvm::Triple::x86 ||
2065 getTriple().getArch() == llvm::Triple::x86_64 ||
2066 getTriple().getArch() == llvm::Triple::aarch64 ||
2067 getTriple().getArch() == llvm::Triple::aarch64_be ||
2068 getTriple().getArch() == llvm::Triple::arm ||
2069 getTriple().getArch() == llvm::Triple::armeb ||
2070 getTriple().getArch() == llvm::Triple::thumb ||
2071 getTriple().getArch() == llvm::Triple::thumbeb ||
2072 getTriple().getArch() == llvm::Triple::ppc ||
2073 getTriple().getArch() == llvm::Triple::ppc64 ||
2074 getTriple().getArch() == llvm::Triple::ppc64le ||
2075 getTriple().getArch() == llvm::Triple::sparc ||
2076 getTriple().getArch() == llvm::Triple::sparcv9 ||
2077 getTriple().getArch() == llvm::Triple::systemz;
2080 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2081 ArgStringList &CC1Args) const {
2082 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2083 bool UseInitArrayDefault =
2084 getTriple().getArch() == llvm::Triple::aarch64 ||
2085 getTriple().getArch() == llvm::Triple::aarch64_be ||
2086 (getTriple().getOS() == llvm::Triple::Linux &&
2087 (!V.isOlderThan(4, 7, 0) ||
2088 getTriple().getEnvironment() == llvm::Triple::Android));
2090 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2091 options::OPT_fno_use_init_array,
2092 UseInitArrayDefault))
2093 CC1Args.push_back("-fuse-init-array");
2096 /// Hexagon Toolchain
2098 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
2099 const ArgList &Args) {
2101 // Locate the rest of the toolchain ...
2102 std::string GccToolchain = getGCCToolchainDir(Args);
2104 if (!GccToolchain.empty())
2105 return GccToolchain;
2107 std::string InstallRelDir = InstalledDir + "/../../gnu";
2108 if (llvm::sys::fs::exists(InstallRelDir))
2109 return InstallRelDir;
2111 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
2112 if (llvm::sys::fs::exists(PrefixRelDir))
2113 return PrefixRelDir;
2115 return InstallRelDir;
2118 static void GetHexagonLibraryPaths(
2119 const ArgList &Args,
2120 const std::string &Ver,
2121 const std::string &MarchString,
2122 const std::string &InstalledDir,
2123 ToolChain::path_list *LibPaths)
2125 bool buildingLib = Args.hasArg(options::OPT_shared);
2127 //----------------------------------------------------------------------------
2129 //----------------------------------------------------------------------------
2131 it = Args.filtered_begin(options::OPT_L),
2132 ie = Args.filtered_end();
2135 for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
2136 LibPaths->push_back((*it)->getValue(i));
2139 //----------------------------------------------------------------------------
2140 // Other standard paths
2141 //----------------------------------------------------------------------------
2142 const std::string MarchSuffix = "/" + MarchString;
2143 const std::string G0Suffix = "/G0";
2144 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
2145 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
2147 // lib/gcc/hexagon/...
2148 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
2150 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
2151 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
2153 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
2154 LibPaths->push_back(LibGCCHexagonDir + Ver);
2157 LibPaths->push_back(RootDir + "lib/gcc");
2160 std::string HexagonLibDir = RootDir + "hexagon/lib";
2162 LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
2163 LibPaths->push_back(HexagonLibDir + G0Suffix);
2165 LibPaths->push_back(HexagonLibDir + MarchSuffix);
2166 LibPaths->push_back(HexagonLibDir);
2169 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
2170 const ArgList &Args)
2171 : Linux(D, Triple, Args) {
2172 const std::string InstalledDir(getDriver().getInstalledDir());
2173 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
2175 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2177 const std::string BinDir(GnuDir + "/bin");
2178 if (llvm::sys::fs::exists(BinDir))
2179 getProgramPaths().push_back(BinDir);
2181 // Determine version of GCC libraries and headers to use.
2182 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
2184 GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
2185 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
2186 !ec && di != de; di = di.increment(ec)) {
2187 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
2188 if (MaxVersion < cv)
2191 GCCLibAndIncVersion = MaxVersion;
2193 ToolChain::path_list *LibPaths= &getFilePaths();
2195 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2196 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2197 // support 'linux' we'll need to fix this up
2200 GetHexagonLibraryPaths(
2202 GetGCCLibAndIncVersion(),
2208 Hexagon_TC::~Hexagon_TC() {
2211 Tool *Hexagon_TC::buildAssembler() const {
2212 return new tools::hexagon::Assemble(*this);
2215 Tool *Hexagon_TC::buildLinker() const {
2216 return new tools::hexagon::Link(*this);
2219 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2220 ArgStringList &CC1Args) const {
2221 const Driver &D = getDriver();
2223 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2224 DriverArgs.hasArg(options::OPT_nostdlibinc))
2227 std::string Ver(GetGCCLibAndIncVersion());
2228 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
2229 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
2230 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
2231 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
2232 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
2235 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2236 ArgStringList &CC1Args) const {
2238 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2239 DriverArgs.hasArg(options::OPT_nostdincxx))
2242 const Driver &D = getDriver();
2243 std::string Ver(GetGCCLibAndIncVersion());
2244 SmallString<128> IncludeDir(
2245 Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
2247 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
2248 llvm::sys::path::append(IncludeDir, Ver);
2249 addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
2252 ToolChain::CXXStdlibType
2253 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
2254 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2256 return ToolChain::CST_Libstdcxx;
2258 StringRef Value = A->getValue();
2259 if (Value != "libstdc++") {
2260 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2261 << A->getAsString(Args);
2264 return ToolChain::CST_Libstdcxx;
2267 static int getHexagonVersion(const ArgList &Args) {
2268 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
2269 // Select the default CPU (v4) if none was given.
2273 // FIXME: produce errors if we cannot parse the version.
2274 StringRef WhichHexagon = A->getValue();
2275 if (WhichHexagon.startswith("hexagonv")) {
2277 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
2280 if (WhichHexagon.startswith("v")) {
2282 if (!WhichHexagon.substr(1).getAsInteger(10, Val))
2286 // FIXME: should probably be an error.
2290 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
2292 int V = getHexagonVersion(Args);
2293 // FIXME: We don't support versions < 4. We should error on them.
2296 llvm_unreachable("Unexpected version");
2311 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2312 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2313 /// Currently does not support anything else but compilation.
2315 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
2316 const ArgList &Args)
2317 : ToolChain(D, Triple, Args) {
2318 // Path mangling to find libexec
2319 std::string Path(getDriver().Dir);
2321 Path += "/../libexec";
2322 getProgramPaths().push_back(Path);
2325 TCEToolChain::~TCEToolChain() {
2328 bool TCEToolChain::IsMathErrnoDefault() const {
2332 bool TCEToolChain::isPICDefault() const {
2336 bool TCEToolChain::isPIEDefault() const {
2340 bool TCEToolChain::isPICDefaultForced() const {
2344 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2346 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2347 : Generic_ELF(D, Triple, Args) {
2348 getFilePaths().push_back(getDriver().Dir + "/../lib");
2349 getFilePaths().push_back("/usr/lib");
2352 Tool *OpenBSD::buildAssembler() const {
2353 return new tools::openbsd::Assemble(*this);
2356 Tool *OpenBSD::buildLinker() const {
2357 return new tools::openbsd::Link(*this);
2360 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2362 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2363 : Generic_ELF(D, Triple, Args) {
2364 getFilePaths().push_back(getDriver().Dir + "/../lib");
2365 getFilePaths().push_back("/usr/lib");
2368 Tool *Bitrig::buildAssembler() const {
2369 return new tools::bitrig::Assemble(*this);
2372 Tool *Bitrig::buildLinker() const {
2373 return new tools::bitrig::Link(*this);
2376 ToolChain::CXXStdlibType
2377 Bitrig::GetCXXStdlibType(const ArgList &Args) const {
2378 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2379 StringRef Value = A->getValue();
2380 if (Value == "libstdc++")
2381 return ToolChain::CST_Libstdcxx;
2382 if (Value == "libc++")
2383 return ToolChain::CST_Libcxx;
2385 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2386 << A->getAsString(Args);
2388 return ToolChain::CST_Libcxx;
2391 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2392 ArgStringList &CC1Args) const {
2393 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2394 DriverArgs.hasArg(options::OPT_nostdincxx))
2397 switch (GetCXXStdlibType(DriverArgs)) {
2398 case ToolChain::CST_Libcxx:
2399 addSystemInclude(DriverArgs, CC1Args,
2400 getDriver().SysRoot + "/usr/include/c++/v1");
2402 case ToolChain::CST_Libstdcxx:
2403 addSystemInclude(DriverArgs, CC1Args,
2404 getDriver().SysRoot + "/usr/include/c++/stdc++");
2405 addSystemInclude(DriverArgs, CC1Args,
2406 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
2408 StringRef Triple = getTriple().str();
2409 if (Triple.startswith("amd64"))
2410 addSystemInclude(DriverArgs, CC1Args,
2411 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
2414 addSystemInclude(DriverArgs, CC1Args,
2415 getDriver().SysRoot + "/usr/include/c++/stdc++/" +
2421 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
2422 ArgStringList &CmdArgs) const {
2423 switch (GetCXXStdlibType(Args)) {
2424 case ToolChain::CST_Libcxx:
2425 CmdArgs.push_back("-lc++");
2426 CmdArgs.push_back("-lc++abi");
2427 CmdArgs.push_back("-lpthread");
2429 case ToolChain::CST_Libstdcxx:
2430 CmdArgs.push_back("-lstdc++");
2435 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
2437 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2438 : Generic_ELF(D, Triple, Args) {
2440 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
2441 // back to '/usr/lib' if it doesn't exist.
2442 if ((Triple.getArch() == llvm::Triple::x86 ||
2443 Triple.getArch() == llvm::Triple::ppc) &&
2444 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
2445 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2447 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2450 ToolChain::CXXStdlibType
2451 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2452 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2453 StringRef Value = A->getValue();
2454 if (Value == "libstdc++")
2455 return ToolChain::CST_Libstdcxx;
2456 if (Value == "libc++")
2457 return ToolChain::CST_Libcxx;
2459 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2460 << A->getAsString(Args);
2462 if (getTriple().getOSMajorVersion() >= 10)
2463 return ToolChain::CST_Libcxx;
2464 return ToolChain::CST_Libstdcxx;
2467 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2468 ArgStringList &CC1Args) const {
2469 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2470 DriverArgs.hasArg(options::OPT_nostdincxx))
2473 switch (GetCXXStdlibType(DriverArgs)) {
2474 case ToolChain::CST_Libcxx:
2475 addSystemInclude(DriverArgs, CC1Args,
2476 getDriver().SysRoot + "/usr/include/c++/v1");
2478 case ToolChain::CST_Libstdcxx:
2479 addSystemInclude(DriverArgs, CC1Args,
2480 getDriver().SysRoot + "/usr/include/c++/4.2");
2481 addSystemInclude(DriverArgs, CC1Args,
2482 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2487 Tool *FreeBSD::buildAssembler() const {
2488 return new tools::freebsd::Assemble(*this);
2491 Tool *FreeBSD::buildLinker() const {
2492 return new tools::freebsd::Link(*this);
2495 bool FreeBSD::UseSjLjExceptions() const {
2496 // FreeBSD uses SjLj exceptions on ARM oabi.
2497 switch (getTriple().getEnvironment()) {
2498 case llvm::Triple::GNUEABIHF:
2499 case llvm::Triple::GNUEABI:
2500 case llvm::Triple::EABI:
2504 return (getTriple().getArch() == llvm::Triple::arm ||
2505 getTriple().getArch() == llvm::Triple::thumb);
2509 bool FreeBSD::HasNativeLLVMSupport() const {
2513 bool FreeBSD::isPIEDefault() const {
2514 return getSanitizerArgs().requiresPIE();
2517 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2519 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2520 : Generic_ELF(D, Triple, Args) {
2522 if (getDriver().UseStdLib) {
2523 // When targeting a 32-bit platform, try the special directory used on
2524 // 64-bit hosts, and only fall back to the main library directory if that
2526 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2527 // what all logic is needed to emulate the '=' prefix here.
2528 switch (Triple.getArch()) {
2529 case llvm::Triple::x86:
2530 getFilePaths().push_back("=/usr/lib/i386");
2532 case llvm::Triple::arm:
2533 case llvm::Triple::armeb:
2534 case llvm::Triple::thumb:
2535 case llvm::Triple::thumbeb:
2536 switch (Triple.getEnvironment()) {
2537 case llvm::Triple::EABI:
2538 case llvm::Triple::GNUEABI:
2539 getFilePaths().push_back("=/usr/lib/eabi");
2541 case llvm::Triple::EABIHF:
2542 case llvm::Triple::GNUEABIHF:
2543 getFilePaths().push_back("=/usr/lib/eabihf");
2546 getFilePaths().push_back("=/usr/lib/oabi");
2550 case llvm::Triple::mips64:
2551 case llvm::Triple::mips64el:
2552 if (tools::mips::hasMipsAbiArg(Args, "o32"))
2553 getFilePaths().push_back("=/usr/lib/o32");
2554 else if (tools::mips::hasMipsAbiArg(Args, "64"))
2555 getFilePaths().push_back("=/usr/lib/64");
2557 case llvm::Triple::ppc:
2558 getFilePaths().push_back("=/usr/lib/powerpc");
2560 case llvm::Triple::sparc:
2561 getFilePaths().push_back("=/usr/lib/sparc");
2567 getFilePaths().push_back("=/usr/lib");
2571 Tool *NetBSD::buildAssembler() const {
2572 return new tools::netbsd::Assemble(*this);
2575 Tool *NetBSD::buildLinker() const {
2576 return new tools::netbsd::Link(*this);
2579 ToolChain::CXXStdlibType
2580 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2581 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2582 StringRef Value = A->getValue();
2583 if (Value == "libstdc++")
2584 return ToolChain::CST_Libstdcxx;
2585 if (Value == "libc++")
2586 return ToolChain::CST_Libcxx;
2588 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2589 << A->getAsString(Args);
2592 unsigned Major, Minor, Micro;
2593 getTriple().getOSVersion(Major, Minor, Micro);
2594 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
2595 switch (getArch()) {
2596 case llvm::Triple::aarch64:
2597 case llvm::Triple::arm:
2598 case llvm::Triple::armeb:
2599 case llvm::Triple::thumb:
2600 case llvm::Triple::thumbeb:
2601 case llvm::Triple::ppc:
2602 case llvm::Triple::ppc64:
2603 case llvm::Triple::ppc64le:
2604 case llvm::Triple::x86:
2605 case llvm::Triple::x86_64:
2606 return ToolChain::CST_Libcxx;
2611 return ToolChain::CST_Libstdcxx;
2614 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2615 ArgStringList &CC1Args) const {
2616 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2617 DriverArgs.hasArg(options::OPT_nostdincxx))
2620 switch (GetCXXStdlibType(DriverArgs)) {
2621 case ToolChain::CST_Libcxx:
2622 addSystemInclude(DriverArgs, CC1Args,
2623 getDriver().SysRoot + "/usr/include/c++/");
2625 case ToolChain::CST_Libstdcxx:
2626 addSystemInclude(DriverArgs, CC1Args,
2627 getDriver().SysRoot + "/usr/include/g++");
2628 addSystemInclude(DriverArgs, CC1Args,
2629 getDriver().SysRoot + "/usr/include/g++/backward");
2634 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2636 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2637 : Generic_ELF(D, Triple, Args) {
2638 getFilePaths().push_back(getDriver().Dir + "/../lib");
2639 getFilePaths().push_back("/usr/lib");
2642 Tool *Minix::buildAssembler() const {
2643 return new tools::minix::Assemble(*this);
2646 Tool *Minix::buildLinker() const {
2647 return new tools::minix::Link(*this);
2650 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2652 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2653 const ArgList &Args)
2654 : Generic_GCC(D, Triple, Args) {
2656 getProgramPaths().push_back(getDriver().getInstalledDir());
2657 if (getDriver().getInstalledDir() != getDriver().Dir)
2658 getProgramPaths().push_back(getDriver().Dir);
2660 getFilePaths().push_back(getDriver().Dir + "/../lib");
2661 getFilePaths().push_back("/usr/lib");
2664 Tool *Solaris::buildAssembler() const {
2665 return new tools::solaris::Assemble(*this);
2668 Tool *Solaris::buildLinker() const {
2669 return new tools::solaris::Link(*this);
2672 /// Distribution (very bare-bones at the moment).
2702 static bool IsRedhat(enum Distro Distro) {
2703 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
2706 static bool IsOpenSUSE(enum Distro Distro) {
2707 return Distro == OpenSUSE;
2710 static bool IsDebian(enum Distro Distro) {
2711 return Distro >= DebianLenny && Distro <= DebianJessie;
2714 static bool IsUbuntu(enum Distro Distro) {
2715 return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
2718 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2719 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2720 llvm::MemoryBuffer::getFile("/etc/lsb-release");
2722 StringRef Data = File.get()->getBuffer();
2723 SmallVector<StringRef, 16> Lines;
2724 Data.split(Lines, "\n");
2725 Distro Version = UnknownDistro;
2726 for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2727 if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2728 Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2729 .Case("hardy", UbuntuHardy)
2730 .Case("intrepid", UbuntuIntrepid)
2731 .Case("jaunty", UbuntuJaunty)
2732 .Case("karmic", UbuntuKarmic)
2733 .Case("lucid", UbuntuLucid)
2734 .Case("maverick", UbuntuMaverick)
2735 .Case("natty", UbuntuNatty)
2736 .Case("oneiric", UbuntuOneiric)
2737 .Case("precise", UbuntuPrecise)
2738 .Case("quantal", UbuntuQuantal)
2739 .Case("raring", UbuntuRaring)
2740 .Case("saucy", UbuntuSaucy)
2741 .Case("trusty", UbuntuTrusty)
2742 .Default(UnknownDistro);
2746 File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
2748 StringRef Data = File.get()->getBuffer();
2749 if (Data.startswith("Fedora release"))
2751 if (Data.startswith("Red Hat Enterprise Linux") ||
2752 Data.startswith("CentOS")) {
2753 if (Data.find("release 6") != StringRef::npos)
2755 else if (Data.find("release 5") != StringRef::npos)
2757 else if (Data.find("release 4") != StringRef::npos)
2760 return UnknownDistro;
2763 File = llvm::MemoryBuffer::getFile("/etc/debian_version");
2765 StringRef Data = File.get()->getBuffer();
2768 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2769 return DebianSqueeze;
2770 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
2771 return DebianWheezy;
2772 else if (Data.startswith("jessie/sid") || Data[0] == '8')
2773 return DebianJessie;
2774 return UnknownDistro;
2777 if (llvm::sys::fs::exists("/etc/SuSE-release"))
2780 if (llvm::sys::fs::exists("/etc/exherbo-release"))
2783 if (llvm::sys::fs::exists("/etc/arch-release"))
2786 return UnknownDistro;
2789 /// \brief Get our best guess at the multiarch triple for a target.
2791 /// Debian-based systems are starting to use a multiarch setup where they use
2792 /// a target-triple directory in the library and header search paths.
2793 /// Unfortunately, this triple does not align with the vanilla target triple,
2794 /// so we provide a rough mapping here.
2795 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
2796 StringRef SysRoot) {
2797 // For most architectures, just use whatever we have rather than trying to be
2799 switch (TargetTriple.getArch()) {
2801 return TargetTriple.str();
2803 // We use the existence of '/lib/<triple>' as a directory to detect some
2804 // common linux triples that don't quite match the Clang triple for both
2805 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2806 // regardless of what the actual target triple is.
2807 case llvm::Triple::arm:
2808 case llvm::Triple::thumb:
2809 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2810 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2811 return "arm-linux-gnueabihf";
2813 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2814 return "arm-linux-gnueabi";
2816 return TargetTriple.str();
2817 case llvm::Triple::armeb:
2818 case llvm::Triple::thumbeb:
2819 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2820 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
2821 return "armeb-linux-gnueabihf";
2823 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
2824 return "armeb-linux-gnueabi";
2826 return TargetTriple.str();
2827 case llvm::Triple::x86:
2828 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2829 return "i386-linux-gnu";
2830 return TargetTriple.str();
2831 case llvm::Triple::x86_64:
2832 // We don't want this for x32, otherwise it will match x86_64 libs
2833 if (TargetTriple.getEnvironment() != llvm::Triple::GNUX32 &&
2834 llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2835 return "x86_64-linux-gnu";
2836 return TargetTriple.str();
2837 case llvm::Triple::aarch64:
2838 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2839 return "aarch64-linux-gnu";
2840 return TargetTriple.str();
2841 case llvm::Triple::aarch64_be:
2842 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
2843 return "aarch64_be-linux-gnu";
2844 return TargetTriple.str();
2845 case llvm::Triple::mips:
2846 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2847 return "mips-linux-gnu";
2848 return TargetTriple.str();
2849 case llvm::Triple::mipsel:
2850 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2851 return "mipsel-linux-gnu";
2852 return TargetTriple.str();
2853 case llvm::Triple::mips64:
2854 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
2855 return "mips64-linux-gnu";
2856 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
2857 return "mips64-linux-gnuabi64";
2858 return TargetTriple.str();
2859 case llvm::Triple::mips64el:
2860 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
2861 return "mips64el-linux-gnu";
2862 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
2863 return "mips64el-linux-gnuabi64";
2864 return TargetTriple.str();
2865 case llvm::Triple::ppc:
2866 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2867 return "powerpc-linux-gnuspe";
2868 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2869 return "powerpc-linux-gnu";
2870 return TargetTriple.str();
2871 case llvm::Triple::ppc64:
2872 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2873 return "powerpc64-linux-gnu";
2874 case llvm::Triple::ppc64le:
2875 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
2876 return "powerpc64le-linux-gnu";
2877 return TargetTriple.str();
2881 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2882 if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2885 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
2886 if (isMipsArch(Triple.getArch())) {
2887 // lib32 directory has a special meaning on MIPS targets.
2888 // It contains N32 ABI binaries. Use this folder if produce
2889 // code for N32 ABI only.
2890 if (tools::mips::hasMipsAbiArg(Args, "n32"))
2892 return Triple.isArch32Bit() ? "lib" : "lib64";
2895 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
2896 // using that variant while targeting other architectures causes problems
2897 // because the libraries are laid out in shared system roots that can't cope
2898 // with a 'lib32' library search path being considered. So we only enable
2899 // them when we know we may need it.
2901 // FIXME: This is a bit of a hack. We should really unify this code for
2902 // reasoning about oslibdir spellings with the lib dir spellings in the
2903 // GCCInstallationDetector, but that is a more significant refactoring.
2904 if (Triple.getArch() == llvm::Triple::x86 ||
2905 Triple.getArch() == llvm::Triple::ppc)
2908 if (Triple.getArch() == llvm::Triple::x86_64 &&
2909 Triple.getEnvironment() == llvm::Triple::GNUX32)
2912 return Triple.isArch32Bit() ? "lib" : "lib64";
2915 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2916 : Generic_ELF(D, Triple, Args) {
2917 GCCInstallation.init(D, Triple, Args);
2918 Multilibs = GCCInstallation.getMultilibs();
2919 llvm::Triple::ArchType Arch = Triple.getArch();
2920 std::string SysRoot = computeSysRoot();
2922 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2923 // least) put various tools in a triple-prefixed directory off of the parent
2924 // of the GCC installation. We use the GCC triple here to ensure that we end
2925 // up with tools that support the same amount of cross compiling as the
2926 // detected GCC installation. For example, if we find a GCC installation
2927 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2928 // used to target i386.
2929 // FIXME: This seems unlikely to be Linux-specific.
2930 ToolChain::path_list &PPaths = getProgramPaths();
2931 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2932 GCCInstallation.getTriple().str() + "/bin").str());
2934 Linker = GetLinkerPath();
2936 Distro Distro = DetectDistro(Arch);
2938 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2939 ExtraOpts.push_back("-z");
2940 ExtraOpts.push_back("relro");
2943 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2944 ExtraOpts.push_back("-X");
2946 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2947 const bool IsMips = isMipsArch(Arch);
2949 if (IsMips && !SysRoot.empty())
2950 ExtraOpts.push_back("--sysroot=" + SysRoot);
2952 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2953 // and the MIPS ABI require .dynsym to be sorted in different ways.
2954 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2955 // ABI requires a mapping between the GOT and the symbol table.
2956 // Android loader does not support .gnu.hash.
2957 if (!IsMips && !IsAndroid) {
2958 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2959 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2960 ExtraOpts.push_back("--hash-style=gnu");
2962 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2963 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2964 ExtraOpts.push_back("--hash-style=both");
2967 if (IsRedhat(Distro))
2968 ExtraOpts.push_back("--no-add-needed");
2970 if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2971 Distro == DebianJessie || IsOpenSUSE(Distro) ||
2972 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2973 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2974 ExtraOpts.push_back("--build-id");
2976 if (IsOpenSUSE(Distro))
2977 ExtraOpts.push_back("--enable-new-dtags");
2979 // The selection of paths to try here is designed to match the patterns which
2980 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2981 // This was determined by running GCC in a fake filesystem, creating all
2982 // possible permutations of these directories, and seeing which ones it added
2983 // to the link paths.
2984 path_list &Paths = getFilePaths();
2986 const std::string OSLibDir = getOSLibDir(Triple, Args);
2987 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2989 // Add the multilib suffixed paths where they are available.
2990 if (GCCInstallation.isValid()) {
2991 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2992 const std::string &LibPath = GCCInstallation.getParentLibPath();
2993 const Multilib &Multilib = GCCInstallation.getMultilib();
2995 // Sourcery CodeBench MIPS toolchain holds some libraries under
2996 // a biarch-like suffix of the GCC installation.
2997 addPathIfExists((GCCInstallation.getInstallPath() +
2998 Multilib.gccSuffix()),
3001 // GCC cross compiling toolchains will install target libraries which ship
3002 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3003 // any part of the GCC installation in
3004 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3005 // debatable, but is the reality today. We need to search this tree even
3006 // when we have a sysroot somewhere else. It is the responsibility of
3007 // whomever is doing the cross build targeting a sysroot using a GCC
3008 // installation that is *not* within the system root to ensure two things:
3010 // 1) Any DSOs that are linked in from this tree or from the install path
3011 // above must be present on the system root and found via an
3012 // appropriate rpath.
3013 // 2) There must not be libraries installed into
3014 // <prefix>/<triple>/<libdir> unless they should be preferred over
3015 // those within the system root.
3017 // Note that this matches the GCC behavior. See the below comment for where
3018 // Clang diverges from GCC's behavior.
3019 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3020 Multilib.osSuffix(),
3023 // If the GCC installation we found is inside of the sysroot, we want to
3024 // prefer libraries installed in the parent prefix of the GCC installation.
3025 // It is important to *not* use these paths when the GCC installation is
3026 // outside of the system root as that can pick up unintended libraries.
3027 // This usually happens when there is an external cross compiler on the
3028 // host system, and a more minimal sysroot available that is the target of
3029 // the cross. Note that GCC does include some of these directories in some
3030 // configurations but this seems somewhere between questionable and simply
3032 if (StringRef(LibPath).startswith(SysRoot)) {
3033 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
3034 addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
3038 // Similar to the logic for GCC above, if we currently running Clang inside
3039 // of the requested system root, add its parent library paths to
3041 // FIXME: It's not clear whether we should use the driver's installed
3042 // directory ('Dir' below) or the ResourceDir.
3043 if (StringRef(D.Dir).startswith(SysRoot)) {
3044 addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
3045 addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
3048 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
3049 addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
3050 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3051 addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3053 // Try walking via the GCC triple path in case of biarch or multiarch GCC
3054 // installations with strange symlinks.
3055 if (GCCInstallation.isValid()) {
3056 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3057 "/../../" + OSLibDir, Paths);
3059 // Add the 'other' biarch variant path
3060 Multilib BiarchSibling;
3061 if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3062 addPathIfExists(GCCInstallation.getInstallPath() +
3063 BiarchSibling.gccSuffix(), Paths);
3066 // See comments above on the multilib variant for details of why this is
3067 // included even from outside the sysroot.
3068 const std::string &LibPath = GCCInstallation.getParentLibPath();
3069 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3070 const Multilib &Multilib = GCCInstallation.getMultilib();
3071 addPathIfExists(LibPath + "/../" + GCCTriple.str() +
3072 "/lib" + Multilib.osSuffix(), Paths);
3074 // See comments above on the multilib variant for details of why this is
3075 // only included from within the sysroot.
3076 if (StringRef(LibPath).startswith(SysRoot))
3077 addPathIfExists(LibPath, Paths);
3080 // Similar to the logic for GCC above, if we are currently running Clang
3081 // inside of the requested system root, add its parent library path to those
3083 // FIXME: It's not clear whether we should use the driver's installed
3084 // directory ('Dir' below) or the ResourceDir.
3085 if (StringRef(D.Dir).startswith(SysRoot))
3086 addPathIfExists(D.Dir + "/../lib", Paths);
3088 addPathIfExists(SysRoot + "/lib", Paths);
3089 addPathIfExists(SysRoot + "/usr/lib", Paths);
3092 bool Linux::HasNativeLLVMSupport() const {
3096 Tool *Linux::buildLinker() const {
3097 return new tools::gnutools::Link(*this);
3100 Tool *Linux::buildAssembler() const {
3101 return new tools::gnutools::Assemble(*this);
3104 std::string Linux::computeSysRoot() const {
3105 if (!getDriver().SysRoot.empty())
3106 return getDriver().SysRoot;
3108 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3109 return std::string();
3111 // Standalone MIPS toolchains use different names for sysroot folder
3112 // and put it into different places. Here we try to check some known
3115 const StringRef InstallDir = GCCInstallation.getInstallPath();
3116 const StringRef TripleStr = GCCInstallation.getTriple().str();
3117 const Multilib &Multilib = GCCInstallation.getMultilib();
3119 std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
3120 Multilib.osSuffix()).str();
3122 if (llvm::sys::fs::exists(Path))
3125 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3127 if (llvm::sys::fs::exists(Path))
3130 return std::string();
3133 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3134 ArgStringList &CC1Args) const {
3135 const Driver &D = getDriver();
3136 std::string SysRoot = computeSysRoot();
3138 if (DriverArgs.hasArg(options::OPT_nostdinc))
3141 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3142 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3144 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3145 SmallString<128> P(D.ResourceDir);
3146 llvm::sys::path::append(P, "include");
3147 addSystemInclude(DriverArgs, CC1Args, P.str());
3150 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3153 // Check for configure-time C include directories.
3154 StringRef CIncludeDirs(C_INCLUDE_DIRS);
3155 if (CIncludeDirs != "") {
3156 SmallVector<StringRef, 5> dirs;
3157 CIncludeDirs.split(dirs, ":");
3158 for (StringRef dir : dirs) {
3160 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3161 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3166 // Lacking those, try to detect the correct set of system includes for the
3169 // Add include directories specific to the selected multilib set and multilib.
3170 if (GCCInstallation.isValid()) {
3171 auto Callback = Multilibs.includeDirsCallback();
3173 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3174 GCCInstallation.getTriple().str(),
3175 GCCInstallation.getMultilib());
3176 for (const auto &Path : IncludePaths)
3177 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3181 // Implement generic Debian multiarch support.
3182 const StringRef X86_64MultiarchIncludeDirs[] = {
3183 "/usr/include/x86_64-linux-gnu",
3185 // FIXME: These are older forms of multiarch. It's not clear that they're
3186 // in use in any released version of Debian, so we should consider
3188 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
3190 const StringRef X86MultiarchIncludeDirs[] = {
3191 "/usr/include/i386-linux-gnu",
3193 // FIXME: These are older forms of multiarch. It's not clear that they're
3194 // in use in any released version of Debian, so we should consider
3196 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3197 "/usr/include/i486-linux-gnu"
3199 const StringRef AArch64MultiarchIncludeDirs[] = {
3200 "/usr/include/aarch64-linux-gnu"
3202 const StringRef ARMMultiarchIncludeDirs[] = {
3203 "/usr/include/arm-linux-gnueabi"
3205 const StringRef ARMHFMultiarchIncludeDirs[] = {
3206 "/usr/include/arm-linux-gnueabihf"
3208 const StringRef MIPSMultiarchIncludeDirs[] = {
3209 "/usr/include/mips-linux-gnu"
3211 const StringRef MIPSELMultiarchIncludeDirs[] = {
3212 "/usr/include/mipsel-linux-gnu"
3214 const StringRef MIPS64MultiarchIncludeDirs[] = {
3215 "/usr/include/mips64-linux-gnu",
3216 "/usr/include/mips64-linux-gnuabi64"
3218 const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3219 "/usr/include/mips64el-linux-gnu",
3220 "/usr/include/mips64el-linux-gnuabi64"
3222 const StringRef PPCMultiarchIncludeDirs[] = {
3223 "/usr/include/powerpc-linux-gnu"
3225 const StringRef PPC64MultiarchIncludeDirs[] = {
3226 "/usr/include/powerpc64-linux-gnu"
3228 const StringRef PPC64LEMultiarchIncludeDirs[] = {
3229 "/usr/include/powerpc64le-linux-gnu"
3231 ArrayRef<StringRef> MultiarchIncludeDirs;
3232 if (getTriple().getArch() == llvm::Triple::x86_64) {
3233 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3234 } else if (getTriple().getArch() == llvm::Triple::x86) {
3235 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3236 } else if (getTriple().getArch() == llvm::Triple::aarch64 ||
3237 getTriple().getArch() == llvm::Triple::aarch64_be) {
3238 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3239 } else if (getTriple().getArch() == llvm::Triple::arm) {
3240 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3241 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3243 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3244 } else if (getTriple().getArch() == llvm::Triple::mips) {
3245 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3246 } else if (getTriple().getArch() == llvm::Triple::mipsel) {
3247 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3248 } else if (getTriple().getArch() == llvm::Triple::mips64) {
3249 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3250 } else if (getTriple().getArch() == llvm::Triple::mips64el) {
3251 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3252 } else if (getTriple().getArch() == llvm::Triple::ppc) {
3253 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3254 } else if (getTriple().getArch() == llvm::Triple::ppc64) {
3255 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3256 } else if (getTriple().getArch() == llvm::Triple::ppc64le) {
3257 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3259 for (StringRef Dir : MultiarchIncludeDirs) {
3260 if (llvm::sys::fs::exists(SysRoot + Dir)) {
3261 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
3266 if (getTriple().getOS() == llvm::Triple::RTEMS)
3269 // Add an include of '/include' directly. This isn't provided by default by
3270 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
3271 // add even when Clang is acting as-if it were a system compiler.
3272 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
3274 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
3277 /// \brief Helper to add the variant paths of a libstdc++ installation.
3278 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
3279 StringRef GCCTriple,
3280 StringRef GCCMultiarchTriple,
3281 StringRef TargetMultiarchTriple,
3282 Twine IncludeSuffix,
3283 const ArgList &DriverArgs,
3284 ArgStringList &CC1Args) {
3285 if (!llvm::sys::fs::exists(Base + Suffix))
3288 addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
3290 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
3291 // that path exists or we have neither a GCC nor target multiarch triple, use
3292 // this vanilla search path.
3293 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
3294 llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
3295 addSystemInclude(DriverArgs, CC1Args,
3296 Base + Suffix + "/" + GCCTriple + IncludeSuffix);
3298 // Otherwise try to use multiarch naming schemes which have normalized the
3299 // triples and put the triple before the suffix.
3301 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
3302 // the target triple, so we support that here.
3303 addSystemInclude(DriverArgs, CC1Args,
3304 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
3305 addSystemInclude(DriverArgs, CC1Args,
3306 Base + "/" + TargetMultiarchTriple + Suffix);
3309 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3313 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3314 ArgStringList &CC1Args) const {
3315 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3316 DriverArgs.hasArg(options::OPT_nostdincxx))
3319 // Check if libc++ has been enabled and provide its include paths if so.
3320 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
3321 const std::string LibCXXIncludePathCandidates[] = {
3322 // The primary location is within the Clang installation.
3323 // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
3324 // newer ABI versions.
3325 getDriver().Dir + "/../include/c++/v1",
3327 // We also check the system as for a long time this is the only place Clang looked.
3328 // FIXME: We should really remove this. It doesn't make any sense.
3329 getDriver().SysRoot + "/usr/include/c++/v1"
3331 for (const auto &IncludePath : LibCXXIncludePathCandidates) {
3332 if (!llvm::sys::fs::exists(IncludePath))
3334 // Add the first candidate that exists.
3335 addSystemInclude(DriverArgs, CC1Args, IncludePath);
3341 // We need a detected GCC installation on Linux to provide libstdc++'s
3342 // headers. We handled the libc++ case above.
3343 if (!GCCInstallation.isValid())
3346 // By default, look for the C++ headers in an include directory adjacent to
3347 // the lib directory of the GCC installation. Note that this is expect to be
3348 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3349 StringRef LibDir = GCCInstallation.getParentLibPath();
3350 StringRef InstallDir = GCCInstallation.getInstallPath();
3351 StringRef TripleStr = GCCInstallation.getTriple().str();
3352 const Multilib &Multilib = GCCInstallation.getMultilib();
3353 const std::string GCCMultiarchTriple =
3354 getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
3355 const std::string TargetMultiarchTriple =
3356 getMultiarchTriple(getTriple(), getDriver().SysRoot);
3357 const GCCVersion &Version = GCCInstallation.getVersion();
3359 // The primary search for libstdc++ supports multiarch variants.
3360 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3361 "/c++/" + Version.Text, TripleStr, GCCMultiarchTriple,
3362 TargetMultiarchTriple,
3363 Multilib.includeSuffix(), DriverArgs, CC1Args))
3366 // Otherwise, fall back on a bunch of options which don't use multiarch
3367 // layouts for simplicity.
3368 const std::string LibStdCXXIncludePathCandidates[] = {
3369 // Gentoo is weird and places its headers inside the GCC install, so if the
3370 // first attempt to find the headers fails, try these patterns.
3371 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3373 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3374 // Android standalone toolchain has C++ headers in yet another place.
3375 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
3376 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
3377 // without a subdirectory corresponding to the gcc version.
3378 LibDir.str() + "/../include/c++",
3381 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3382 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3383 /*GCCMultiarchTriple*/ "",
3384 /*TargetMultiarchTriple*/ "",
3385 Multilib.includeSuffix(), DriverArgs, CC1Args))
3390 bool Linux::isPIEDefault() const {
3391 return getSanitizerArgs().requiresPIE();
3394 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
3396 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3397 : Generic_ELF(D, Triple, Args) {
3399 // Path mangling to find libexec
3400 getProgramPaths().push_back(getDriver().getInstalledDir());
3401 if (getDriver().getInstalledDir() != getDriver().Dir)
3402 getProgramPaths().push_back(getDriver().Dir);
3404 getFilePaths().push_back(getDriver().Dir + "/../lib");
3405 getFilePaths().push_back("/usr/lib");
3406 if (llvm::sys::fs::exists("/usr/lib/gcc47"))
3407 getFilePaths().push_back("/usr/lib/gcc47");
3409 getFilePaths().push_back("/usr/lib/gcc44");
3412 Tool *DragonFly::buildAssembler() const {
3413 return new tools::dragonfly::Assemble(*this);
3416 Tool *DragonFly::buildLinker() const {
3417 return new tools::dragonfly::Link(*this);
3421 /// XCore tool chain
3422 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
3423 const ArgList &Args) : ToolChain(D, Triple, Args) {
3424 // ProgramPaths are found via 'PATH' environment variable.
3427 Tool *XCore::buildAssembler() const {
3428 return new tools::XCore::Assemble(*this);
3431 Tool *XCore::buildLinker() const {
3432 return new tools::XCore::Link(*this);
3435 bool XCore::isPICDefault() const {
3439 bool XCore::isPIEDefault() const {
3443 bool XCore::isPICDefaultForced() const {
3447 bool XCore::SupportsProfiling() const {
3451 bool XCore::hasBlocksRuntime() const {
3455 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3456 ArgStringList &CC1Args) const {
3457 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3458 DriverArgs.hasArg(options::OPT_nostdlibinc))
3460 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
3461 SmallVector<StringRef, 4> Dirs;
3462 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3463 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3464 ArrayRef<StringRef> DirVec(Dirs);
3465 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3469 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3470 llvm::opt::ArgStringList &CC1Args) const {
3471 CC1Args.push_back("-nostdsysteminc");
3474 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3475 ArgStringList &CC1Args) const {
3476 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3477 DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3478 DriverArgs.hasArg(options::OPT_nostdincxx))
3480 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
3481 SmallVector<StringRef, 4> Dirs;
3482 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3483 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3484 ArrayRef<StringRef> DirVec(Dirs);
3485 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3489 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
3490 ArgStringList &CmdArgs) const {
3491 // We don't output any lib args. This is handled by xcc.