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/TargetParser.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <cstdlib> // ::getenv
35 #include <system_error>
37 using namespace clang::driver;
38 using namespace clang::driver::toolchains;
39 using namespace clang;
40 using namespace llvm::opt;
42 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
43 : ToolChain(D, Triple, Args) {
44 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
45 getProgramPaths().push_back(getDriver().getInstalledDir());
46 if (getDriver().getInstalledDir() != getDriver().Dir)
47 getProgramPaths().push_back(getDriver().Dir);
50 /// Darwin - Darwin tool chain for i386 and x86_64.
51 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
52 : MachO(D, Triple, Args), TargetInitialized(false) {}
54 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
55 types::ID Ty = types::lookupTypeForExtension(Ext);
57 // Darwin always preprocesses assembly files (unless -x is used explicitly).
58 if (Ty == types::TY_PP_Asm)
64 bool MachO::HasNativeLLVMSupport() const { return true; }
66 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
67 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
68 if (isTargetIOSBased())
69 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
71 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
72 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
75 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
76 bool Darwin::hasBlocksRuntime() const {
77 if (isTargetIOSBased())
78 return !isIPhoneOSVersionLT(3, 2);
80 assert(isTargetMacOS() && "unexpected darwin target");
81 return !isMacosxVersionLT(10, 6);
85 // This is just a MachO name translation routine and there's no
86 // way to join this into ARMTargetParser without breaking all
87 // other assumptions. Maybe MachO should consider standardising
88 // their nomenclature.
89 static const char *ArmMachOArchName(StringRef Arch) {
90 return llvm::StringSwitch<const char *>(Arch)
91 .Case("armv6k", "armv6")
92 .Case("armv6m", "armv6m")
93 .Case("armv5tej", "armv5")
94 .Case("xscale", "xscale")
95 .Case("armv4t", "armv4t")
96 .Case("armv7", "armv7")
97 .Cases("armv7a", "armv7-a", "armv7")
98 .Cases("armv7r", "armv7-r", "armv7")
99 .Cases("armv7em", "armv7e-m", "armv7em")
100 .Cases("armv7k", "armv7-k", "armv7k")
101 .Cases("armv7m", "armv7-m", "armv7m")
102 .Cases("armv7s", "armv7-s", "armv7s")
106 static const char *ArmMachOArchNameCPU(StringRef CPU) {
107 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
108 if (ArchKind == llvm::ARM::AK_INVALID)
110 StringRef Arch = llvm::ARMTargetParser::getArchName(ArchKind);
112 // FIXME: Make sure this MachO triple mangling is really necessary.
113 // ARMv5* normalises to ARMv5.
114 if (Arch.startswith("armv5"))
115 Arch = Arch.substr(0, 5);
116 // ARMv6*, except ARMv6M, normalises to ARMv6.
117 else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
118 Arch = Arch.substr(0, 5);
119 // ARMv7A normalises to ARMv7.
120 else if (Arch.endswith("v7a"))
121 Arch = Arch.substr(0, 5);
125 static bool isSoftFloatABI(const ArgList &Args) {
126 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
127 options::OPT_mfloat_abi_EQ);
131 return A->getOption().matches(options::OPT_msoft_float) ||
132 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
133 A->getValue() == StringRef("soft"));
136 StringRef MachO::getMachOArchName(const ArgList &Args) const {
137 switch (getTriple().getArch()) {
139 return getDefaultUniversalArchName();
141 case llvm::Triple::aarch64:
144 case llvm::Triple::thumb:
145 case llvm::Triple::arm: {
146 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
147 if (const char *Arch = ArmMachOArchName(A->getValue()))
150 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
151 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
163 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
164 types::ID InputType) const {
165 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
167 return Triple.getTriple();
170 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
171 types::ID InputType) const {
172 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
174 // If the target isn't initialized (e.g., an unknown Darwin platform, return
175 // the default triple).
176 if (!isTargetInitialized())
177 return Triple.getTriple();
180 Str += isTargetIOSBased() ? "ios" : "macosx";
181 Str += getTargetVersion().getAsString();
182 Triple.setOSName(Str);
184 return Triple.getTriple();
187 void Generic_ELF::anchor() {}
189 Tool *MachO::getTool(Action::ActionClass AC) const {
191 case Action::LipoJobClass:
193 Lipo.reset(new tools::darwin::Lipo(*this));
195 case Action::DsymutilJobClass:
197 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
198 return Dsymutil.get();
199 case Action::VerifyDebugInfoJobClass:
201 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
202 return VerifyDebug.get();
204 return ToolChain::getTool(AC);
208 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
210 Tool *MachO::buildAssembler() const {
211 return new tools::darwin::Assembler(*this);
214 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
216 : Darwin(D, Triple, Args) {}
218 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
219 // For iOS, 64-bit, promote certain warnings to errors.
220 if (!isTargetMacOS() && getTriple().isArch64Bit()) {
221 // Always enable -Wdeprecated-objc-isa-usage and promote it
223 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
224 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
226 // Also error about implicit function declarations, as that
227 // can impact calling conventions.
228 CC1Args.push_back("-Werror=implicit-function-declaration");
232 /// \brief Determine whether Objective-C automated reference counting is
234 static bool isObjCAutoRefCount(const ArgList &Args) {
235 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
238 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
239 ArgStringList &CmdArgs) const {
240 // Avoid linking compatibility stubs on i386 mac.
241 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
244 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
246 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
247 runtime.hasSubscripting())
250 CmdArgs.push_back("-force_load");
251 SmallString<128> P(getDriver().ClangExecutable);
252 llvm::sys::path::remove_filename(P); // 'clang'
253 llvm::sys::path::remove_filename(P); // 'bin'
254 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
255 // Mash in the platform.
256 if (isTargetIOSSimulator())
257 P += "iphonesimulator";
258 else if (isTargetIPhoneOS())
264 CmdArgs.push_back(Args.MakeArgString(P));
267 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
268 StringRef DarwinLibName, bool AlwaysLink,
269 bool IsEmbedded, bool AddRPath) const {
270 SmallString<128> Dir(getDriver().ResourceDir);
271 llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
273 SmallString<128> P(Dir);
274 llvm::sys::path::append(P, DarwinLibName);
276 // For now, allow missing resource libraries to support developers who may
277 // not have compiler-rt checked out or integrated into their build (unless
278 // we explicitly force linking with this library).
279 if (AlwaysLink || llvm::sys::fs::exists(P))
280 CmdArgs.push_back(Args.MakeArgString(P));
282 // Adding the rpaths might negatively interact when other rpaths are involved,
283 // so we should make sure we add the rpaths last, after all user-specified
284 // rpaths. This is currently true from this place, but we need to be
285 // careful if this function is ever called before user's rpaths are emitted.
287 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
289 // Add @executable_path to rpath to support having the dylib copied with
291 CmdArgs.push_back("-rpath");
292 CmdArgs.push_back("@executable_path");
294 // Add the path to the resource dir to rpath to support using the dylib
295 // from the default location without copying.
296 CmdArgs.push_back("-rpath");
297 CmdArgs.push_back(Args.MakeArgString(Dir));
301 void Darwin::addProfileRTLibs(const ArgList &Args,
302 ArgStringList &CmdArgs) const {
303 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
305 Args.hasArg(options::OPT_fprofile_generate) ||
306 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
307 Args.hasArg(options::OPT_fprofile_instr_generate) ||
308 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
309 Args.hasArg(options::OPT_fcreate_profile) ||
310 Args.hasArg(options::OPT_coverage)))
313 // Select the appropriate runtime library for the target.
314 if (isTargetIOSBased())
315 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a",
316 /*AlwaysLink*/ true);
318 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a",
319 /*AlwaysLink*/ true);
322 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
323 ArgStringList &CmdArgs,
324 StringRef Sanitizer) const {
325 if (!Args.hasArg(options::OPT_dynamiclib) &&
326 !Args.hasArg(options::OPT_bundle)) {
327 // Sanitizer runtime libraries requires C++.
328 AddCXXStdlibLibArgs(Args, CmdArgs);
330 assert(isTargetMacOS() || isTargetIOSSimulator());
331 StringRef OS = isTargetMacOS() ? "osx" : "iossim";
334 (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
335 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
338 if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
339 // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
340 // all RTTI-related symbols that UBSan uses.
341 CmdArgs.push_back("-lc++abi");
345 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
346 ArgStringList &CmdArgs) const {
347 // Darwin only supports the compiler-rt based runtime libraries.
348 switch (GetRuntimeLibType(Args)) {
349 case ToolChain::RLT_CompilerRT:
352 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
353 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
357 // Darwin doesn't support real static executables, don't link any runtime
358 // libraries with -static.
359 if (Args.hasArg(options::OPT_static) ||
360 Args.hasArg(options::OPT_fapple_kext) ||
361 Args.hasArg(options::OPT_mkernel))
364 // Reject -static-libgcc for now, we can deal with this when and if someone
365 // cares. This is useful in situations where someone wants to statically link
366 // something like libstdc++, and needs its runtime support routines.
367 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
368 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
372 const SanitizerArgs &Sanitize = getSanitizerArgs();
373 if (Sanitize.needsAsanRt())
374 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
375 if (Sanitize.needsUbsanRt())
376 AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
378 // Otherwise link libSystem, then the dynamic runtime library, and finally any
379 // target specific static runtime library.
380 CmdArgs.push_back("-lSystem");
382 // Select the dynamic runtime library and the target specific static library.
383 if (isTargetIOSBased()) {
384 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
385 // it never went into the SDK.
386 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
387 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
388 getTriple().getArch() != llvm::Triple::aarch64)
389 CmdArgs.push_back("-lgcc_s.1");
391 // We currently always need a static runtime library for iOS.
392 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
394 assert(isTargetMacOS() && "unexpected non MacOS platform");
395 // The dynamic runtime library was merged with libSystem for 10.6 and
396 // beyond; only 10.4 and 10.5 need an additional runtime library.
397 if (isMacosxVersionLT(10, 5))
398 CmdArgs.push_back("-lgcc_s.10.4");
399 else if (isMacosxVersionLT(10, 6))
400 CmdArgs.push_back("-lgcc_s.10.5");
402 // For OS X, we thought we would only need a static runtime library when
403 // targeting 10.4, to provide versions of the static functions which were
404 // omitted from 10.4.dylib.
406 // Unfortunately, that turned out to not be true, because Darwin system
407 // headers can still use eprintf on i386, and it is not exported from
408 // libSystem. Therefore, we still must provide a runtime library just for
409 // the tiny tiny handful of projects that *might* use that symbol.
410 if (isMacosxVersionLT(10, 5)) {
411 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
413 if (getTriple().getArch() == llvm::Triple::x86)
414 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
415 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
420 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
421 const OptTable &Opts = getDriver().getOpts();
423 // Support allowing the SDKROOT environment variable used by xcrun and other
424 // Xcode tools to define the default sysroot, by making it the default for
426 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
427 // Warn if the path does not exist.
428 if (!llvm::sys::fs::exists(A->getValue()))
429 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
431 if (char *env = ::getenv("SDKROOT")) {
432 // We only use this value as the default if it is an absolute path,
433 // exists, and it is not the root path.
434 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
435 StringRef(env) != "/") {
436 Args.append(Args.MakeSeparateArg(
437 nullptr, Opts.getOption(options::OPT_isysroot), env));
442 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
443 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
445 if (OSXVersion && iOSVersion) {
446 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
447 << OSXVersion->getAsString(Args) << iOSVersion->getAsString(Args);
448 iOSVersion = nullptr;
449 } else if (!OSXVersion && !iOSVersion) {
450 // If no deployment target was specified on the command line, check for
451 // environment defines.
452 std::string OSXTarget;
453 std::string iOSTarget;
454 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
456 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
459 // If there is no command-line argument to specify the Target version and
460 // no environment variable defined, see if we can set the default based
462 if (iOSTarget.empty() && OSXTarget.empty() &&
463 Args.hasArg(options::OPT_isysroot)) {
464 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
465 StringRef isysroot = A->getValue();
466 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
467 size_t BeginSDK = isysroot.rfind("SDKs/");
468 size_t EndSDK = isysroot.rfind(".sdk");
469 if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
470 StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
471 // Slice the version number out.
472 // Version number is between the first and the last number.
473 size_t StartVer = SDK.find_first_of("0123456789");
474 size_t EndVer = SDK.find_last_of("0123456789");
475 if (StartVer != StringRef::npos && EndVer > StartVer) {
476 StringRef Version = SDK.slice(StartVer, EndVer + 1);
477 if (SDK.startswith("iPhoneOS") ||
478 SDK.startswith("iPhoneSimulator"))
480 else if (SDK.startswith("MacOSX"))
487 // If no OSX or iOS target has been specified, try to guess platform
488 // from arch name and compute the version from the triple.
489 if (OSXTarget.empty() && iOSTarget.empty()) {
490 StringRef MachOArchName = getMachOArchName(Args);
491 unsigned Major, Minor, Micro;
492 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
493 MachOArchName == "arm64") {
494 getTriple().getiOSVersion(Major, Minor, Micro);
495 llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
497 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
498 MachOArchName != "armv7em") {
499 if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
500 getDriver().Diag(diag::err_drv_invalid_darwin_version)
501 << getTriple().getOSName();
503 llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
508 // Allow conflicts among OSX and iOS for historical reasons, but choose the
510 if (!OSXTarget.empty() && !iOSTarget.empty()) {
511 if (getTriple().getArch() == llvm::Triple::arm ||
512 getTriple().getArch() == llvm::Triple::aarch64 ||
513 getTriple().getArch() == llvm::Triple::thumb)
519 if (!OSXTarget.empty()) {
520 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
521 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
522 Args.append(OSXVersion);
523 } else if (!iOSTarget.empty()) {
524 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
525 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
526 Args.append(iOSVersion);
530 DarwinPlatformKind Platform;
536 llvm_unreachable("Unable to infer Darwin variant");
538 // Set the tool chain target information.
539 unsigned Major, Minor, Micro;
541 if (Platform == MacOS) {
542 assert(!iOSVersion && "Unknown target platform!");
543 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
545 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
546 getDriver().Diag(diag::err_drv_invalid_version_number)
547 << OSXVersion->getAsString(Args);
548 } else if (Platform == IPhoneOS) {
549 assert(iOSVersion && "Unknown target platform!");
550 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
552 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
553 getDriver().Diag(diag::err_drv_invalid_version_number)
554 << iOSVersion->getAsString(Args);
556 llvm_unreachable("unknown kind of Darwin platform");
558 // Recognize iOS targets with an x86 architecture as the iOS simulator.
559 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
560 getTriple().getArch() == llvm::Triple::x86_64))
561 Platform = IPhoneOSSimulator;
563 setTarget(Platform, Major, Minor, Micro);
566 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
567 ArgStringList &CmdArgs) const {
568 CXXStdlibType Type = GetCXXStdlibType(Args);
571 case ToolChain::CST_Libcxx:
572 CmdArgs.push_back("-lc++");
575 case ToolChain::CST_Libstdcxx: {
576 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
577 // it was previously found in the gcc lib dir. However, for all the Darwin
578 // platforms we care about it was -lstdc++.6, so we search for that
579 // explicitly if we can't see an obvious -lstdc++ candidate.
581 // Check in the sysroot first.
582 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
583 SmallString<128> P(A->getValue());
584 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
586 if (!llvm::sys::fs::exists(P)) {
587 llvm::sys::path::remove_filename(P);
588 llvm::sys::path::append(P, "libstdc++.6.dylib");
589 if (llvm::sys::fs::exists(P)) {
590 CmdArgs.push_back(Args.MakeArgString(P));
596 // Otherwise, look in the root.
597 // FIXME: This should be removed someday when we don't have to care about
598 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
599 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
600 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
601 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
605 // Otherwise, let the linker search.
606 CmdArgs.push_back("-lstdc++");
612 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
613 ArgStringList &CmdArgs) const {
615 // For Darwin platforms, use the compiler-rt-based support library
616 // instead of the gcc-provided one (which is also incidentally
617 // only present in the gcc lib dir, which makes it hard to find).
619 SmallString<128> P(getDriver().ResourceDir);
620 llvm::sys::path::append(P, "lib", "darwin");
622 // Use the newer cc_kext for iOS ARM after 6.0.
623 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
624 getTriple().getArch() == llvm::Triple::aarch64 ||
625 !isIPhoneOSVersionLT(6, 0)) {
626 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
628 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
631 // For now, allow missing resource libraries to support developers who may
632 // not have compiler-rt checked out or integrated into their build.
633 if (llvm::sys::fs::exists(P))
634 CmdArgs.push_back(Args.MakeArgString(P));
637 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
638 const char *BoundArch) const {
639 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
640 const OptTable &Opts = getDriver().getOpts();
642 // FIXME: We really want to get out of the tool chain level argument
643 // translation business, as it makes the driver functionality much
644 // more opaque. For now, we follow gcc closely solely for the
645 // purpose of easily achieving feature parity & testability. Once we
646 // have something that works, we should reevaluate each translation
647 // and try to push it down into tool specific logic.
649 for (Arg *A : Args) {
650 if (A->getOption().matches(options::OPT_Xarch__)) {
651 // Skip this argument unless the architecture matches either the toolchain
652 // triple arch, or the arch being bound.
653 llvm::Triple::ArchType XarchArch =
654 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
655 if (!(XarchArch == getArch() ||
658 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
661 Arg *OriginalArg = A;
662 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
663 unsigned Prev = Index;
664 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
666 // If the argument parsing failed or more than one argument was
667 // consumed, the -Xarch_ argument's parameter tried to consume
668 // extra arguments. Emit an error and ignore.
670 // We also want to disallow any options which would alter the
671 // driver behavior; that isn't going to work in our model. We
672 // use isDriverOption() as an approximation, although things
673 // like -O4 are going to slip through.
674 if (!XarchArg || Index > Prev + 1) {
675 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
676 << A->getAsString(Args);
678 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
679 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
680 << A->getAsString(Args);
684 XarchArg->setBaseArg(A);
686 A = XarchArg.release();
687 DAL->AddSynthesizedArg(A);
689 // Linker input arguments require custom handling. The problem is that we
690 // have already constructed the phase actions, so we can not treat them as
691 // "input arguments".
692 if (A->getOption().hasFlag(options::LinkerInput)) {
693 // Convert the argument into individual Zlinker_input_args.
694 for (const char *Value : A->getValues()) {
696 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
702 // Sob. These is strictly gcc compatible for the time being. Apple
703 // gcc translates options twice, which means that self-expanding
704 // options add duplicates.
705 switch ((options::ID)A->getOption().getID()) {
710 case options::OPT_mkernel:
711 case options::OPT_fapple_kext:
713 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
716 case options::OPT_dependency_file:
717 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
720 case options::OPT_gfull:
721 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
723 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
726 case options::OPT_gused:
727 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
729 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
732 case options::OPT_shared:
733 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
736 case options::OPT_fconstant_cfstrings:
737 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
740 case options::OPT_fno_constant_cfstrings:
741 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
744 case options::OPT_Wnonportable_cfstrings:
746 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
749 case options::OPT_Wno_nonportable_cfstrings:
751 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
754 case options::OPT_fpascal_strings:
755 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
758 case options::OPT_fno_pascal_strings:
759 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
764 if (getTriple().getArch() == llvm::Triple::x86 ||
765 getTriple().getArch() == llvm::Triple::x86_64)
766 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
767 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
770 // Add the arch options based on the particular spelling of -arch, to match
771 // how the driver driver works.
773 StringRef Name = BoundArch;
774 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
775 const Option MArch = Opts.getOption(options::OPT_march_EQ);
777 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
778 // which defines the list of which architectures we accept.
781 else if (Name == "ppc601")
782 DAL->AddJoinedArg(nullptr, MCpu, "601");
783 else if (Name == "ppc603")
784 DAL->AddJoinedArg(nullptr, MCpu, "603");
785 else if (Name == "ppc604")
786 DAL->AddJoinedArg(nullptr, MCpu, "604");
787 else if (Name == "ppc604e")
788 DAL->AddJoinedArg(nullptr, MCpu, "604e");
789 else if (Name == "ppc750")
790 DAL->AddJoinedArg(nullptr, MCpu, "750");
791 else if (Name == "ppc7400")
792 DAL->AddJoinedArg(nullptr, MCpu, "7400");
793 else if (Name == "ppc7450")
794 DAL->AddJoinedArg(nullptr, MCpu, "7450");
795 else if (Name == "ppc970")
796 DAL->AddJoinedArg(nullptr, MCpu, "970");
798 else if (Name == "ppc64" || Name == "ppc64le")
799 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
801 else if (Name == "i386")
803 else if (Name == "i486")
804 DAL->AddJoinedArg(nullptr, MArch, "i486");
805 else if (Name == "i586")
806 DAL->AddJoinedArg(nullptr, MArch, "i586");
807 else if (Name == "i686")
808 DAL->AddJoinedArg(nullptr, MArch, "i686");
809 else if (Name == "pentium")
810 DAL->AddJoinedArg(nullptr, MArch, "pentium");
811 else if (Name == "pentium2")
812 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
813 else if (Name == "pentpro")
814 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
815 else if (Name == "pentIIm3")
816 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
818 else if (Name == "x86_64")
819 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
820 else if (Name == "x86_64h") {
821 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
822 DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
825 else if (Name == "arm")
826 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
827 else if (Name == "armv4t")
828 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
829 else if (Name == "armv5")
830 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
831 else if (Name == "xscale")
832 DAL->AddJoinedArg(nullptr, MArch, "xscale");
833 else if (Name == "armv6")
834 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
835 else if (Name == "armv6m")
836 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
837 else if (Name == "armv7")
838 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
839 else if (Name == "armv7em")
840 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
841 else if (Name == "armv7k")
842 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
843 else if (Name == "armv7m")
844 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
845 else if (Name == "armv7s")
846 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
852 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
853 ArgStringList &CmdArgs) const {
854 // Embedded targets are simple at the moment, not supporting sanitizers and
855 // with different libraries for each member of the product { static, PIC } x
856 // { hard-float, soft-float }
857 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
859 tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
862 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
864 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
867 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
868 const char *BoundArch) const {
869 // First get the generic Apple args, before moving onto Darwin-specific ones.
870 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
871 const OptTable &Opts = getDriver().getOpts();
873 // If no architecture is bound, none of the translations here are relevant.
877 // Add an explicit version min argument for the deployment target. We do this
878 // after argument translation because -Xarch_ arguments may add a version min
880 AddDeploymentTarget(*DAL);
882 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
883 // FIXME: It would be far better to avoid inserting those -static arguments,
884 // but we can't check the deployment target in the translation code until
886 if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
887 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie;) {
890 if (A->getOption().getID() != options::OPT_mkernel &&
891 A->getOption().getID() != options::OPT_fapple_kext)
893 assert(it != ie && "unexpected argument translation");
895 assert(A->getOption().getID() == options::OPT_static &&
896 "missing expected -static argument");
897 it = DAL->getArgs().erase(it);
901 // Default to use libc++ on OS X 10.9+ and iOS 7+.
902 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
903 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
904 !Args.getLastArg(options::OPT_stdlib_EQ))
905 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
908 // Validate the C++ standard library choice.
909 CXXStdlibType Type = GetCXXStdlibType(*DAL);
910 if (Type == ToolChain::CST_Libcxx) {
911 // Check whether the target provides libc++.
914 // Complain about targeting iOS < 5.0 in any way.
915 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
918 if (where != StringRef()) {
919 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
926 bool MachO::IsUnwindTablesDefault() const {
927 return getArch() == llvm::Triple::x86_64;
930 bool MachO::UseDwarfDebugFlags() const {
931 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
936 bool Darwin::UseSjLjExceptions() const {
937 // Darwin uses SjLj exceptions on ARM.
938 return (getTriple().getArch() == llvm::Triple::arm ||
939 getTriple().getArch() == llvm::Triple::thumb);
942 bool MachO::isPICDefault() const { return true; }
944 bool MachO::isPIEDefault() const { return false; }
946 bool MachO::isPICDefaultForced() const {
947 return (getArch() == llvm::Triple::x86_64 ||
948 getArch() == llvm::Triple::aarch64);
951 bool MachO::SupportsProfiling() const {
952 // Profiling instrumentation is only supported on x86.
953 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
956 void Darwin::addMinVersionArgs(const ArgList &Args,
957 ArgStringList &CmdArgs) const {
958 VersionTuple TargetVersion = getTargetVersion();
960 if (isTargetIOSSimulator())
961 CmdArgs.push_back("-ios_simulator_version_min");
962 else if (isTargetIOSBased())
963 CmdArgs.push_back("-iphoneos_version_min");
965 assert(isTargetMacOS() && "unexpected target");
966 CmdArgs.push_back("-macosx_version_min");
969 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
972 void Darwin::addStartObjectFileArgs(const ArgList &Args,
973 ArgStringList &CmdArgs) const {
974 // Derived from startfile spec.
975 if (Args.hasArg(options::OPT_dynamiclib)) {
976 // Derived from darwin_dylib1 spec.
977 if (isTargetIOSSimulator()) {
978 ; // iOS simulator does not need dylib1.o.
979 } else if (isTargetIPhoneOS()) {
980 if (isIPhoneOSVersionLT(3, 1))
981 CmdArgs.push_back("-ldylib1.o");
983 if (isMacosxVersionLT(10, 5))
984 CmdArgs.push_back("-ldylib1.o");
985 else if (isMacosxVersionLT(10, 6))
986 CmdArgs.push_back("-ldylib1.10.5.o");
989 if (Args.hasArg(options::OPT_bundle)) {
990 if (!Args.hasArg(options::OPT_static)) {
991 // Derived from darwin_bundle1 spec.
992 if (isTargetIOSSimulator()) {
993 ; // iOS simulator does not need bundle1.o.
994 } else if (isTargetIPhoneOS()) {
995 if (isIPhoneOSVersionLT(3, 1))
996 CmdArgs.push_back("-lbundle1.o");
998 if (isMacosxVersionLT(10, 6))
999 CmdArgs.push_back("-lbundle1.o");
1003 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1004 if (Args.hasArg(options::OPT_static) ||
1005 Args.hasArg(options::OPT_object) ||
1006 Args.hasArg(options::OPT_preload)) {
1007 CmdArgs.push_back("-lgcrt0.o");
1009 CmdArgs.push_back("-lgcrt1.o");
1011 // darwin_crt2 spec is empty.
1013 // By default on OS X 10.8 and later, we don't link with a crt1.o
1014 // file and the linker knows to use _main as the entry point. But,
1015 // when compiling with -pg, we need to link with the gcrt1.o file,
1016 // so pass the -no_new_main option to tell the linker to use the
1017 // "start" symbol as the entry point.
1018 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1019 CmdArgs.push_back("-no_new_main");
1021 if (Args.hasArg(options::OPT_static) ||
1022 Args.hasArg(options::OPT_object) ||
1023 Args.hasArg(options::OPT_preload)) {
1024 CmdArgs.push_back("-lcrt0.o");
1026 // Derived from darwin_crt1 spec.
1027 if (isTargetIOSSimulator()) {
1028 ; // iOS simulator does not need crt1.o.
1029 } else if (isTargetIPhoneOS()) {
1030 if (getArch() == llvm::Triple::aarch64)
1031 ; // iOS does not need any crt1 files for arm64
1032 else if (isIPhoneOSVersionLT(3, 1))
1033 CmdArgs.push_back("-lcrt1.o");
1034 else if (isIPhoneOSVersionLT(6, 0))
1035 CmdArgs.push_back("-lcrt1.3.1.o");
1037 if (isMacosxVersionLT(10, 5))
1038 CmdArgs.push_back("-lcrt1.o");
1039 else if (isMacosxVersionLT(10, 6))
1040 CmdArgs.push_back("-lcrt1.10.5.o");
1041 else if (isMacosxVersionLT(10, 8))
1042 CmdArgs.push_back("-lcrt1.10.6.o");
1044 // darwin_crt2 spec is empty.
1051 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1052 isMacosxVersionLT(10, 5)) {
1053 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1054 CmdArgs.push_back(Str);
1058 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1060 void Darwin::CheckObjCARC() const {
1061 if (isTargetIOSBased() || (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1063 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1066 SanitizerMask Darwin::getSupportedSanitizers() const {
1067 SanitizerMask Res = ToolChain::getSupportedSanitizers();
1068 if (isTargetMacOS() || isTargetIOSSimulator())
1069 Res |= SanitizerKind::Address;
1070 if (isTargetMacOS()) {
1071 if (!isMacosxVersionLT(10, 9))
1072 Res |= SanitizerKind::Vptr;
1073 Res |= SanitizerKind::SafeStack;
1078 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1079 /// all subcommands; this relies on gcc translating the majority of
1080 /// command line options.
1082 /// \brief Parse a GCCVersion object out of a string of text.
1084 /// This is the primary means of forming GCCVersion objects.
1086 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1087 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1088 std::pair<StringRef, StringRef> First = VersionText.split('.');
1089 std::pair<StringRef, StringRef> Second = First.second.split('.');
1091 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1092 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1094 GoodVersion.MajorStr = First.first.str();
1095 if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1097 GoodVersion.MinorStr = Second.first.str();
1099 // First look for a number prefix and parse that if present. Otherwise just
1100 // stash the entire patch string in the suffix, and leave the number
1101 // unspecified. This covers versions strings such as:
1107 // And retains any patch number it finds.
1108 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1109 if (!PatchText.empty()) {
1110 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1111 // Try to parse the number and any suffix.
1112 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1113 GoodVersion.Patch < 0)
1115 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1122 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1123 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1125 StringRef RHSPatchSuffix) const {
1126 if (Major != RHSMajor)
1127 return Major < RHSMajor;
1128 if (Minor != RHSMinor)
1129 return Minor < RHSMinor;
1130 if (Patch != RHSPatch) {
1131 // Note that versions without a specified patch sort higher than those with
1138 // Otherwise just sort on the patch itself.
1139 return Patch < RHSPatch;
1141 if (PatchSuffix != RHSPatchSuffix) {
1142 // Sort empty suffixes higher.
1143 if (RHSPatchSuffix.empty())
1145 if (PatchSuffix.empty())
1148 // Provide a lexicographic sort to make this a total ordering.
1149 return PatchSuffix < RHSPatchSuffix;
1152 // The versions are equal.
1156 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1157 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1159 return A->getValue();
1160 return GCC_INSTALL_PREFIX;
1163 /// \brief Initialize a GCCInstallationDetector from the driver.
1165 /// This performs all of the autodetection and sets up the various paths.
1166 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1168 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1169 /// should instead pull the target out of the driver. This is currently
1170 /// necessary because the driver doesn't store the final version of the target
1172 void Generic_GCC::GCCInstallationDetector::init(
1173 const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
1174 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1175 ? TargetTriple.get64BitArchVariant()
1176 : TargetTriple.get32BitArchVariant();
1177 // The library directories which may contain GCC installations.
1178 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1179 // The compatible GCC triples for this particular architecture.
1180 SmallVector<StringRef, 16> CandidateTripleAliases;
1181 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1182 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1183 CandidateTripleAliases, CandidateBiarchLibDirs,
1184 CandidateBiarchTripleAliases);
1186 // Compute the set of prefixes for our search.
1187 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1188 D.PrefixDirs.end());
1190 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1191 if (GCCToolchainDir != "") {
1192 if (GCCToolchainDir.back() == '/')
1193 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1195 Prefixes.push_back(GCCToolchainDir);
1197 // If we have a SysRoot, try that first.
1198 if (!D.SysRoot.empty()) {
1199 Prefixes.push_back(D.SysRoot);
1200 Prefixes.push_back(D.SysRoot + "/usr");
1203 // Then look for gcc installed alongside clang.
1204 Prefixes.push_back(D.InstalledDir + "/..");
1206 // And finally in /usr.
1207 if (D.SysRoot.empty())
1208 Prefixes.push_back("/usr");
1211 // Loop over the various components which exist and select the best GCC
1212 // installation available. GCC installs are ranked by version number.
1213 Version = GCCVersion::Parse("0.0.0");
1214 for (const std::string &Prefix : Prefixes) {
1215 if (!llvm::sys::fs::exists(Prefix))
1217 for (const StringRef Suffix : CandidateLibDirs) {
1218 const std::string LibDir = Prefix + Suffix.str();
1219 if (!llvm::sys::fs::exists(LibDir))
1221 for (const StringRef Candidate : CandidateTripleAliases)
1222 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1224 for (const StringRef Suffix : CandidateBiarchLibDirs) {
1225 const std::string LibDir = Prefix + Suffix.str();
1226 if (!llvm::sys::fs::exists(LibDir))
1228 for (const StringRef Candidate : CandidateBiarchTripleAliases)
1229 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1230 /*NeedsBiarchSuffix=*/ true);
1235 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1236 for (const auto &InstallPath : CandidateGCCInstallPaths)
1237 OS << "Found candidate GCC installation: " << InstallPath << "\n";
1239 if (!GCCInstallPath.empty())
1240 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1242 for (const auto &Multilib : Multilibs)
1243 OS << "Candidate multilib: " << Multilib << "\n";
1245 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1246 OS << "Selected multilib: " << SelectedMultilib << "\n";
1249 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1250 if (BiarchSibling.hasValue()) {
1251 M = BiarchSibling.getValue();
1257 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1258 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1259 SmallVectorImpl<StringRef> &LibDirs,
1260 SmallVectorImpl<StringRef> &TripleAliases,
1261 SmallVectorImpl<StringRef> &BiarchLibDirs,
1262 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1263 // Declare a bunch of static data sets that we'll select between below. These
1264 // are specifically designed to always refer to string literals to avoid any
1265 // lifetime or initialization issues.
1266 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1267 static const char *const AArch64Triples[] = {
1268 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1269 "aarch64-redhat-linux"};
1270 static const char *const AArch64beLibDirs[] = {"/lib"};
1271 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1272 "aarch64_be-linux-gnu"};
1274 static const char *const ARMLibDirs[] = {"/lib"};
1275 static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1276 "arm-linux-androideabi"};
1277 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1278 "armv7hl-redhat-linux-gnueabi"};
1279 static const char *const ARMebLibDirs[] = {"/lib"};
1280 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1281 "armeb-linux-androideabi"};
1282 static const char *const ARMebHFTriples[] = {
1283 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1285 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1286 static const char *const X86_64Triples[] = {
1287 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1288 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1289 "x86_64-redhat-linux", "x86_64-suse-linux",
1290 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1291 "x86_64-slackware-linux", "x86_64-linux-android",
1292 "x86_64-unknown-linux"};
1293 static const char *const X32LibDirs[] = {"/libx32"};
1294 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1295 static const char *const X86Triples[] = {
1296 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1297 "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1298 "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1299 "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1302 static const char *const MIPSLibDirs[] = {"/lib"};
1303 static const char *const MIPSTriples[] = {
1304 "mips-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu"};
1305 static const char *const MIPSELLibDirs[] = {"/lib"};
1306 static const char *const MIPSELTriples[] = {
1307 "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
1309 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1310 static const char *const MIPS64Triples[] = {
1311 "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1312 "mips64-linux-gnuabi64"};
1313 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1314 static const char *const MIPS64ELTriples[] = {
1315 "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1316 "mips64el-linux-android", "mips64el-linux-gnuabi64"};
1318 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1319 static const char *const PPCTriples[] = {
1320 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1321 "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1322 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1323 static const char *const PPC64Triples[] = {
1324 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1325 "powerpc64-suse-linux", "ppc64-redhat-linux"};
1326 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1327 static const char *const PPC64LETriples[] = {
1328 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1329 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1331 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1332 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1333 "sparcv8-linux-gnu"};
1334 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1335 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1336 "sparcv9-linux-gnu"};
1338 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1339 static const char *const SystemZTriples[] = {
1340 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1341 "s390x-suse-linux", "s390x-redhat-linux"};
1346 switch (TargetTriple.getArch()) {
1347 case llvm::Triple::aarch64:
1348 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1349 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1350 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1351 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1353 case llvm::Triple::aarch64_be:
1354 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1355 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1356 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1357 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1359 case llvm::Triple::arm:
1360 case llvm::Triple::thumb:
1361 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1362 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1363 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1365 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1368 case llvm::Triple::armeb:
1369 case llvm::Triple::thumbeb:
1370 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1371 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1372 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1374 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1377 case llvm::Triple::x86_64:
1378 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1379 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1380 // x32 is always available when x86_64 is available, so adding it as
1381 // secondary arch with x86_64 triples
1382 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1383 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1384 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1386 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1387 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1390 case llvm::Triple::x86:
1391 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1392 TripleAliases.append(begin(X86Triples), end(X86Triples));
1393 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1394 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1396 case llvm::Triple::mips:
1397 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1398 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1399 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1400 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1402 case llvm::Triple::mipsel:
1403 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1404 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1405 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1406 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1407 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1409 case llvm::Triple::mips64:
1410 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1411 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1412 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1413 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1415 case llvm::Triple::mips64el:
1416 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1417 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1418 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1419 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1420 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1422 case llvm::Triple::ppc:
1423 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1424 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1425 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1426 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1428 case llvm::Triple::ppc64:
1429 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1430 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1431 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1432 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1434 case llvm::Triple::ppc64le:
1435 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1436 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1438 case llvm::Triple::sparc:
1439 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1440 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1441 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1442 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1444 case llvm::Triple::sparcv9:
1445 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1446 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1447 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1448 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1450 case llvm::Triple::systemz:
1451 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1452 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1456 // By default, just rely on the standard lib directories and the original
1461 // Always append the drivers target triple to the end, in case it doesn't
1462 // match any of our aliases.
1463 TripleAliases.push_back(TargetTriple.str());
1465 // Also include the multiarch variant if it's different.
1466 if (TargetTriple.str() != BiarchTriple.str())
1467 BiarchTripleAliases.push_back(BiarchTriple.str());
1471 // Filter to remove Multilibs that don't exist as a suffix to Path
1472 class FilterNonExistent {
1476 FilterNonExistent(StringRef Base) : Base(Base) {}
1477 bool operator()(const Multilib &M) {
1478 return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
1481 } // end anonymous namespace
1483 static void addMultilibFlag(bool Enabled, const char *const Flag,
1484 std::vector<std::string> &Flags) {
1486 Flags.push_back(std::string("+") + Flag);
1488 Flags.push_back(std::string("-") + Flag);
1491 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1492 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1493 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1496 static bool isMips32(llvm::Triple::ArchType Arch) {
1497 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1500 static bool isMips64(llvm::Triple::ArchType Arch) {
1501 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1504 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1505 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1508 static bool isMips16(const ArgList &Args) {
1509 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1510 return A && A->getOption().matches(options::OPT_mips16);
1513 static bool isMicroMips(const ArgList &Args) {
1514 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1515 return A && A->getOption().matches(options::OPT_mmicromips);
1518 struct DetectedMultilibs {
1519 /// The set of multilibs that the detected installation supports.
1520 MultilibSet Multilibs;
1522 /// The primary multilib appropriate for the given flags.
1523 Multilib SelectedMultilib;
1525 /// On Biarch systems, this corresponds to the default multilib when
1526 /// targeting the non-default multilib. Otherwise, it is empty.
1527 llvm::Optional<Multilib> BiarchSibling;
1530 static Multilib makeMultilib(StringRef commonSuffix) {
1531 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1534 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
1535 const ArgList &Args, DetectedMultilibs &Result) {
1536 // Some MIPS toolchains put libraries and object files compiled
1537 // using different options in to the sub-directoris which names
1538 // reflects the flags used for compilation. For example sysroot
1539 // directory might looks like the following examples:
1542 // /lib <= crt*.o files compiled with '-mips32'
1545 // /lib <= crt*.o files compiled with '-mips16'
1548 // /lib <= crt*.o files compiled with '-mips16 -EL'
1553 // /lib <= crt*.o files compiled with '-mips32r2'
1556 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1559 // /lib <= crt*.o files compiled with '-mips32'
1561 FilterNonExistent NonExistent(Path);
1563 // Check for FSF toolchain multilibs
1564 MultilibSet FSFMipsMultilibs;
1566 auto MArchMips32 = makeMultilib("/mips32")
1569 .flag("-mmicromips")
1570 .flag("+march=mips32");
1572 auto MArchMicroMips = makeMultilib("/micromips")
1575 .flag("+mmicromips");
1577 auto MArchMips64r2 = makeMultilib("/mips64r2")
1580 .flag("+march=mips64r2");
1582 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1585 auto MArchDefault = makeMultilib("")
1588 .flag("-mmicromips")
1589 .flag("+march=mips32r2");
1591 auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1593 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1596 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1598 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1600 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1602 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1604 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1608 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1612 .FilterOut("/mips64/mips16")
1613 .FilterOut("/mips64r2/mips16")
1614 .FilterOut("/micromips/mips16")
1616 .FilterOut("/micromips/64")
1617 .FilterOut("/mips32/64")
1619 .FilterOut("/mips16/64")
1620 .Either(BigEndian, LittleEndian)
1623 .FilterOut(".*sof/nan2008")
1624 .FilterOut(NonExistent)
1625 .setIncludeDirsCallback([](StringRef InstallDir,
1626 StringRef TripleStr, const Multilib &M) {
1627 std::vector<std::string> Dirs;
1628 Dirs.push_back((InstallDir + "/include").str());
1629 std::string SysRootInc =
1630 InstallDir.str() + "/../../../../sysroot";
1631 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1632 Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1634 Dirs.push_back(SysRootInc + "/usr/include");
1639 // Check for Code Sourcery toolchain multilibs
1640 MultilibSet CSMipsMultilibs;
1642 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1644 auto MArchMicroMips =
1645 makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1647 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1649 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1651 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1653 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1656 makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1658 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1660 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1662 // Note that this one's osSuffix is ""
1663 auto MAbi64 = makeMultilib("")
1665 .includeSuffix("/64")
1672 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1674 .Either(SoftFloat, Nan2008, DefaultFloat)
1675 .FilterOut("/micromips/nan2008")
1676 .FilterOut("/mips16/nan2008")
1677 .Either(BigEndian, LittleEndian)
1679 .FilterOut("/mips16.*/64")
1680 .FilterOut("/micromips.*/64")
1681 .FilterOut(NonExistent)
1682 .setIncludeDirsCallback([](StringRef InstallDir,
1683 StringRef TripleStr, const Multilib &M) {
1684 std::vector<std::string> Dirs;
1685 Dirs.push_back((InstallDir + "/include").str());
1686 std::string SysRootInc =
1687 InstallDir.str() + "/../../../../" + TripleStr.str();
1688 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1689 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1691 Dirs.push_back(SysRootInc + "/libc/usr/include");
1696 MultilibSet AndroidMipsMultilibs =
1698 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1699 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1700 .FilterOut(NonExistent);
1702 MultilibSet DebianMipsMultilibs;
1705 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1707 Multilib M64 = Multilib()
1709 .includeSuffix("/64")
1714 Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1716 DebianMipsMultilibs =
1717 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1720 MultilibSet ImgMultilibs;
1722 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1724 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1727 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1733 .Maybe(LittleEndian)
1734 .FilterOut(NonExistent)
1735 .setIncludeDirsCallback([](StringRef InstallDir,
1736 StringRef TripleStr, const Multilib &M) {
1737 std::vector<std::string> Dirs;
1738 Dirs.push_back((InstallDir + "/include").str());
1740 (InstallDir + "/../../../../sysroot/usr/include").str());
1747 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1749 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1751 Multilib::flags_list Flags;
1752 addMultilibFlag(isMips32(TargetArch), "m32", Flags);
1753 addMultilibFlag(isMips64(TargetArch), "m64", Flags);
1754 addMultilibFlag(isMips16(Args), "mips16", Flags);
1755 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1756 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1757 CPUName == "mips32r5",
1758 "march=mips32r2", Flags);
1759 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1760 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1761 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1762 CPUName == "mips64r5" || CPUName == "octeon",
1763 "march=mips64r2", Flags);
1764 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1765 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1766 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1768 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1769 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1770 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1771 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1772 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1773 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1775 if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
1776 // Select Android toolchain. It's the only choice in that case.
1777 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1778 Result.Multilibs = AndroidMipsMultilibs;
1784 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1785 TargetTriple.getOS() == llvm::Triple::Linux &&
1786 TargetTriple.getEnvironment() == llvm::Triple::GNU) {
1787 // Select mips-img-linux-gnu toolchain.
1788 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
1789 Result.Multilibs = ImgMultilibs;
1795 // Sort candidates. Toolchain that best meets the directories goes first.
1796 // Then select the first toolchains matches command line flags.
1797 MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
1800 std::begin(candidates), std::end(candidates),
1801 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
1802 for (const auto &candidate : candidates) {
1803 if (candidate->select(Flags, Result.SelectedMultilib)) {
1804 if (candidate == &DebianMipsMultilibs)
1805 Result.BiarchSibling = Multilib();
1806 Result.Multilibs = *candidate;
1812 // Fallback to the regular toolchain-tree structure.
1814 Result.Multilibs.push_back(Default);
1815 Result.Multilibs.FilterOut(NonExistent);
1817 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1818 Result.BiarchSibling = Multilib();
1826 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
1827 StringRef Path, const ArgList &Args,
1828 bool NeedsBiarchSuffix,
1829 DetectedMultilibs &Result) {
1831 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1832 // in what would normally be GCCInstallPath and put the 64-bit
1833 // libs in a subdirectory named 64. The simple logic we follow is that
1834 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1835 // we use that. If not, and if not a biarch triple alias, we look for
1836 // crtbegin.o without the subdirectory.
1839 Multilib Alt64 = Multilib()
1841 .includeSuffix("/64")
1845 Multilib Alt32 = Multilib()
1847 .includeSuffix("/32")
1851 Multilib Altx32 = Multilib()
1853 .includeSuffix("/x32")
1858 FilterNonExistent NonExistent(Path);
1860 // Determine default multilib from: 32, 64, x32
1861 // Also handle cases such as 64 on 32, 32 on 64, etc.
1862 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1863 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1864 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1866 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1868 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1871 if (TargetTriple.isArch32Bit())
1872 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1874 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1876 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1880 Default.flag("+m32").flag("-m64").flag("-mx32");
1881 else if (Want == WANT64)
1882 Default.flag("-m32").flag("+m64").flag("-mx32");
1883 else if (Want == WANTX32)
1884 Default.flag("-m32").flag("-m64").flag("+mx32");
1888 Result.Multilibs.push_back(Default);
1889 Result.Multilibs.push_back(Alt64);
1890 Result.Multilibs.push_back(Alt32);
1891 Result.Multilibs.push_back(Altx32);
1893 Result.Multilibs.FilterOut(NonExistent);
1895 Multilib::flags_list Flags;
1896 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1897 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1898 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1900 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1903 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1904 Result.SelectedMultilib == Altx32)
1905 Result.BiarchSibling = Default;
1910 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1911 const llvm::Triple &TargetTriple, const ArgList &Args,
1912 const std::string &LibDir, StringRef CandidateTriple,
1913 bool NeedsBiarchSuffix) {
1914 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1915 // There are various different suffixes involving the triple we
1916 // check for. We also record what is necessary to walk from each back
1917 // up to the lib directory.
1918 const std::string LibSuffixes[] = {
1919 "/gcc/" + CandidateTriple.str(),
1920 // Debian puts cross-compilers in gcc-cross
1921 "/gcc-cross/" + CandidateTriple.str(),
1922 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1924 // The Freescale PPC SDK has the gcc libraries in
1925 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1926 "/" + CandidateTriple.str(),
1928 // Ubuntu has a strange mis-matched pair of triples that this happens to
1930 // FIXME: It may be worthwhile to generalize this and look for a second
1932 "/i386-linux-gnu/gcc/" + CandidateTriple.str()};
1933 const std::string InstallSuffixes[] = {
1934 "/../../..", // gcc/
1935 "/../../..", // gcc-cross/
1936 "/../../../..", // <triple>/gcc/
1937 "/../..", // <triple>/
1938 "/../../../.." // i386-linux-gnu/gcc/<triple>/
1940 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1941 const unsigned NumLibSuffixes =
1942 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1943 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1944 StringRef LibSuffix = LibSuffixes[i];
1946 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1947 !EC && LI != LE; LI = LI.increment(EC)) {
1948 StringRef VersionText = llvm::sys::path::filename(LI->path());
1949 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1950 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1951 if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1952 continue; // Saw this path before; no need to look at it again.
1953 if (CandidateVersion.isOlderThan(4, 1, 1))
1955 if (CandidateVersion <= Version)
1958 DetectedMultilibs Detected;
1960 // Debian mips multilibs behave more like the rest of the biarch ones,
1961 // so handle them there
1962 if (isMipsArch(TargetArch)) {
1963 if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
1965 } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
1966 NeedsBiarchSuffix, Detected)) {
1970 Multilibs = Detected.Multilibs;
1971 SelectedMultilib = Detected.SelectedMultilib;
1972 BiarchSibling = Detected.BiarchSibling;
1973 Version = CandidateVersion;
1974 GCCTriple.setTriple(CandidateTriple);
1975 // FIXME: We hack together the directory name here instead of
1976 // using LI to ensure stable path separators across Windows and
1978 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1979 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1985 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
1986 const ArgList &Args)
1987 : ToolChain(D, Triple, Args), GCCInstallation() {
1988 getProgramPaths().push_back(getDriver().getInstalledDir());
1989 if (getDriver().getInstalledDir() != getDriver().Dir)
1990 getProgramPaths().push_back(getDriver().Dir);
1993 Generic_GCC::~Generic_GCC() {}
1995 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
1997 case Action::PreprocessJobClass:
1999 Preprocess.reset(new tools::gcc::Preprocessor(*this));
2000 return Preprocess.get();
2001 case Action::CompileJobClass:
2003 Compile.reset(new tools::gcc::Compiler(*this));
2004 return Compile.get();
2006 return ToolChain::getTool(AC);
2010 Tool *Generic_GCC::buildAssembler() const {
2011 return new tools::gnutools::Assembler(*this);
2014 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2016 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2017 // Print the information about how we detected the GCC installation.
2018 GCCInstallation.print(OS);
2021 bool Generic_GCC::IsUnwindTablesDefault() const {
2022 return getArch() == llvm::Triple::x86_64;
2025 bool Generic_GCC::isPICDefault() const {
2026 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2029 bool Generic_GCC::isPIEDefault() const { return false; }
2031 bool Generic_GCC::isPICDefaultForced() const {
2032 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2035 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2036 switch (getTriple().getArch()) {
2037 case llvm::Triple::x86:
2038 case llvm::Triple::x86_64:
2039 case llvm::Triple::aarch64:
2040 case llvm::Triple::aarch64_be:
2041 case llvm::Triple::arm:
2042 case llvm::Triple::armeb:
2043 case llvm::Triple::bpfel:
2044 case llvm::Triple::bpfeb:
2045 case llvm::Triple::thumb:
2046 case llvm::Triple::thumbeb:
2047 case llvm::Triple::ppc:
2048 case llvm::Triple::ppc64:
2049 case llvm::Triple::ppc64le:
2050 case llvm::Triple::sparc:
2051 case llvm::Triple::sparcel:
2052 case llvm::Triple::sparcv9:
2053 case llvm::Triple::systemz:
2060 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2061 ArgStringList &CC1Args) const {
2062 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2063 bool UseInitArrayDefault =
2064 getTriple().getArch() == llvm::Triple::aarch64 ||
2065 getTriple().getArch() == llvm::Triple::aarch64_be ||
2066 (getTriple().getOS() == llvm::Triple::Linux &&
2067 (!V.isOlderThan(4, 7, 0) ||
2068 getTriple().getEnvironment() == llvm::Triple::Android)) ||
2069 getTriple().getOS() == llvm::Triple::NaCl;
2071 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2072 options::OPT_fno_use_init_array, UseInitArrayDefault))
2073 CC1Args.push_back("-fuse-init-array");
2076 /// Hexagon Toolchain
2078 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
2079 const ArgList &Args) {
2081 // Locate the rest of the toolchain ...
2082 std::string GccToolchain = getGCCToolchainDir(Args);
2084 if (!GccToolchain.empty())
2085 return GccToolchain;
2087 std::string InstallRelDir = InstalledDir + "/../../gnu";
2088 if (llvm::sys::fs::exists(InstallRelDir))
2089 return InstallRelDir;
2091 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
2092 if (llvm::sys::fs::exists(PrefixRelDir))
2093 return PrefixRelDir;
2095 return InstallRelDir;
2098 const char *Hexagon_TC::GetSmallDataThreshold(const ArgList &Args) {
2101 A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
2102 options::OPT_msmall_data_threshold_EQ);
2104 return A->getValue();
2106 A = Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2114 bool Hexagon_TC::UsesG0(const char *smallDataThreshold) {
2115 return smallDataThreshold && smallDataThreshold[0] == '0';
2118 static void GetHexagonLibraryPaths(const ArgList &Args, const std::string &Ver,
2119 const std::string &MarchString,
2120 const std::string &InstalledDir,
2121 ToolChain::path_list *LibPaths) {
2122 bool buildingLib = Args.hasArg(options::OPT_shared);
2124 //----------------------------------------------------------------------------
2126 //----------------------------------------------------------------------------
2127 for (Arg *A : Args.filtered(options::OPT_L))
2128 for (const char *Value : A->getValues())
2129 LibPaths->push_back(Value);
2131 //----------------------------------------------------------------------------
2132 // Other standard paths
2133 //----------------------------------------------------------------------------
2134 const std::string MarchSuffix = "/" + MarchString;
2135 const std::string G0Suffix = "/G0";
2136 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
2137 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
2139 // lib/gcc/hexagon/...
2140 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
2142 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
2143 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
2145 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
2146 LibPaths->push_back(LibGCCHexagonDir + Ver);
2149 LibPaths->push_back(RootDir + "lib/gcc");
2152 std::string HexagonLibDir = RootDir + "hexagon/lib";
2154 LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
2155 LibPaths->push_back(HexagonLibDir + G0Suffix);
2157 LibPaths->push_back(HexagonLibDir + MarchSuffix);
2158 LibPaths->push_back(HexagonLibDir);
2161 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
2162 const ArgList &Args)
2163 : Linux(D, Triple, Args) {
2164 const std::string InstalledDir(getDriver().getInstalledDir());
2165 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
2167 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2169 const std::string BinDir(GnuDir + "/bin");
2170 if (llvm::sys::fs::exists(BinDir))
2171 getProgramPaths().push_back(BinDir);
2173 // Determine version of GCC libraries and headers to use.
2174 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
2176 GCCVersion MaxVersion = GCCVersion::Parse("0.0.0");
2177 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
2178 !ec && di != de; di = di.increment(ec)) {
2179 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
2180 if (MaxVersion < cv)
2183 GCCLibAndIncVersion = MaxVersion;
2185 ToolChain::path_list *LibPaths = &getFilePaths();
2187 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2188 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2189 // support 'linux' we'll need to fix this up
2192 GetHexagonLibraryPaths(Args, GetGCCLibAndIncVersion(), GetTargetCPU(Args),
2193 InstalledDir, LibPaths);
2196 Hexagon_TC::~Hexagon_TC() {}
2198 Tool *Hexagon_TC::buildAssembler() const {
2199 return new tools::hexagon::Assembler(*this);
2202 Tool *Hexagon_TC::buildLinker() const {
2203 return new tools::hexagon::Linker(*this);
2206 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2207 ArgStringList &CC1Args) const {
2208 const Driver &D = getDriver();
2210 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2211 DriverArgs.hasArg(options::OPT_nostdlibinc))
2214 std::string Ver(GetGCCLibAndIncVersion());
2215 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
2216 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
2217 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
2218 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
2219 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
2222 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2223 ArgStringList &CC1Args) const {
2225 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2226 DriverArgs.hasArg(options::OPT_nostdincxx))
2229 const Driver &D = getDriver();
2230 std::string Ver(GetGCCLibAndIncVersion());
2231 SmallString<128> IncludeDir(
2232 Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
2234 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
2235 llvm::sys::path::append(IncludeDir, Ver);
2236 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
2239 ToolChain::CXXStdlibType
2240 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
2241 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2243 return ToolChain::CST_Libstdcxx;
2245 StringRef Value = A->getValue();
2246 if (Value != "libstdc++") {
2247 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2250 return ToolChain::CST_Libstdcxx;
2253 static int getHexagonVersion(const ArgList &Args) {
2254 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
2255 // Select the default CPU (v4) if none was given.
2259 // FIXME: produce errors if we cannot parse the version.
2260 StringRef WhichHexagon = A->getValue();
2261 if (WhichHexagon.startswith("hexagonv")) {
2263 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
2266 if (WhichHexagon.startswith("v")) {
2268 if (!WhichHexagon.substr(1).getAsInteger(10, Val))
2272 // FIXME: should probably be an error.
2276 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args) {
2277 int V = getHexagonVersion(Args);
2278 // FIXME: We don't support versions < 4. We should error on them.
2281 llvm_unreachable("Unexpected version");
2297 NaCl_TC::NaCl_TC(const Driver &D, const llvm::Triple &Triple,
2298 const ArgList &Args)
2299 : Generic_ELF(D, Triple, Args) {
2301 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
2302 // default paths, and must instead only use the paths provided
2303 // with this toolchain based on architecture.
2304 path_list &file_paths = getFilePaths();
2305 path_list &prog_paths = getProgramPaths();
2310 // Path for library files (libc.a, ...)
2311 std::string FilePath(getDriver().Dir + "/../");
2313 // Path for tools (clang, ld, etc..)
2314 std::string ProgPath(getDriver().Dir + "/../");
2316 // Path for toolchain libraries (libgcc.a, ...)
2317 std::string ToolPath(getDriver().ResourceDir + "/lib/");
2319 switch (Triple.getArch()) {
2320 case llvm::Triple::x86: {
2321 file_paths.push_back(FilePath + "x86_64-nacl/lib32");
2322 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib32");
2323 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2324 file_paths.push_back(ToolPath + "i686-nacl");
2327 case llvm::Triple::x86_64: {
2328 file_paths.push_back(FilePath + "x86_64-nacl/lib");
2329 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
2330 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2331 file_paths.push_back(ToolPath + "x86_64-nacl");
2334 case llvm::Triple::arm: {
2335 file_paths.push_back(FilePath + "arm-nacl/lib");
2336 file_paths.push_back(FilePath + "arm-nacl/usr/lib");
2337 prog_paths.push_back(ProgPath + "arm-nacl/bin");
2338 file_paths.push_back(ToolPath + "arm-nacl");
2341 case llvm::Triple::mipsel: {
2342 file_paths.push_back(FilePath + "mipsel-nacl/lib");
2343 file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
2344 prog_paths.push_back(ProgPath + "bin");
2345 file_paths.push_back(ToolPath + "mipsel-nacl");
2352 // Use provided linker, not system linker
2353 Linker = GetProgramPath("ld");
2354 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
2357 void NaCl_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2358 ArgStringList &CC1Args) const {
2359 const Driver &D = getDriver();
2360 if (DriverArgs.hasArg(options::OPT_nostdinc))
2363 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2364 SmallString<128> P(D.ResourceDir);
2365 llvm::sys::path::append(P, "include");
2366 addSystemInclude(DriverArgs, CC1Args, P.str());
2369 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2372 SmallString<128> P(D.Dir + "/../");
2373 switch (getTriple().getArch()) {
2374 case llvm::Triple::arm:
2375 llvm::sys::path::append(P, "arm-nacl/usr/include");
2377 case llvm::Triple::x86:
2378 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2380 case llvm::Triple::x86_64:
2381 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2383 case llvm::Triple::mipsel:
2384 llvm::sys::path::append(P, "mipsel-nacl/usr/include");
2390 addSystemInclude(DriverArgs, CC1Args, P.str());
2391 llvm::sys::path::remove_filename(P);
2392 llvm::sys::path::remove_filename(P);
2393 llvm::sys::path::append(P, "include");
2394 addSystemInclude(DriverArgs, CC1Args, P.str());
2397 void NaCl_TC::AddCXXStdlibLibArgs(const ArgList &Args,
2398 ArgStringList &CmdArgs) const {
2399 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2400 // if the value is libc++, and emits an error for other values.
2401 GetCXXStdlibType(Args);
2402 CmdArgs.push_back("-lc++");
2405 void NaCl_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2406 ArgStringList &CC1Args) const {
2407 const Driver &D = getDriver();
2408 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2409 DriverArgs.hasArg(options::OPT_nostdincxx))
2412 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2413 // if the value is libc++, and emits an error for other values.
2414 GetCXXStdlibType(DriverArgs);
2416 SmallString<128> P(D.Dir + "/../");
2417 switch (getTriple().getArch()) {
2418 case llvm::Triple::arm:
2419 llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
2420 addSystemInclude(DriverArgs, CC1Args, P.str());
2422 case llvm::Triple::x86:
2423 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2424 addSystemInclude(DriverArgs, CC1Args, P.str());
2426 case llvm::Triple::x86_64:
2427 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2428 addSystemInclude(DriverArgs, CC1Args, P.str());
2430 case llvm::Triple::mipsel:
2431 llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
2432 addSystemInclude(DriverArgs, CC1Args, P.str());
2439 ToolChain::CXXStdlibType NaCl_TC::GetCXXStdlibType(const ArgList &Args) const {
2440 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2441 StringRef Value = A->getValue();
2442 if (Value == "libc++")
2443 return ToolChain::CST_Libcxx;
2444 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2447 return ToolChain::CST_Libcxx;
2450 std::string NaCl_TC::ComputeEffectiveClangTriple(const ArgList &Args,
2451 types::ID InputType) const {
2452 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
2453 if (TheTriple.getArch() == llvm::Triple::arm &&
2454 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2455 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
2456 return TheTriple.getTriple();
2459 Tool *NaCl_TC::buildLinker() const {
2460 return new tools::nacltools::Linker(*this);
2463 Tool *NaCl_TC::buildAssembler() const {
2464 if (getTriple().getArch() == llvm::Triple::arm)
2465 return new tools::nacltools::AssemblerARM(*this);
2466 return new tools::gnutools::Assembler(*this);
2470 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2471 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2472 /// Currently does not support anything else but compilation.
2474 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
2475 const ArgList &Args)
2476 : ToolChain(D, Triple, Args) {
2477 // Path mangling to find libexec
2478 std::string Path(getDriver().Dir);
2480 Path += "/../libexec";
2481 getProgramPaths().push_back(Path);
2484 TCEToolChain::~TCEToolChain() {}
2486 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
2488 bool TCEToolChain::isPICDefault() const { return false; }
2490 bool TCEToolChain::isPIEDefault() const { return false; }
2492 bool TCEToolChain::isPICDefaultForced() const { return false; }
2494 // CloudABI - CloudABI tool chain which can call ld(1) directly.
2496 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
2497 const ArgList &Args)
2498 : Generic_ELF(D, Triple, Args) {
2499 SmallString<128> P(getDriver().Dir);
2500 llvm::sys::path::append(P, "..", getTriple().str(), "lib");
2501 getFilePaths().push_back(P.str());
2504 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2505 ArgStringList &CC1Args) const {
2506 if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
2507 DriverArgs.hasArg(options::OPT_nostdincxx))
2510 SmallString<128> P(getDriver().Dir);
2511 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
2512 addSystemInclude(DriverArgs, CC1Args, P.str());
2515 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
2516 ArgStringList &CmdArgs) const {
2517 CmdArgs.push_back("-lc++");
2518 CmdArgs.push_back("-lc++abi");
2519 CmdArgs.push_back("-lunwind");
2522 Tool *CloudABI::buildLinker() const {
2523 return new tools::cloudabi::Linker(*this);
2526 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2528 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
2529 const ArgList &Args)
2530 : Generic_ELF(D, Triple, Args) {
2531 getFilePaths().push_back(getDriver().Dir + "/../lib");
2532 getFilePaths().push_back("/usr/lib");
2535 Tool *OpenBSD::buildAssembler() const {
2536 return new tools::openbsd::Assembler(*this);
2539 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
2541 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2543 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2544 : Generic_ELF(D, Triple, Args) {
2545 getFilePaths().push_back(getDriver().Dir + "/../lib");
2546 getFilePaths().push_back("/usr/lib");
2549 Tool *Bitrig::buildAssembler() const {
2550 return new tools::bitrig::Assembler(*this);
2553 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
2555 ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const {
2556 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2557 StringRef Value = A->getValue();
2558 if (Value == "libstdc++")
2559 return ToolChain::CST_Libstdcxx;
2560 if (Value == "libc++")
2561 return ToolChain::CST_Libcxx;
2563 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2565 return ToolChain::CST_Libcxx;
2568 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2569 ArgStringList &CC1Args) const {
2570 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2571 DriverArgs.hasArg(options::OPT_nostdincxx))
2574 switch (GetCXXStdlibType(DriverArgs)) {
2575 case ToolChain::CST_Libcxx:
2576 addSystemInclude(DriverArgs, CC1Args,
2577 getDriver().SysRoot + "/usr/include/c++/v1");
2579 case ToolChain::CST_Libstdcxx:
2580 addSystemInclude(DriverArgs, CC1Args,
2581 getDriver().SysRoot + "/usr/include/c++/stdc++");
2582 addSystemInclude(DriverArgs, CC1Args,
2583 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
2585 StringRef Triple = getTriple().str();
2586 if (Triple.startswith("amd64"))
2587 addSystemInclude(DriverArgs, CC1Args,
2588 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
2591 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
2592 "/usr/include/c++/stdc++/" +
2598 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
2599 ArgStringList &CmdArgs) const {
2600 switch (GetCXXStdlibType(Args)) {
2601 case ToolChain::CST_Libcxx:
2602 CmdArgs.push_back("-lc++");
2603 CmdArgs.push_back("-lc++abi");
2604 CmdArgs.push_back("-lpthread");
2606 case ToolChain::CST_Libstdcxx:
2607 CmdArgs.push_back("-lstdc++");
2612 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
2614 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
2615 const ArgList &Args)
2616 : Generic_ELF(D, Triple, Args) {
2618 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
2619 // back to '/usr/lib' if it doesn't exist.
2620 if ((Triple.getArch() == llvm::Triple::x86 ||
2621 Triple.getArch() == llvm::Triple::ppc) &&
2622 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
2623 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2625 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2628 ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2629 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2630 StringRef Value = A->getValue();
2631 if (Value == "libstdc++")
2632 return ToolChain::CST_Libstdcxx;
2633 if (Value == "libc++")
2634 return ToolChain::CST_Libcxx;
2636 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2638 if (getTriple().getOSMajorVersion() >= 10)
2639 return ToolChain::CST_Libcxx;
2640 return ToolChain::CST_Libstdcxx;
2643 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2644 ArgStringList &CC1Args) const {
2645 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2646 DriverArgs.hasArg(options::OPT_nostdincxx))
2649 switch (GetCXXStdlibType(DriverArgs)) {
2650 case ToolChain::CST_Libcxx:
2651 addSystemInclude(DriverArgs, CC1Args,
2652 getDriver().SysRoot + "/usr/include/c++/v1");
2654 case ToolChain::CST_Libstdcxx:
2655 addSystemInclude(DriverArgs, CC1Args,
2656 getDriver().SysRoot + "/usr/include/c++/4.2");
2657 addSystemInclude(DriverArgs, CC1Args,
2658 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2663 Tool *FreeBSD::buildAssembler() const {
2664 return new tools::freebsd::Assembler(*this);
2667 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
2669 bool FreeBSD::UseSjLjExceptions() const {
2670 // FreeBSD uses SjLj exceptions on ARM oabi.
2671 switch (getTriple().getEnvironment()) {
2672 case llvm::Triple::GNUEABIHF:
2673 case llvm::Triple::GNUEABI:
2674 case llvm::Triple::EABI:
2678 return (getTriple().getArch() == llvm::Triple::arm ||
2679 getTriple().getArch() == llvm::Triple::thumb);
2683 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
2685 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
2687 SanitizerMask FreeBSD::getSupportedSanitizers() const {
2688 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
2689 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2690 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
2691 getTriple().getArch() == llvm::Triple::mips64el;
2692 SanitizerMask Res = ToolChain::getSupportedSanitizers();
2693 Res |= SanitizerKind::Address;
2694 Res |= SanitizerKind::Vptr;
2695 if (IsX86_64 || IsMIPS64) {
2696 Res |= SanitizerKind::Leak;
2697 Res |= SanitizerKind::Thread;
2699 if (IsX86 || IsX86_64) {
2700 Res |= SanitizerKind::SafeStack;
2705 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2707 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2708 : Generic_ELF(D, Triple, Args) {
2710 if (getDriver().UseStdLib) {
2711 // When targeting a 32-bit platform, try the special directory used on
2712 // 64-bit hosts, and only fall back to the main library directory if that
2714 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2715 // what all logic is needed to emulate the '=' prefix here.
2716 switch (Triple.getArch()) {
2717 case llvm::Triple::x86:
2718 getFilePaths().push_back("=/usr/lib/i386");
2720 case llvm::Triple::arm:
2721 case llvm::Triple::armeb:
2722 case llvm::Triple::thumb:
2723 case llvm::Triple::thumbeb:
2724 switch (Triple.getEnvironment()) {
2725 case llvm::Triple::EABI:
2726 case llvm::Triple::GNUEABI:
2727 getFilePaths().push_back("=/usr/lib/eabi");
2729 case llvm::Triple::EABIHF:
2730 case llvm::Triple::GNUEABIHF:
2731 getFilePaths().push_back("=/usr/lib/eabihf");
2734 getFilePaths().push_back("=/usr/lib/oabi");
2738 case llvm::Triple::mips64:
2739 case llvm::Triple::mips64el:
2740 if (tools::mips::hasMipsAbiArg(Args, "o32"))
2741 getFilePaths().push_back("=/usr/lib/o32");
2742 else if (tools::mips::hasMipsAbiArg(Args, "64"))
2743 getFilePaths().push_back("=/usr/lib/64");
2745 case llvm::Triple::ppc:
2746 getFilePaths().push_back("=/usr/lib/powerpc");
2748 case llvm::Triple::sparc:
2749 getFilePaths().push_back("=/usr/lib/sparc");
2755 getFilePaths().push_back("=/usr/lib");
2759 Tool *NetBSD::buildAssembler() const {
2760 return new tools::netbsd::Assembler(*this);
2763 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
2765 ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2766 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2767 StringRef Value = A->getValue();
2768 if (Value == "libstdc++")
2769 return ToolChain::CST_Libstdcxx;
2770 if (Value == "libc++")
2771 return ToolChain::CST_Libcxx;
2773 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2776 unsigned Major, Minor, Micro;
2777 getTriple().getOSVersion(Major, Minor, Micro);
2778 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
2779 switch (getArch()) {
2780 case llvm::Triple::aarch64:
2781 case llvm::Triple::arm:
2782 case llvm::Triple::armeb:
2783 case llvm::Triple::thumb:
2784 case llvm::Triple::thumbeb:
2785 case llvm::Triple::ppc:
2786 case llvm::Triple::ppc64:
2787 case llvm::Triple::ppc64le:
2788 case llvm::Triple::x86:
2789 case llvm::Triple::x86_64:
2790 return ToolChain::CST_Libcxx;
2795 return ToolChain::CST_Libstdcxx;
2798 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2799 ArgStringList &CC1Args) const {
2800 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2801 DriverArgs.hasArg(options::OPT_nostdincxx))
2804 switch (GetCXXStdlibType(DriverArgs)) {
2805 case ToolChain::CST_Libcxx:
2806 addSystemInclude(DriverArgs, CC1Args,
2807 getDriver().SysRoot + "/usr/include/c++/");
2809 case ToolChain::CST_Libstdcxx:
2810 addSystemInclude(DriverArgs, CC1Args,
2811 getDriver().SysRoot + "/usr/include/g++");
2812 addSystemInclude(DriverArgs, CC1Args,
2813 getDriver().SysRoot + "/usr/include/g++/backward");
2818 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2820 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2821 : Generic_ELF(D, Triple, Args) {
2822 getFilePaths().push_back(getDriver().Dir + "/../lib");
2823 getFilePaths().push_back("/usr/lib");
2826 Tool *Minix::buildAssembler() const {
2827 return new tools::minix::Assembler(*this);
2830 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
2832 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2834 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
2835 const ArgList &Args)
2836 : Generic_GCC(D, Triple, Args) {
2838 getProgramPaths().push_back(getDriver().getInstalledDir());
2839 if (getDriver().getInstalledDir() != getDriver().Dir)
2840 getProgramPaths().push_back(getDriver().Dir);
2842 getFilePaths().push_back(getDriver().Dir + "/../lib");
2843 getFilePaths().push_back("/usr/lib");
2846 Tool *Solaris::buildAssembler() const {
2847 return new tools::solaris::Assembler(*this);
2850 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
2852 /// Distribution (very bare-bones at the moment).
2855 // NB: Releases of a particular Linux distro should be kept together
2856 // in this enum, because some tests are done by integer comparison against
2857 // the first and last known member in the family, e.g. IsRedHat().
2890 static bool IsRedhat(enum Distro Distro) {
2891 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
2894 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
2896 static bool IsDebian(enum Distro Distro) {
2897 return Distro >= DebianLenny && Distro <= DebianStretch;
2900 static bool IsUbuntu(enum Distro Distro) {
2901 return Distro >= UbuntuHardy && Distro <= UbuntuWily;
2904 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2905 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2906 llvm::MemoryBuffer::getFile("/etc/lsb-release");
2908 StringRef Data = File.get()->getBuffer();
2909 SmallVector<StringRef, 16> Lines;
2910 Data.split(Lines, "\n");
2911 Distro Version = UnknownDistro;
2912 for (const StringRef Line : Lines)
2913 if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
2914 Version = llvm::StringSwitch<Distro>(Line.substr(17))
2915 .Case("hardy", UbuntuHardy)
2916 .Case("intrepid", UbuntuIntrepid)
2917 .Case("jaunty", UbuntuJaunty)
2918 .Case("karmic", UbuntuKarmic)
2919 .Case("lucid", UbuntuLucid)
2920 .Case("maverick", UbuntuMaverick)
2921 .Case("natty", UbuntuNatty)
2922 .Case("oneiric", UbuntuOneiric)
2923 .Case("precise", UbuntuPrecise)
2924 .Case("quantal", UbuntuQuantal)
2925 .Case("raring", UbuntuRaring)
2926 .Case("saucy", UbuntuSaucy)
2927 .Case("trusty", UbuntuTrusty)
2928 .Case("utopic", UbuntuUtopic)
2929 .Case("vivid", UbuntuVivid)
2930 .Case("wily", UbuntuWily)
2931 .Default(UnknownDistro);
2935 File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
2937 StringRef Data = File.get()->getBuffer();
2938 if (Data.startswith("Fedora release"))
2940 if (Data.startswith("Red Hat Enterprise Linux") ||
2941 Data.startswith("CentOS")) {
2942 if (Data.find("release 7") != StringRef::npos)
2944 else if (Data.find("release 6") != StringRef::npos)
2946 else if (Data.find("release 5") != StringRef::npos)
2948 else if (Data.find("release 4") != StringRef::npos)
2951 return UnknownDistro;
2954 File = llvm::MemoryBuffer::getFile("/etc/debian_version");
2956 StringRef Data = File.get()->getBuffer();
2959 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2960 return DebianSqueeze;
2961 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
2962 return DebianWheezy;
2963 else if (Data.startswith("jessie/sid") || Data[0] == '8')
2964 return DebianJessie;
2965 else if (Data.startswith("stretch/sid") || Data[0] == '9')
2966 return DebianStretch;
2967 return UnknownDistro;
2970 if (llvm::sys::fs::exists("/etc/SuSE-release"))
2973 if (llvm::sys::fs::exists("/etc/exherbo-release"))
2976 if (llvm::sys::fs::exists("/etc/arch-release"))
2979 return UnknownDistro;
2982 /// \brief Get our best guess at the multiarch triple for a target.
2984 /// Debian-based systems are starting to use a multiarch setup where they use
2985 /// a target-triple directory in the library and header search paths.
2986 /// Unfortunately, this triple does not align with the vanilla target triple,
2987 /// so we provide a rough mapping here.
2988 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
2989 StringRef SysRoot) {
2990 llvm::Triple::EnvironmentType TargetEnvironment = TargetTriple.getEnvironment();
2992 // For most architectures, just use whatever we have rather than trying to be
2994 switch (TargetTriple.getArch()) {
2998 // We use the existence of '/lib/<triple>' as a directory to detect some
2999 // common linux triples that don't quite match the Clang triple for both
3000 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3001 // regardless of what the actual target triple is.
3002 case llvm::Triple::arm:
3003 case llvm::Triple::thumb:
3004 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3005 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3006 return "arm-linux-gnueabihf";
3008 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
3009 return "arm-linux-gnueabi";
3012 case llvm::Triple::armeb:
3013 case llvm::Triple::thumbeb:
3014 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3015 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3016 return "armeb-linux-gnueabihf";
3018 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3019 return "armeb-linux-gnueabi";
3022 case llvm::Triple::x86:
3023 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
3024 return "i386-linux-gnu";
3026 case llvm::Triple::x86_64:
3027 // We don't want this for x32, otherwise it will match x86_64 libs
3028 if (TargetEnvironment != llvm::Triple::GNUX32 &&
3029 llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
3030 return "x86_64-linux-gnu";
3032 case llvm::Triple::aarch64:
3033 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
3034 return "aarch64-linux-gnu";
3036 case llvm::Triple::aarch64_be:
3037 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3038 return "aarch64_be-linux-gnu";
3040 case llvm::Triple::mips:
3041 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
3042 return "mips-linux-gnu";
3044 case llvm::Triple::mipsel:
3045 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
3046 return "mipsel-linux-gnu";
3048 case llvm::Triple::mips64:
3049 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
3050 return "mips64-linux-gnu";
3051 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3052 return "mips64-linux-gnuabi64";
3054 case llvm::Triple::mips64el:
3055 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
3056 return "mips64el-linux-gnu";
3057 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
3058 return "mips64el-linux-gnuabi64";
3060 case llvm::Triple::ppc:
3061 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
3062 return "powerpc-linux-gnuspe";
3063 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
3064 return "powerpc-linux-gnu";
3066 case llvm::Triple::ppc64:
3067 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
3068 return "powerpc64-linux-gnu";
3070 case llvm::Triple::ppc64le:
3071 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
3072 return "powerpc64le-linux-gnu";
3074 case llvm::Triple::sparc:
3075 if (llvm::sys::fs::exists(SysRoot + "/lib/sparc-linux-gnu"))
3076 return "sparc-linux-gnu";
3078 case llvm::Triple::sparcv9:
3079 if (llvm::sys::fs::exists(SysRoot + "/lib/sparc64-linux-gnu"))
3080 return "sparc64-linux-gnu";
3083 return TargetTriple.str();
3086 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
3087 if (llvm::sys::fs::exists(Path))
3088 Paths.push_back(Path.str());
3091 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
3092 if (isMipsArch(Triple.getArch())) {
3093 // lib32 directory has a special meaning on MIPS targets.
3094 // It contains N32 ABI binaries. Use this folder if produce
3095 // code for N32 ABI only.
3096 if (tools::mips::hasMipsAbiArg(Args, "n32"))
3098 return Triple.isArch32Bit() ? "lib" : "lib64";
3101 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
3102 // using that variant while targeting other architectures causes problems
3103 // because the libraries are laid out in shared system roots that can't cope
3104 // with a 'lib32' library search path being considered. So we only enable
3105 // them when we know we may need it.
3107 // FIXME: This is a bit of a hack. We should really unify this code for
3108 // reasoning about oslibdir spellings with the lib dir spellings in the
3109 // GCCInstallationDetector, but that is a more significant refactoring.
3110 if (Triple.getArch() == llvm::Triple::x86 ||
3111 Triple.getArch() == llvm::Triple::ppc)
3114 if (Triple.getArch() == llvm::Triple::x86_64 &&
3115 Triple.getEnvironment() == llvm::Triple::GNUX32)
3118 return Triple.isArch32Bit() ? "lib" : "lib64";
3121 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3122 : Generic_ELF(D, Triple, Args) {
3123 GCCInstallation.init(D, Triple, Args);
3124 Multilibs = GCCInstallation.getMultilibs();
3125 llvm::Triple::ArchType Arch = Triple.getArch();
3126 std::string SysRoot = computeSysRoot();
3128 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3129 // least) put various tools in a triple-prefixed directory off of the parent
3130 // of the GCC installation. We use the GCC triple here to ensure that we end
3131 // up with tools that support the same amount of cross compiling as the
3132 // detected GCC installation. For example, if we find a GCC installation
3133 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3134 // used to target i386.
3135 // FIXME: This seems unlikely to be Linux-specific.
3136 ToolChain::path_list &PPaths = getProgramPaths();
3137 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3138 GCCInstallation.getTriple().str() + "/bin")
3141 Linker = GetLinkerPath();
3143 Distro Distro = DetectDistro(Arch);
3145 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
3146 ExtraOpts.push_back("-z");
3147 ExtraOpts.push_back("relro");
3150 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
3151 ExtraOpts.push_back("-X");
3153 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
3154 const bool IsMips = isMipsArch(Arch);
3156 if (IsMips && !SysRoot.empty())
3157 ExtraOpts.push_back("--sysroot=" + SysRoot);
3159 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
3160 // and the MIPS ABI require .dynsym to be sorted in different ways.
3161 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
3162 // ABI requires a mapping between the GOT and the symbol table.
3163 // Android loader does not support .gnu.hash.
3164 if (!IsMips && !IsAndroid) {
3165 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
3166 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
3167 ExtraOpts.push_back("--hash-style=gnu");
3169 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
3170 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
3171 ExtraOpts.push_back("--hash-style=both");
3174 if (IsRedhat(Distro))
3175 ExtraOpts.push_back("--no-add-needed");
3177 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
3178 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
3179 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
3180 ExtraOpts.push_back("--build-id");
3182 if (IsOpenSUSE(Distro))
3183 ExtraOpts.push_back("--enable-new-dtags");
3185 // The selection of paths to try here is designed to match the patterns which
3186 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
3187 // This was determined by running GCC in a fake filesystem, creating all
3188 // possible permutations of these directories, and seeing which ones it added
3189 // to the link paths.
3190 path_list &Paths = getFilePaths();
3192 const std::string OSLibDir = getOSLibDir(Triple, Args);
3193 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
3195 // Add the multilib suffixed paths where they are available.
3196 if (GCCInstallation.isValid()) {
3197 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3198 const std::string &LibPath = GCCInstallation.getParentLibPath();
3199 const Multilib &Multilib = GCCInstallation.getMultilib();
3201 // Sourcery CodeBench MIPS toolchain holds some libraries under
3202 // a biarch-like suffix of the GCC installation.
3203 addPathIfExists((GCCInstallation.getInstallPath() + Multilib.gccSuffix()),
3206 // GCC cross compiling toolchains will install target libraries which ship
3207 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3208 // any part of the GCC installation in
3209 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3210 // debatable, but is the reality today. We need to search this tree even
3211 // when we have a sysroot somewhere else. It is the responsibility of
3212 // whomever is doing the cross build targeting a sysroot using a GCC
3213 // installation that is *not* within the system root to ensure two things:
3215 // 1) Any DSOs that are linked in from this tree or from the install path
3216 // above must be present on the system root and found via an
3217 // appropriate rpath.
3218 // 2) There must not be libraries installed into
3219 // <prefix>/<triple>/<libdir> unless they should be preferred over
3220 // those within the system root.
3222 // Note that this matches the GCC behavior. See the below comment for where
3223 // Clang diverges from GCC's behavior.
3224 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3225 Multilib.osSuffix(),
3228 // If the GCC installation we found is inside of the sysroot, we want to
3229 // prefer libraries installed in the parent prefix of the GCC installation.
3230 // It is important to *not* use these paths when the GCC installation is
3231 // outside of the system root as that can pick up unintended libraries.
3232 // This usually happens when there is an external cross compiler on the
3233 // host system, and a more minimal sysroot available that is the target of
3234 // the cross. Note that GCC does include some of these directories in some
3235 // configurations but this seems somewhere between questionable and simply
3237 if (StringRef(LibPath).startswith(SysRoot)) {
3238 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
3239 addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
3243 // Similar to the logic for GCC above, if we currently running Clang inside
3244 // of the requested system root, add its parent library paths to
3246 // FIXME: It's not clear whether we should use the driver's installed
3247 // directory ('Dir' below) or the ResourceDir.
3248 if (StringRef(D.Dir).startswith(SysRoot)) {
3249 addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
3250 addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
3253 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
3254 addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
3255 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3256 addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3258 // Try walking via the GCC triple path in case of biarch or multiarch GCC
3259 // installations with strange symlinks.
3260 if (GCCInstallation.isValid()) {
3261 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3262 "/../../" + OSLibDir,
3265 // Add the 'other' biarch variant path
3266 Multilib BiarchSibling;
3267 if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3269 GCCInstallation.getInstallPath() + BiarchSibling.gccSuffix(), Paths);
3272 // See comments above on the multilib variant for details of why this is
3273 // included even from outside the sysroot.
3274 const std::string &LibPath = GCCInstallation.getParentLibPath();
3275 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3276 const Multilib &Multilib = GCCInstallation.getMultilib();
3277 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib" +
3278 Multilib.osSuffix(),
3281 // See comments above on the multilib variant for details of why this is
3282 // only included from within the sysroot.
3283 if (StringRef(LibPath).startswith(SysRoot))
3284 addPathIfExists(LibPath, Paths);
3287 // Similar to the logic for GCC above, if we are currently running Clang
3288 // inside of the requested system root, add its parent library path to those
3290 // FIXME: It's not clear whether we should use the driver's installed
3291 // directory ('Dir' below) or the ResourceDir.
3292 if (StringRef(D.Dir).startswith(SysRoot))
3293 addPathIfExists(D.Dir + "/../lib", Paths);
3295 addPathIfExists(SysRoot + "/lib", Paths);
3296 addPathIfExists(SysRoot + "/usr/lib", Paths);
3299 bool Linux::HasNativeLLVMSupport() const { return true; }
3301 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
3303 Tool *Linux::buildAssembler() const {
3304 return new tools::gnutools::Assembler(*this);
3307 std::string Linux::computeSysRoot() const {
3308 if (!getDriver().SysRoot.empty())
3309 return getDriver().SysRoot;
3311 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3312 return std::string();
3314 // Standalone MIPS toolchains use different names for sysroot folder
3315 // and put it into different places. Here we try to check some known
3318 const StringRef InstallDir = GCCInstallation.getInstallPath();
3319 const StringRef TripleStr = GCCInstallation.getTriple().str();
3320 const Multilib &Multilib = GCCInstallation.getMultilib();
3323 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
3326 if (llvm::sys::fs::exists(Path))
3329 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3331 if (llvm::sys::fs::exists(Path))
3334 return std::string();
3337 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3338 ArgStringList &CC1Args) const {
3339 const Driver &D = getDriver();
3340 std::string SysRoot = computeSysRoot();
3342 if (DriverArgs.hasArg(options::OPT_nostdinc))
3345 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3346 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3348 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3349 SmallString<128> P(D.ResourceDir);
3350 llvm::sys::path::append(P, "include");
3351 addSystemInclude(DriverArgs, CC1Args, P);
3354 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3357 // Check for configure-time C include directories.
3358 StringRef CIncludeDirs(C_INCLUDE_DIRS);
3359 if (CIncludeDirs != "") {
3360 SmallVector<StringRef, 5> dirs;
3361 CIncludeDirs.split(dirs, ":");
3362 for (StringRef dir : dirs) {
3364 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3365 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3370 // Lacking those, try to detect the correct set of system includes for the
3373 // Add include directories specific to the selected multilib set and multilib.
3374 if (GCCInstallation.isValid()) {
3375 const auto &Callback = Multilibs.includeDirsCallback();
3377 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3378 GCCInstallation.getTriple().str(),
3379 GCCInstallation.getMultilib());
3380 for (const auto &Path : IncludePaths)
3381 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3385 // Implement generic Debian multiarch support.
3386 const StringRef X86_64MultiarchIncludeDirs[] = {
3387 "/usr/include/x86_64-linux-gnu",
3389 // FIXME: These are older forms of multiarch. It's not clear that they're
3390 // in use in any released version of Debian, so we should consider
3392 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
3393 const StringRef X86MultiarchIncludeDirs[] = {
3394 "/usr/include/i386-linux-gnu",
3396 // FIXME: These are older forms of multiarch. It's not clear that they're
3397 // in use in any released version of Debian, so we should consider
3399 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3400 "/usr/include/i486-linux-gnu"};
3401 const StringRef AArch64MultiarchIncludeDirs[] = {
3402 "/usr/include/aarch64-linux-gnu"};
3403 const StringRef ARMMultiarchIncludeDirs[] = {
3404 "/usr/include/arm-linux-gnueabi"};
3405 const StringRef ARMHFMultiarchIncludeDirs[] = {
3406 "/usr/include/arm-linux-gnueabihf"};
3407 const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
3408 const StringRef MIPSELMultiarchIncludeDirs[] = {
3409 "/usr/include/mipsel-linux-gnu"};
3410 const StringRef MIPS64MultiarchIncludeDirs[] = {
3411 "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
3412 const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3413 "/usr/include/mips64el-linux-gnu",
3414 "/usr/include/mips64el-linux-gnuabi64"};
3415 const StringRef PPCMultiarchIncludeDirs[] = {
3416 "/usr/include/powerpc-linux-gnu"};
3417 const StringRef PPC64MultiarchIncludeDirs[] = {
3418 "/usr/include/powerpc64-linux-gnu"};
3419 const StringRef PPC64LEMultiarchIncludeDirs[] = {
3420 "/usr/include/powerpc64le-linux-gnu"};
3421 const StringRef SparcMultiarchIncludeDirs[] = {
3422 "/usr/include/sparc-linux-gnu"};
3423 const StringRef Sparc64MultiarchIncludeDirs[] = {
3424 "/usr/include/sparc64-linux-gnu"};
3425 ArrayRef<StringRef> MultiarchIncludeDirs;
3426 switch (getTriple().getArch()) {
3427 case llvm::Triple::x86_64:
3428 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3430 case llvm::Triple::x86:
3431 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3433 case llvm::Triple::aarch64:
3434 case llvm::Triple::aarch64_be:
3435 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3437 case llvm::Triple::arm:
3438 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3439 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3441 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3443 case llvm::Triple::mips:
3444 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3446 case llvm::Triple::mipsel:
3447 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3449 case llvm::Triple::mips64:
3450 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3452 case llvm::Triple::mips64el:
3453 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3455 case llvm::Triple::ppc:
3456 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3458 case llvm::Triple::ppc64:
3459 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3461 case llvm::Triple::ppc64le:
3462 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3464 case llvm::Triple::sparc:
3465 MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
3467 case llvm::Triple::sparcv9:
3468 MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
3473 for (StringRef Dir : MultiarchIncludeDirs) {
3474 if (llvm::sys::fs::exists(SysRoot + Dir)) {
3475 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
3480 if (getTriple().getOS() == llvm::Triple::RTEMS)
3483 // Add an include of '/include' directly. This isn't provided by default by
3484 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
3485 // add even when Clang is acting as-if it were a system compiler.
3486 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
3488 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
3491 /// \brief Helper to add the variant paths of a libstdc++ installation.
3492 /*static*/ bool Linux::addLibStdCXXIncludePaths(
3493 Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
3494 StringRef TargetMultiarchTriple, Twine IncludeSuffix,
3495 const ArgList &DriverArgs, ArgStringList &CC1Args) {
3496 if (!llvm::sys::fs::exists(Base + Suffix))
3499 addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
3501 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
3502 // that path exists or we have neither a GCC nor target multiarch triple, use
3503 // this vanilla search path.
3504 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
3505 llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
3506 addSystemInclude(DriverArgs, CC1Args,
3507 Base + Suffix + "/" + GCCTriple + IncludeSuffix);
3509 // Otherwise try to use multiarch naming schemes which have normalized the
3510 // triples and put the triple before the suffix.
3512 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
3513 // the target triple, so we support that here.
3514 addSystemInclude(DriverArgs, CC1Args,
3515 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
3516 addSystemInclude(DriverArgs, CC1Args,
3517 Base + "/" + TargetMultiarchTriple + Suffix);
3520 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3524 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3525 ArgStringList &CC1Args) const {
3526 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3527 DriverArgs.hasArg(options::OPT_nostdincxx))
3530 // Check if libc++ has been enabled and provide its include paths if so.
3531 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
3532 const std::string LibCXXIncludePathCandidates[] = {
3533 // The primary location is within the Clang installation.
3534 // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
3535 // newer ABI versions.
3536 getDriver().Dir + "/../include/c++/v1",
3538 // We also check the system as for a long time this is the only place
3540 // FIXME: We should really remove this. It doesn't make any sense.
3541 getDriver().SysRoot + "/usr/include/c++/v1"};
3542 for (const auto &IncludePath : LibCXXIncludePathCandidates) {
3543 if (!llvm::sys::fs::exists(IncludePath))
3545 // Add the first candidate that exists.
3546 addSystemInclude(DriverArgs, CC1Args, IncludePath);
3552 // We need a detected GCC installation on Linux to provide libstdc++'s
3553 // headers. We handled the libc++ case above.
3554 if (!GCCInstallation.isValid())
3557 // By default, look for the C++ headers in an include directory adjacent to
3558 // the lib directory of the GCC installation. Note that this is expect to be
3559 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3560 StringRef LibDir = GCCInstallation.getParentLibPath();
3561 StringRef InstallDir = GCCInstallation.getInstallPath();
3562 StringRef TripleStr = GCCInstallation.getTriple().str();
3563 const Multilib &Multilib = GCCInstallation.getMultilib();
3564 const std::string GCCMultiarchTriple =
3565 getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
3566 const std::string TargetMultiarchTriple =
3567 getMultiarchTriple(getTriple(), getDriver().SysRoot);
3568 const GCCVersion &Version = GCCInstallation.getVersion();
3570 // The primary search for libstdc++ supports multiarch variants.
3571 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3572 "/c++/" + Version.Text, TripleStr,
3573 GCCMultiarchTriple, TargetMultiarchTriple,
3574 Multilib.includeSuffix(), DriverArgs, CC1Args))
3577 // Otherwise, fall back on a bunch of options which don't use multiarch
3578 // layouts for simplicity.
3579 const std::string LibStdCXXIncludePathCandidates[] = {
3580 // Gentoo is weird and places its headers inside the GCC install,
3581 // so if the first attempt to find the headers fails, try these patterns.
3582 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3584 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3585 // Android standalone toolchain has C++ headers in yet another place.
3586 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
3587 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
3588 // without a subdirectory corresponding to the gcc version.
3589 LibDir.str() + "/../include/c++",
3592 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3593 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3594 /*GCCMultiarchTriple*/ "",
3595 /*TargetMultiarchTriple*/ "",
3596 Multilib.includeSuffix(), DriverArgs, CC1Args))
3601 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3603 SanitizerMask Linux::getSupportedSanitizers() const {
3604 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3605 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3606 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3607 getTriple().getArch() == llvm::Triple::mips64el;
3608 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
3609 getTriple().getArch() == llvm::Triple::ppc64le;
3610 SanitizerMask Res = ToolChain::getSupportedSanitizers();
3611 Res |= SanitizerKind::Address;
3612 Res |= SanitizerKind::KernelAddress;
3613 Res |= SanitizerKind::Vptr;
3614 if (IsX86_64 || IsMIPS64) {
3615 Res |= SanitizerKind::DataFlow;
3616 Res |= SanitizerKind::Leak;
3617 Res |= SanitizerKind::Thread;
3619 if (IsX86_64 || IsMIPS64 || IsPowerPC64)
3620 Res |= SanitizerKind::Memory;
3621 if (IsX86 || IsX86_64) {
3622 Res |= SanitizerKind::Function;
3623 Res |= SanitizerKind::SafeStack;
3628 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
3630 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
3631 const ArgList &Args)
3632 : Generic_ELF(D, Triple, Args) {
3634 // Path mangling to find libexec
3635 getProgramPaths().push_back(getDriver().getInstalledDir());
3636 if (getDriver().getInstalledDir() != getDriver().Dir)
3637 getProgramPaths().push_back(getDriver().Dir);
3639 getFilePaths().push_back(getDriver().Dir + "/../lib");
3640 getFilePaths().push_back("/usr/lib");
3641 if (llvm::sys::fs::exists("/usr/lib/gcc47"))
3642 getFilePaths().push_back("/usr/lib/gcc47");
3644 getFilePaths().push_back("/usr/lib/gcc44");
3647 Tool *DragonFly::buildAssembler() const {
3648 return new tools::dragonfly::Assembler(*this);
3651 Tool *DragonFly::buildLinker() const {
3652 return new tools::dragonfly::Linker(*this);
3655 /// Stub for CUDA toolchain. At the moment we don't have assembler or
3656 /// linker and need toolchain mainly to propagate device-side options
3659 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
3660 const ArgList &Args)
3661 : Linux(D, Triple, Args) {}
3664 CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3665 llvm::opt::ArgStringList &CC1Args) const {
3666 Linux::addClangTargetOptions(DriverArgs, CC1Args);
3667 CC1Args.push_back("-fcuda-is-device");
3670 llvm::opt::DerivedArgList *
3671 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
3672 const char *BoundArch) const {
3673 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3674 const OptTable &Opts = getDriver().getOpts();
3676 for (Arg *A : Args) {
3677 if (A->getOption().matches(options::OPT_Xarch__)) {
3678 // Skip this argument unless the architecture matches BoundArch
3679 if (A->getValue(0) != StringRef(BoundArch))
3682 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
3683 unsigned Prev = Index;
3684 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
3686 // If the argument parsing failed or more than one argument was
3687 // consumed, the -Xarch_ argument's parameter tried to consume
3688 // extra arguments. Emit an error and ignore.
3690 // We also want to disallow any options which would alter the
3691 // driver behavior; that isn't going to work in our model. We
3692 // use isDriverOption() as an approximation, although things
3693 // like -O4 are going to slip through.
3694 if (!XarchArg || Index > Prev + 1) {
3695 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
3696 << A->getAsString(Args);
3698 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
3699 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
3700 << A->getAsString(Args);
3703 XarchArg->setBaseArg(A);
3704 A = XarchArg.release();
3705 DAL->AddSynthesizedArg(A);
3710 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
3714 /// XCore tool chain
3715 XCore::XCore(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3716 : ToolChain(D, Triple, Args) {
3717 // ProgramPaths are found via 'PATH' environment variable.
3720 Tool *XCore::buildAssembler() const {
3721 return new tools::XCore::Assembler(*this);
3724 Tool *XCore::buildLinker() const { return new tools::XCore::Linker(*this); }
3726 bool XCore::isPICDefault() const { return false; }
3728 bool XCore::isPIEDefault() const { return false; }
3730 bool XCore::isPICDefaultForced() const { return false; }
3732 bool XCore::SupportsProfiling() const { return false; }
3734 bool XCore::hasBlocksRuntime() const { return false; }
3736 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3737 ArgStringList &CC1Args) const {
3738 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3739 DriverArgs.hasArg(options::OPT_nostdlibinc))
3741 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
3742 SmallVector<StringRef, 4> Dirs;
3743 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
3744 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3745 ArrayRef<StringRef> DirVec(Dirs);
3746 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3750 void XCore::addClangTargetOptions(const ArgList &DriverArgs,
3751 ArgStringList &CC1Args) const {
3752 CC1Args.push_back("-nostdsysteminc");
3755 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3756 ArgStringList &CC1Args) const {
3757 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3758 DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3759 DriverArgs.hasArg(options::OPT_nostdincxx))
3761 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
3762 SmallVector<StringRef, 4> Dirs;
3763 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
3764 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3765 ArrayRef<StringRef> DirVec(Dirs);
3766 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3770 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
3771 ArgStringList &CmdArgs) const {
3772 // We don't output any lib args. This is handled by xcc.
3775 // SHAVEToolChain does not call Clang's C compiler.
3776 // We override SelectTool to avoid testing ShouldUseClangCompiler().
3777 Tool *SHAVEToolChain::SelectTool(const JobAction &JA) const {
3778 switch (JA.getKind()) {
3779 case Action::CompileJobClass:
3781 Compiler.reset(new tools::SHAVE::Compiler(*this));
3782 return Compiler.get();
3783 case Action::AssembleJobClass:
3785 Assembler.reset(new tools::SHAVE::Assembler(*this));
3786 return Assembler.get();
3788 return ToolChain::getTool(JA.getKind());
3792 SHAVEToolChain::SHAVEToolChain(const Driver &D, const llvm::Triple &Triple,
3793 const ArgList &Args)
3794 : Generic_GCC(D, Triple, Args) {}
3796 SHAVEToolChain::~SHAVEToolChain() {}
3798 /// Following are methods necessary to avoid having moviClang be an abstract
3801 Tool *SHAVEToolChain::getTool(Action::ActionClass AC) const {
3802 // SelectTool() must find a tool using the method in the superclass.
3803 // There's nothing we can do if that fails.
3804 llvm_unreachable("SHAVEToolChain can't getTool");
3807 Tool *SHAVEToolChain::buildLinker() const {
3808 // SHAVEToolChain executables can not be linked except by the vendor tools.
3809 llvm_unreachable("SHAVEToolChain can't buildLinker");
3812 Tool *SHAVEToolChain::buildAssembler() const {
3813 // This one you'd think should be reachable since we expose an
3814 // assembler to the driver, except not the way it expects.
3815 llvm_unreachable("SHAVEToolChain can't buildAssembler");