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_instr_generate) ||
307 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
308 Args.hasArg(options::OPT_fcreate_profile) ||
309 Args.hasArg(options::OPT_coverage)))
312 // Select the appropriate runtime library for the target.
313 if (isTargetIOSBased())
314 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a",
315 /*AlwaysLink*/ true);
317 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a",
318 /*AlwaysLink*/ true);
321 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
322 ArgStringList &CmdArgs,
323 StringRef Sanitizer) const {
324 if (!Args.hasArg(options::OPT_dynamiclib) &&
325 !Args.hasArg(options::OPT_bundle)) {
326 // Sanitizer runtime libraries requires C++.
327 AddCXXStdlibLibArgs(Args, CmdArgs);
329 assert(isTargetMacOS() || isTargetIOSSimulator());
330 StringRef OS = isTargetMacOS() ? "osx" : "iossim";
333 (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
334 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
337 if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
338 // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
339 // all RTTI-related symbols that UBSan uses.
340 CmdArgs.push_back("-lc++abi");
344 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
345 ArgStringList &CmdArgs) const {
346 // Darwin only supports the compiler-rt based runtime libraries.
347 switch (GetRuntimeLibType(Args)) {
348 case ToolChain::RLT_CompilerRT:
351 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
352 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
356 // Darwin doesn't support real static executables, don't link any runtime
357 // libraries with -static.
358 if (Args.hasArg(options::OPT_static) ||
359 Args.hasArg(options::OPT_fapple_kext) ||
360 Args.hasArg(options::OPT_mkernel))
363 // Reject -static-libgcc for now, we can deal with this when and if someone
364 // cares. This is useful in situations where someone wants to statically link
365 // something like libstdc++, and needs its runtime support routines.
366 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
367 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
371 const SanitizerArgs &Sanitize = getSanitizerArgs();
372 if (Sanitize.needsAsanRt())
373 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
374 if (Sanitize.needsUbsanRt())
375 AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
377 // Otherwise link libSystem, then the dynamic runtime library, and finally any
378 // target specific static runtime library.
379 CmdArgs.push_back("-lSystem");
381 // Select the dynamic runtime library and the target specific static library.
382 if (isTargetIOSBased()) {
383 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
384 // it never went into the SDK.
385 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
386 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
387 getTriple().getArch() != llvm::Triple::aarch64)
388 CmdArgs.push_back("-lgcc_s.1");
390 // We currently always need a static runtime library for iOS.
391 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
393 assert(isTargetMacOS() && "unexpected non MacOS platform");
394 // The dynamic runtime library was merged with libSystem for 10.6 and
395 // beyond; only 10.4 and 10.5 need an additional runtime library.
396 if (isMacosxVersionLT(10, 5))
397 CmdArgs.push_back("-lgcc_s.10.4");
398 else if (isMacosxVersionLT(10, 6))
399 CmdArgs.push_back("-lgcc_s.10.5");
401 // For OS X, we thought we would only need a static runtime library when
402 // targeting 10.4, to provide versions of the static functions which were
403 // omitted from 10.4.dylib.
405 // Unfortunately, that turned out to not be true, because Darwin system
406 // headers can still use eprintf on i386, and it is not exported from
407 // libSystem. Therefore, we still must provide a runtime library just for
408 // the tiny tiny handful of projects that *might* use that symbol.
409 if (isMacosxVersionLT(10, 5)) {
410 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
412 if (getTriple().getArch() == llvm::Triple::x86)
413 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
414 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
419 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
420 const OptTable &Opts = getDriver().getOpts();
422 // Support allowing the SDKROOT environment variable used by xcrun and other
423 // Xcode tools to define the default sysroot, by making it the default for
425 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
426 // Warn if the path does not exist.
427 if (!llvm::sys::fs::exists(A->getValue()))
428 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
430 if (char *env = ::getenv("SDKROOT")) {
431 // We only use this value as the default if it is an absolute path,
432 // exists, and it is not the root path.
433 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
434 StringRef(env) != "/") {
435 Args.append(Args.MakeSeparateArg(
436 nullptr, Opts.getOption(options::OPT_isysroot), env));
441 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
442 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
444 if (OSXVersion && iOSVersion) {
445 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
446 << OSXVersion->getAsString(Args) << iOSVersion->getAsString(Args);
447 iOSVersion = nullptr;
448 } else if (!OSXVersion && !iOSVersion) {
449 // If no deployment target was specified on the command line, check for
450 // environment defines.
451 std::string OSXTarget;
452 std::string iOSTarget;
453 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
455 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
458 // If there is no command-line argument to specify the Target version and
459 // no environment variable defined, see if we can set the default based
461 if (iOSTarget.empty() && OSXTarget.empty() &&
462 Args.hasArg(options::OPT_isysroot)) {
463 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
464 StringRef isysroot = A->getValue();
465 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
466 size_t BeginSDK = isysroot.rfind("SDKs/");
467 size_t EndSDK = isysroot.rfind(".sdk");
468 if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
469 StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
470 // Slice the version number out.
471 // Version number is between the first and the last number.
472 size_t StartVer = SDK.find_first_of("0123456789");
473 size_t EndVer = SDK.find_last_of("0123456789");
474 if (StartVer != StringRef::npos && EndVer > StartVer) {
475 StringRef Version = SDK.slice(StartVer, EndVer + 1);
476 if (SDK.startswith("iPhoneOS") ||
477 SDK.startswith("iPhoneSimulator"))
479 else if (SDK.startswith("MacOSX"))
486 // If no OSX or iOS target has been specified, try to guess platform
487 // from arch name and compute the version from the triple.
488 if (OSXTarget.empty() && iOSTarget.empty()) {
489 StringRef MachOArchName = getMachOArchName(Args);
490 unsigned Major, Minor, Micro;
491 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
492 MachOArchName == "arm64") {
493 getTriple().getiOSVersion(Major, Minor, Micro);
494 llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
496 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
497 MachOArchName != "armv7em") {
498 if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
499 getDriver().Diag(diag::err_drv_invalid_darwin_version)
500 << getTriple().getOSName();
502 llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
507 // Allow conflicts among OSX and iOS for historical reasons, but choose the
509 if (!OSXTarget.empty() && !iOSTarget.empty()) {
510 if (getTriple().getArch() == llvm::Triple::arm ||
511 getTriple().getArch() == llvm::Triple::aarch64 ||
512 getTriple().getArch() == llvm::Triple::thumb)
518 if (!OSXTarget.empty()) {
519 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
520 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
521 Args.append(OSXVersion);
522 } else if (!iOSTarget.empty()) {
523 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
524 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
525 Args.append(iOSVersion);
529 DarwinPlatformKind Platform;
535 llvm_unreachable("Unable to infer Darwin variant");
537 // Set the tool chain target information.
538 unsigned Major, Minor, Micro;
540 if (Platform == MacOS) {
541 assert(!iOSVersion && "Unknown target platform!");
542 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
544 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
545 getDriver().Diag(diag::err_drv_invalid_version_number)
546 << OSXVersion->getAsString(Args);
547 } else if (Platform == IPhoneOS) {
548 assert(iOSVersion && "Unknown target platform!");
549 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
551 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
552 getDriver().Diag(diag::err_drv_invalid_version_number)
553 << iOSVersion->getAsString(Args);
555 llvm_unreachable("unknown kind of Darwin platform");
557 // Recognize iOS targets with an x86 architecture as the iOS simulator.
558 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
559 getTriple().getArch() == llvm::Triple::x86_64))
560 Platform = IPhoneOSSimulator;
562 setTarget(Platform, Major, Minor, Micro);
565 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
566 ArgStringList &CmdArgs) const {
567 CXXStdlibType Type = GetCXXStdlibType(Args);
570 case ToolChain::CST_Libcxx:
571 CmdArgs.push_back("-lc++");
574 case ToolChain::CST_Libstdcxx: {
575 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
576 // it was previously found in the gcc lib dir. However, for all the Darwin
577 // platforms we care about it was -lstdc++.6, so we search for that
578 // explicitly if we can't see an obvious -lstdc++ candidate.
580 // Check in the sysroot first.
581 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
582 SmallString<128> P(A->getValue());
583 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
585 if (!llvm::sys::fs::exists(P)) {
586 llvm::sys::path::remove_filename(P);
587 llvm::sys::path::append(P, "libstdc++.6.dylib");
588 if (llvm::sys::fs::exists(P)) {
589 CmdArgs.push_back(Args.MakeArgString(P));
595 // Otherwise, look in the root.
596 // FIXME: This should be removed someday when we don't have to care about
597 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
598 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
599 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
600 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
604 // Otherwise, let the linker search.
605 CmdArgs.push_back("-lstdc++");
611 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
612 ArgStringList &CmdArgs) const {
614 // For Darwin platforms, use the compiler-rt-based support library
615 // instead of the gcc-provided one (which is also incidentally
616 // only present in the gcc lib dir, which makes it hard to find).
618 SmallString<128> P(getDriver().ResourceDir);
619 llvm::sys::path::append(P, "lib", "darwin");
621 // Use the newer cc_kext for iOS ARM after 6.0.
622 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
623 getTriple().getArch() == llvm::Triple::aarch64 ||
624 !isIPhoneOSVersionLT(6, 0)) {
625 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
627 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
630 // For now, allow missing resource libraries to support developers who may
631 // not have compiler-rt checked out or integrated into their build.
632 if (llvm::sys::fs::exists(P))
633 CmdArgs.push_back(Args.MakeArgString(P));
636 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
637 const char *BoundArch) const {
638 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
639 const OptTable &Opts = getDriver().getOpts();
641 // FIXME: We really want to get out of the tool chain level argument
642 // translation business, as it makes the driver functionality much
643 // more opaque. For now, we follow gcc closely solely for the
644 // purpose of easily achieving feature parity & testability. Once we
645 // have something that works, we should reevaluate each translation
646 // and try to push it down into tool specific logic.
648 for (Arg *A : Args) {
649 if (A->getOption().matches(options::OPT_Xarch__)) {
650 // Skip this argument unless the architecture matches either the toolchain
651 // triple arch, or the arch being bound.
652 llvm::Triple::ArchType XarchArch =
653 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
654 if (!(XarchArch == getArch() ||
657 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
660 Arg *OriginalArg = A;
661 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
662 unsigned Prev = Index;
663 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
665 // If the argument parsing failed or more than one argument was
666 // consumed, the -Xarch_ argument's parameter tried to consume
667 // extra arguments. Emit an error and ignore.
669 // We also want to disallow any options which would alter the
670 // driver behavior; that isn't going to work in our model. We
671 // use isDriverOption() as an approximation, although things
672 // like -O4 are going to slip through.
673 if (!XarchArg || Index > Prev + 1) {
674 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
675 << A->getAsString(Args);
677 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
678 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
679 << A->getAsString(Args);
683 XarchArg->setBaseArg(A);
685 A = XarchArg.release();
686 DAL->AddSynthesizedArg(A);
688 // Linker input arguments require custom handling. The problem is that we
689 // have already constructed the phase actions, so we can not treat them as
690 // "input arguments".
691 if (A->getOption().hasFlag(options::LinkerInput)) {
692 // Convert the argument into individual Zlinker_input_args.
693 for (const char *Value : A->getValues()) {
695 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
701 // Sob. These is strictly gcc compatible for the time being. Apple
702 // gcc translates options twice, which means that self-expanding
703 // options add duplicates.
704 switch ((options::ID)A->getOption().getID()) {
709 case options::OPT_mkernel:
710 case options::OPT_fapple_kext:
712 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
715 case options::OPT_dependency_file:
716 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
719 case options::OPT_gfull:
720 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
722 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
725 case options::OPT_gused:
726 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
728 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
731 case options::OPT_shared:
732 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
735 case options::OPT_fconstant_cfstrings:
736 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
739 case options::OPT_fno_constant_cfstrings:
740 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
743 case options::OPT_Wnonportable_cfstrings:
745 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
748 case options::OPT_Wno_nonportable_cfstrings:
750 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
753 case options::OPT_fpascal_strings:
754 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
757 case options::OPT_fno_pascal_strings:
758 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
763 if (getTriple().getArch() == llvm::Triple::x86 ||
764 getTriple().getArch() == llvm::Triple::x86_64)
765 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
766 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
769 // Add the arch options based on the particular spelling of -arch, to match
770 // how the driver driver works.
772 StringRef Name = BoundArch;
773 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
774 const Option MArch = Opts.getOption(options::OPT_march_EQ);
776 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
777 // which defines the list of which architectures we accept.
780 else if (Name == "ppc601")
781 DAL->AddJoinedArg(nullptr, MCpu, "601");
782 else if (Name == "ppc603")
783 DAL->AddJoinedArg(nullptr, MCpu, "603");
784 else if (Name == "ppc604")
785 DAL->AddJoinedArg(nullptr, MCpu, "604");
786 else if (Name == "ppc604e")
787 DAL->AddJoinedArg(nullptr, MCpu, "604e");
788 else if (Name == "ppc750")
789 DAL->AddJoinedArg(nullptr, MCpu, "750");
790 else if (Name == "ppc7400")
791 DAL->AddJoinedArg(nullptr, MCpu, "7400");
792 else if (Name == "ppc7450")
793 DAL->AddJoinedArg(nullptr, MCpu, "7450");
794 else if (Name == "ppc970")
795 DAL->AddJoinedArg(nullptr, MCpu, "970");
797 else if (Name == "ppc64" || Name == "ppc64le")
798 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
800 else if (Name == "i386")
802 else if (Name == "i486")
803 DAL->AddJoinedArg(nullptr, MArch, "i486");
804 else if (Name == "i586")
805 DAL->AddJoinedArg(nullptr, MArch, "i586");
806 else if (Name == "i686")
807 DAL->AddJoinedArg(nullptr, MArch, "i686");
808 else if (Name == "pentium")
809 DAL->AddJoinedArg(nullptr, MArch, "pentium");
810 else if (Name == "pentium2")
811 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
812 else if (Name == "pentpro")
813 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
814 else if (Name == "pentIIm3")
815 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
817 else if (Name == "x86_64")
818 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
819 else if (Name == "x86_64h") {
820 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
821 DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
824 else if (Name == "arm")
825 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
826 else if (Name == "armv4t")
827 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
828 else if (Name == "armv5")
829 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
830 else if (Name == "xscale")
831 DAL->AddJoinedArg(nullptr, MArch, "xscale");
832 else if (Name == "armv6")
833 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
834 else if (Name == "armv6m")
835 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
836 else if (Name == "armv7")
837 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
838 else if (Name == "armv7em")
839 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
840 else if (Name == "armv7k")
841 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
842 else if (Name == "armv7m")
843 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
844 else if (Name == "armv7s")
845 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
851 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
852 ArgStringList &CmdArgs) const {
853 // Embedded targets are simple at the moment, not supporting sanitizers and
854 // with different libraries for each member of the product { static, PIC } x
855 // { hard-float, soft-float }
856 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
858 tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
861 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
863 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
866 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
867 const char *BoundArch) const {
868 // First get the generic Apple args, before moving onto Darwin-specific ones.
869 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
870 const OptTable &Opts = getDriver().getOpts();
872 // If no architecture is bound, none of the translations here are relevant.
876 // Add an explicit version min argument for the deployment target. We do this
877 // after argument translation because -Xarch_ arguments may add a version min
879 AddDeploymentTarget(*DAL);
881 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
882 // FIXME: It would be far better to avoid inserting those -static arguments,
883 // but we can't check the deployment target in the translation code until
885 if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
886 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie;) {
889 if (A->getOption().getID() != options::OPT_mkernel &&
890 A->getOption().getID() != options::OPT_fapple_kext)
892 assert(it != ie && "unexpected argument translation");
894 assert(A->getOption().getID() == options::OPT_static &&
895 "missing expected -static argument");
896 it = DAL->getArgs().erase(it);
900 // Default to use libc++ on OS X 10.9+ and iOS 7+.
901 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
902 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
903 !Args.getLastArg(options::OPT_stdlib_EQ))
904 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
907 // Validate the C++ standard library choice.
908 CXXStdlibType Type = GetCXXStdlibType(*DAL);
909 if (Type == ToolChain::CST_Libcxx) {
910 // Check whether the target provides libc++.
913 // Complain about targeting iOS < 5.0 in any way.
914 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
917 if (where != StringRef()) {
918 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
925 bool MachO::IsUnwindTablesDefault() const {
926 return getArch() == llvm::Triple::x86_64;
929 bool MachO::UseDwarfDebugFlags() const {
930 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
935 bool Darwin::UseSjLjExceptions() const {
936 // Darwin uses SjLj exceptions on ARM.
937 return (getTriple().getArch() == llvm::Triple::arm ||
938 getTriple().getArch() == llvm::Triple::thumb);
941 bool MachO::isPICDefault() const { return true; }
943 bool MachO::isPIEDefault() const { return false; }
945 bool MachO::isPICDefaultForced() const {
946 return (getArch() == llvm::Triple::x86_64 ||
947 getArch() == llvm::Triple::aarch64);
950 bool MachO::SupportsProfiling() const {
951 // Profiling instrumentation is only supported on x86.
952 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
955 void Darwin::addMinVersionArgs(const ArgList &Args,
956 ArgStringList &CmdArgs) const {
957 VersionTuple TargetVersion = getTargetVersion();
959 if (isTargetIOSSimulator())
960 CmdArgs.push_back("-ios_simulator_version_min");
961 else if (isTargetIOSBased())
962 CmdArgs.push_back("-iphoneos_version_min");
964 assert(isTargetMacOS() && "unexpected target");
965 CmdArgs.push_back("-macosx_version_min");
968 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
971 void Darwin::addStartObjectFileArgs(const ArgList &Args,
972 ArgStringList &CmdArgs) const {
973 // Derived from startfile spec.
974 if (Args.hasArg(options::OPT_dynamiclib)) {
975 // Derived from darwin_dylib1 spec.
976 if (isTargetIOSSimulator()) {
977 ; // iOS simulator does not need dylib1.o.
978 } else if (isTargetIPhoneOS()) {
979 if (isIPhoneOSVersionLT(3, 1))
980 CmdArgs.push_back("-ldylib1.o");
982 if (isMacosxVersionLT(10, 5))
983 CmdArgs.push_back("-ldylib1.o");
984 else if (isMacosxVersionLT(10, 6))
985 CmdArgs.push_back("-ldylib1.10.5.o");
988 if (Args.hasArg(options::OPT_bundle)) {
989 if (!Args.hasArg(options::OPT_static)) {
990 // Derived from darwin_bundle1 spec.
991 if (isTargetIOSSimulator()) {
992 ; // iOS simulator does not need bundle1.o.
993 } else if (isTargetIPhoneOS()) {
994 if (isIPhoneOSVersionLT(3, 1))
995 CmdArgs.push_back("-lbundle1.o");
997 if (isMacosxVersionLT(10, 6))
998 CmdArgs.push_back("-lbundle1.o");
1002 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1003 if (Args.hasArg(options::OPT_static) ||
1004 Args.hasArg(options::OPT_object) ||
1005 Args.hasArg(options::OPT_preload)) {
1006 CmdArgs.push_back("-lgcrt0.o");
1008 CmdArgs.push_back("-lgcrt1.o");
1010 // darwin_crt2 spec is empty.
1012 // By default on OS X 10.8 and later, we don't link with a crt1.o
1013 // file and the linker knows to use _main as the entry point. But,
1014 // when compiling with -pg, we need to link with the gcrt1.o file,
1015 // so pass the -no_new_main option to tell the linker to use the
1016 // "start" symbol as the entry point.
1017 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1018 CmdArgs.push_back("-no_new_main");
1020 if (Args.hasArg(options::OPT_static) ||
1021 Args.hasArg(options::OPT_object) ||
1022 Args.hasArg(options::OPT_preload)) {
1023 CmdArgs.push_back("-lcrt0.o");
1025 // Derived from darwin_crt1 spec.
1026 if (isTargetIOSSimulator()) {
1027 ; // iOS simulator does not need crt1.o.
1028 } else if (isTargetIPhoneOS()) {
1029 if (getArch() == llvm::Triple::aarch64)
1030 ; // iOS does not need any crt1 files for arm64
1031 else if (isIPhoneOSVersionLT(3, 1))
1032 CmdArgs.push_back("-lcrt1.o");
1033 else if (isIPhoneOSVersionLT(6, 0))
1034 CmdArgs.push_back("-lcrt1.3.1.o");
1036 if (isMacosxVersionLT(10, 5))
1037 CmdArgs.push_back("-lcrt1.o");
1038 else if (isMacosxVersionLT(10, 6))
1039 CmdArgs.push_back("-lcrt1.10.5.o");
1040 else if (isMacosxVersionLT(10, 8))
1041 CmdArgs.push_back("-lcrt1.10.6.o");
1043 // darwin_crt2 spec is empty.
1050 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1051 isMacosxVersionLT(10, 5)) {
1052 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1053 CmdArgs.push_back(Str);
1057 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1059 void Darwin::CheckObjCARC() const {
1060 if (isTargetIOSBased() || (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1062 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1065 SanitizerMask Darwin::getSupportedSanitizers() const {
1066 SanitizerMask Res = ToolChain::getSupportedSanitizers();
1067 if (isTargetMacOS() || isTargetIOSSimulator())
1068 Res |= SanitizerKind::Address;
1069 if (isTargetMacOS()) {
1070 if (!isMacosxVersionLT(10, 9))
1071 Res |= SanitizerKind::Vptr;
1072 Res |= SanitizerKind::SafeStack;
1077 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1078 /// all subcommands; this relies on gcc translating the majority of
1079 /// command line options.
1081 /// \brief Parse a GCCVersion object out of a string of text.
1083 /// This is the primary means of forming GCCVersion objects.
1085 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1086 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1087 std::pair<StringRef, StringRef> First = VersionText.split('.');
1088 std::pair<StringRef, StringRef> Second = First.second.split('.');
1090 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1091 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1093 GoodVersion.MajorStr = First.first.str();
1094 if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1096 GoodVersion.MinorStr = Second.first.str();
1098 // First look for a number prefix and parse that if present. Otherwise just
1099 // stash the entire patch string in the suffix, and leave the number
1100 // unspecified. This covers versions strings such as:
1106 // And retains any patch number it finds.
1107 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1108 if (!PatchText.empty()) {
1109 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1110 // Try to parse the number and any suffix.
1111 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1112 GoodVersion.Patch < 0)
1114 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1121 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1122 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1124 StringRef RHSPatchSuffix) const {
1125 if (Major != RHSMajor)
1126 return Major < RHSMajor;
1127 if (Minor != RHSMinor)
1128 return Minor < RHSMinor;
1129 if (Patch != RHSPatch) {
1130 // Note that versions without a specified patch sort higher than those with
1137 // Otherwise just sort on the patch itself.
1138 return Patch < RHSPatch;
1140 if (PatchSuffix != RHSPatchSuffix) {
1141 // Sort empty suffixes higher.
1142 if (RHSPatchSuffix.empty())
1144 if (PatchSuffix.empty())
1147 // Provide a lexicographic sort to make this a total ordering.
1148 return PatchSuffix < RHSPatchSuffix;
1151 // The versions are equal.
1155 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1156 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1158 return A->getValue();
1159 return GCC_INSTALL_PREFIX;
1162 /// \brief Initialize a GCCInstallationDetector from the driver.
1164 /// This performs all of the autodetection and sets up the various paths.
1165 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1167 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1168 /// should instead pull the target out of the driver. This is currently
1169 /// necessary because the driver doesn't store the final version of the target
1171 void Generic_GCC::GCCInstallationDetector::init(
1172 const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
1173 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1174 ? TargetTriple.get64BitArchVariant()
1175 : TargetTriple.get32BitArchVariant();
1176 // The library directories which may contain GCC installations.
1177 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1178 // The compatible GCC triples for this particular architecture.
1179 SmallVector<StringRef, 16> CandidateTripleAliases;
1180 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1181 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1182 CandidateTripleAliases, CandidateBiarchLibDirs,
1183 CandidateBiarchTripleAliases);
1185 // Compute the set of prefixes for our search.
1186 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1187 D.PrefixDirs.end());
1189 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1190 if (GCCToolchainDir != "") {
1191 if (GCCToolchainDir.back() == '/')
1192 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1194 Prefixes.push_back(GCCToolchainDir);
1196 // If we have a SysRoot, try that first.
1197 if (!D.SysRoot.empty()) {
1198 Prefixes.push_back(D.SysRoot);
1199 Prefixes.push_back(D.SysRoot + "/usr");
1202 // Then look for gcc installed alongside clang.
1203 Prefixes.push_back(D.InstalledDir + "/..");
1205 // And finally in /usr.
1206 if (D.SysRoot.empty())
1207 Prefixes.push_back("/usr");
1210 // Loop over the various components which exist and select the best GCC
1211 // installation available. GCC installs are ranked by version number.
1212 Version = GCCVersion::Parse("0.0.0");
1213 for (const std::string &Prefix : Prefixes) {
1214 if (!llvm::sys::fs::exists(Prefix))
1216 for (const StringRef Suffix : CandidateLibDirs) {
1217 const std::string LibDir = Prefix + Suffix.str();
1218 if (!llvm::sys::fs::exists(LibDir))
1220 for (const StringRef Candidate : CandidateTripleAliases)
1221 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1223 for (const StringRef Suffix : CandidateBiarchLibDirs) {
1224 const std::string LibDir = Prefix + Suffix.str();
1225 if (!llvm::sys::fs::exists(LibDir))
1227 for (const StringRef Candidate : CandidateBiarchTripleAliases)
1228 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1229 /*NeedsBiarchSuffix=*/ true);
1234 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1235 for (const auto &InstallPath : CandidateGCCInstallPaths)
1236 OS << "Found candidate GCC installation: " << InstallPath << "\n";
1238 if (!GCCInstallPath.empty())
1239 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1241 for (const auto &Multilib : Multilibs)
1242 OS << "Candidate multilib: " << Multilib << "\n";
1244 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1245 OS << "Selected multilib: " << SelectedMultilib << "\n";
1248 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1249 if (BiarchSibling.hasValue()) {
1250 M = BiarchSibling.getValue();
1256 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1257 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1258 SmallVectorImpl<StringRef> &LibDirs,
1259 SmallVectorImpl<StringRef> &TripleAliases,
1260 SmallVectorImpl<StringRef> &BiarchLibDirs,
1261 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1262 // Declare a bunch of static data sets that we'll select between below. These
1263 // are specifically designed to always refer to string literals to avoid any
1264 // lifetime or initialization issues.
1265 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1266 static const char *const AArch64Triples[] = {
1267 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1268 "aarch64-redhat-linux"};
1269 static const char *const AArch64beLibDirs[] = {"/lib"};
1270 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1271 "aarch64_be-linux-gnu"};
1273 static const char *const ARMLibDirs[] = {"/lib"};
1274 static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1275 "arm-linux-androideabi"};
1276 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1277 "armv7hl-redhat-linux-gnueabi"};
1278 static const char *const ARMebLibDirs[] = {"/lib"};
1279 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1280 "armeb-linux-androideabi"};
1281 static const char *const ARMebHFTriples[] = {
1282 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1284 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1285 static const char *const X86_64Triples[] = {
1286 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1287 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1288 "x86_64-redhat-linux", "x86_64-suse-linux",
1289 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1290 "x86_64-slackware-linux", "x86_64-linux-android",
1291 "x86_64-unknown-linux"};
1292 static const char *const X32LibDirs[] = {"/libx32"};
1293 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1294 static const char *const X86Triples[] = {
1295 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1296 "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1297 "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1298 "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1301 static const char *const MIPSLibDirs[] = {"/lib"};
1302 static const char *const MIPSTriples[] = {
1303 "mips-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu"};
1304 static const char *const MIPSELLibDirs[] = {"/lib"};
1305 static const char *const MIPSELTriples[] = {
1306 "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
1308 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1309 static const char *const MIPS64Triples[] = {
1310 "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1311 "mips64-linux-gnuabi64"};
1312 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1313 static const char *const MIPS64ELTriples[] = {
1314 "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1315 "mips64el-linux-android", "mips64el-linux-gnuabi64"};
1317 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1318 static const char *const PPCTriples[] = {
1319 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1320 "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1321 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1322 static const char *const PPC64Triples[] = {
1323 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1324 "powerpc64-suse-linux", "ppc64-redhat-linux"};
1325 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1326 static const char *const PPC64LETriples[] = {
1327 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1328 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1330 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1331 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1332 "sparcv8-linux-gnu"};
1333 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1334 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1335 "sparcv9-linux-gnu"};
1337 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1338 static const char *const SystemZTriples[] = {
1339 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1340 "s390x-suse-linux", "s390x-redhat-linux"};
1345 switch (TargetTriple.getArch()) {
1346 case llvm::Triple::aarch64:
1347 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1348 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1349 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1350 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1352 case llvm::Triple::aarch64_be:
1353 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1354 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1355 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1356 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1358 case llvm::Triple::arm:
1359 case llvm::Triple::thumb:
1360 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1361 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1362 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1364 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1367 case llvm::Triple::armeb:
1368 case llvm::Triple::thumbeb:
1369 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1370 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1371 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1373 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1376 case llvm::Triple::x86_64:
1377 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1378 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1379 // x32 is always available when x86_64 is available, so adding it as
1380 // secondary arch with x86_64 triples
1381 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1382 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1383 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1385 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1386 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1389 case llvm::Triple::x86:
1390 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1391 TripleAliases.append(begin(X86Triples), end(X86Triples));
1392 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1393 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1395 case llvm::Triple::mips:
1396 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1397 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1398 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1399 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1401 case llvm::Triple::mipsel:
1402 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1403 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1404 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1405 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1406 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1408 case llvm::Triple::mips64:
1409 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1410 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1411 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1412 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1414 case llvm::Triple::mips64el:
1415 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1416 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1417 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1418 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1419 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1421 case llvm::Triple::ppc:
1422 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1423 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1424 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1425 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1427 case llvm::Triple::ppc64:
1428 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1429 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1430 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1431 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1433 case llvm::Triple::ppc64le:
1434 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1435 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1437 case llvm::Triple::sparc:
1438 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1439 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1440 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1441 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1443 case llvm::Triple::sparcv9:
1444 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1445 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1446 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1447 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1449 case llvm::Triple::systemz:
1450 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1451 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1455 // By default, just rely on the standard lib directories and the original
1460 // Always append the drivers target triple to the end, in case it doesn't
1461 // match any of our aliases.
1462 TripleAliases.push_back(TargetTriple.str());
1464 // Also include the multiarch variant if it's different.
1465 if (TargetTriple.str() != BiarchTriple.str())
1466 BiarchTripleAliases.push_back(BiarchTriple.str());
1470 // Filter to remove Multilibs that don't exist as a suffix to Path
1471 class FilterNonExistent {
1475 FilterNonExistent(StringRef Base) : Base(Base) {}
1476 bool operator()(const Multilib &M) {
1477 return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
1480 } // end anonymous namespace
1482 static void addMultilibFlag(bool Enabled, const char *const Flag,
1483 std::vector<std::string> &Flags) {
1485 Flags.push_back(std::string("+") + Flag);
1487 Flags.push_back(std::string("-") + Flag);
1490 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1491 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1492 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1495 static bool isMips32(llvm::Triple::ArchType Arch) {
1496 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1499 static bool isMips64(llvm::Triple::ArchType Arch) {
1500 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1503 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1504 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1507 static bool isMips16(const ArgList &Args) {
1508 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1509 return A && A->getOption().matches(options::OPT_mips16);
1512 static bool isMicroMips(const ArgList &Args) {
1513 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1514 return A && A->getOption().matches(options::OPT_mmicromips);
1517 struct DetectedMultilibs {
1518 /// The set of multilibs that the detected installation supports.
1519 MultilibSet Multilibs;
1521 /// The primary multilib appropriate for the given flags.
1522 Multilib SelectedMultilib;
1524 /// On Biarch systems, this corresponds to the default multilib when
1525 /// targeting the non-default multilib. Otherwise, it is empty.
1526 llvm::Optional<Multilib> BiarchSibling;
1529 static Multilib makeMultilib(StringRef commonSuffix) {
1530 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1533 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
1534 const ArgList &Args, DetectedMultilibs &Result) {
1535 // Some MIPS toolchains put libraries and object files compiled
1536 // using different options in to the sub-directoris which names
1537 // reflects the flags used for compilation. For example sysroot
1538 // directory might looks like the following examples:
1541 // /lib <= crt*.o files compiled with '-mips32'
1544 // /lib <= crt*.o files compiled with '-mips16'
1547 // /lib <= crt*.o files compiled with '-mips16 -EL'
1552 // /lib <= crt*.o files compiled with '-mips32r2'
1555 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1558 // /lib <= crt*.o files compiled with '-mips32'
1560 FilterNonExistent NonExistent(Path);
1562 // Check for FSF toolchain multilibs
1563 MultilibSet FSFMipsMultilibs;
1565 auto MArchMips32 = makeMultilib("/mips32")
1568 .flag("-mmicromips")
1569 .flag("+march=mips32");
1571 auto MArchMicroMips = makeMultilib("/micromips")
1574 .flag("+mmicromips");
1576 auto MArchMips64r2 = makeMultilib("/mips64r2")
1579 .flag("+march=mips64r2");
1581 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1584 auto MArchDefault = makeMultilib("")
1587 .flag("-mmicromips")
1588 .flag("+march=mips32r2");
1590 auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1592 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1595 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1597 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1599 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1601 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1603 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1607 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1611 .FilterOut("/mips64/mips16")
1612 .FilterOut("/mips64r2/mips16")
1613 .FilterOut("/micromips/mips16")
1615 .FilterOut("/micromips/64")
1616 .FilterOut("/mips32/64")
1618 .FilterOut("/mips16/64")
1619 .Either(BigEndian, LittleEndian)
1622 .FilterOut(".*sof/nan2008")
1623 .FilterOut(NonExistent)
1624 .setIncludeDirsCallback([](StringRef InstallDir,
1625 StringRef TripleStr, const Multilib &M) {
1626 std::vector<std::string> Dirs;
1627 Dirs.push_back((InstallDir + "/include").str());
1628 std::string SysRootInc =
1629 InstallDir.str() + "/../../../../sysroot";
1630 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1631 Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1633 Dirs.push_back(SysRootInc + "/usr/include");
1638 // Check for Code Sourcery toolchain multilibs
1639 MultilibSet CSMipsMultilibs;
1641 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1643 auto MArchMicroMips =
1644 makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1646 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1648 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1650 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1652 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1655 makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1657 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1659 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1661 // Note that this one's osSuffix is ""
1662 auto MAbi64 = makeMultilib("")
1664 .includeSuffix("/64")
1671 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1673 .Either(SoftFloat, Nan2008, DefaultFloat)
1674 .FilterOut("/micromips/nan2008")
1675 .FilterOut("/mips16/nan2008")
1676 .Either(BigEndian, LittleEndian)
1678 .FilterOut("/mips16.*/64")
1679 .FilterOut("/micromips.*/64")
1680 .FilterOut(NonExistent)
1681 .setIncludeDirsCallback([](StringRef InstallDir,
1682 StringRef TripleStr, const Multilib &M) {
1683 std::vector<std::string> Dirs;
1684 Dirs.push_back((InstallDir + "/include").str());
1685 std::string SysRootInc =
1686 InstallDir.str() + "/../../../../" + TripleStr.str();
1687 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1688 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1690 Dirs.push_back(SysRootInc + "/libc/usr/include");
1695 MultilibSet AndroidMipsMultilibs =
1697 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1698 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1699 .FilterOut(NonExistent);
1701 MultilibSet DebianMipsMultilibs;
1704 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1706 Multilib M64 = Multilib()
1708 .includeSuffix("/64")
1713 Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1715 DebianMipsMultilibs =
1716 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1719 MultilibSet ImgMultilibs;
1721 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1723 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1726 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1732 .Maybe(LittleEndian)
1733 .FilterOut(NonExistent)
1734 .setIncludeDirsCallback([](StringRef InstallDir,
1735 StringRef TripleStr, const Multilib &M) {
1736 std::vector<std::string> Dirs;
1737 Dirs.push_back((InstallDir + "/include").str());
1739 (InstallDir + "/../../../../sysroot/usr/include").str());
1746 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1748 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1750 Multilib::flags_list Flags;
1751 addMultilibFlag(isMips32(TargetArch), "m32", Flags);
1752 addMultilibFlag(isMips64(TargetArch), "m64", Flags);
1753 addMultilibFlag(isMips16(Args), "mips16", Flags);
1754 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1755 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1756 CPUName == "mips32r5",
1757 "march=mips32r2", Flags);
1758 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1759 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1760 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1761 CPUName == "mips64r5" || CPUName == "octeon",
1762 "march=mips64r2", Flags);
1763 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1764 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1765 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1767 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1768 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1769 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1770 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1771 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1772 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1774 if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
1775 // Select Android toolchain. It's the only choice in that case.
1776 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1777 Result.Multilibs = AndroidMipsMultilibs;
1783 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1784 TargetTriple.getOS() == llvm::Triple::Linux &&
1785 TargetTriple.getEnvironment() == llvm::Triple::GNU) {
1786 // Select mips-img-linux-gnu toolchain.
1787 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
1788 Result.Multilibs = ImgMultilibs;
1794 // Sort candidates. Toolchain that best meets the directories goes first.
1795 // Then select the first toolchains matches command line flags.
1796 MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
1799 std::begin(candidates), std::end(candidates),
1800 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
1801 for (const auto &candidate : candidates) {
1802 if (candidate->select(Flags, Result.SelectedMultilib)) {
1803 if (candidate == &DebianMipsMultilibs)
1804 Result.BiarchSibling = Multilib();
1805 Result.Multilibs = *candidate;
1811 // Fallback to the regular toolchain-tree structure.
1813 Result.Multilibs.push_back(Default);
1814 Result.Multilibs.FilterOut(NonExistent);
1816 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1817 Result.BiarchSibling = Multilib();
1825 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
1826 StringRef Path, const ArgList &Args,
1827 bool NeedsBiarchSuffix,
1828 DetectedMultilibs &Result) {
1830 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1831 // in what would normally be GCCInstallPath and put the 64-bit
1832 // libs in a subdirectory named 64. The simple logic we follow is that
1833 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1834 // we use that. If not, and if not a biarch triple alias, we look for
1835 // crtbegin.o without the subdirectory.
1838 Multilib Alt64 = Multilib()
1840 .includeSuffix("/64")
1844 Multilib Alt32 = Multilib()
1846 .includeSuffix("/32")
1850 Multilib Altx32 = Multilib()
1852 .includeSuffix("/x32")
1857 FilterNonExistent NonExistent(Path);
1859 // Determine default multilib from: 32, 64, x32
1860 // Also handle cases such as 64 on 32, 32 on 64, etc.
1861 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1862 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1863 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1865 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1867 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1870 if (TargetTriple.isArch32Bit())
1871 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1873 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1875 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1879 Default.flag("+m32").flag("-m64").flag("-mx32");
1880 else if (Want == WANT64)
1881 Default.flag("-m32").flag("+m64").flag("-mx32");
1882 else if (Want == WANTX32)
1883 Default.flag("-m32").flag("-m64").flag("+mx32");
1887 Result.Multilibs.push_back(Default);
1888 Result.Multilibs.push_back(Alt64);
1889 Result.Multilibs.push_back(Alt32);
1890 Result.Multilibs.push_back(Altx32);
1892 Result.Multilibs.FilterOut(NonExistent);
1894 Multilib::flags_list Flags;
1895 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1896 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1897 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1899 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1902 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1903 Result.SelectedMultilib == Altx32)
1904 Result.BiarchSibling = Default;
1909 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1910 const llvm::Triple &TargetTriple, const ArgList &Args,
1911 const std::string &LibDir, StringRef CandidateTriple,
1912 bool NeedsBiarchSuffix) {
1913 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1914 // There are various different suffixes involving the triple we
1915 // check for. We also record what is necessary to walk from each back
1916 // up to the lib directory.
1917 const std::string LibSuffixes[] = {
1918 "/gcc/" + CandidateTriple.str(),
1919 // Debian puts cross-compilers in gcc-cross
1920 "/gcc-cross/" + CandidateTriple.str(),
1921 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1923 // The Freescale PPC SDK has the gcc libraries in
1924 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1925 "/" + CandidateTriple.str(),
1927 // Ubuntu has a strange mis-matched pair of triples that this happens to
1929 // FIXME: It may be worthwhile to generalize this and look for a second
1931 "/i386-linux-gnu/gcc/" + CandidateTriple.str()};
1932 const std::string InstallSuffixes[] = {
1933 "/../../..", // gcc/
1934 "/../../..", // gcc-cross/
1935 "/../../../..", // <triple>/gcc/
1936 "/../..", // <triple>/
1937 "/../../../.." // i386-linux-gnu/gcc/<triple>/
1939 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1940 const unsigned NumLibSuffixes =
1941 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1942 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1943 StringRef LibSuffix = LibSuffixes[i];
1945 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1946 !EC && LI != LE; LI = LI.increment(EC)) {
1947 StringRef VersionText = llvm::sys::path::filename(LI->path());
1948 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1949 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1950 if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1951 continue; // Saw this path before; no need to look at it again.
1952 if (CandidateVersion.isOlderThan(4, 1, 1))
1954 if (CandidateVersion <= Version)
1957 DetectedMultilibs Detected;
1959 // Debian mips multilibs behave more like the rest of the biarch ones,
1960 // so handle them there
1961 if (isMipsArch(TargetArch)) {
1962 if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
1964 } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
1965 NeedsBiarchSuffix, Detected)) {
1969 Multilibs = Detected.Multilibs;
1970 SelectedMultilib = Detected.SelectedMultilib;
1971 BiarchSibling = Detected.BiarchSibling;
1972 Version = CandidateVersion;
1973 GCCTriple.setTriple(CandidateTriple);
1974 // FIXME: We hack together the directory name here instead of
1975 // using LI to ensure stable path separators across Windows and
1977 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1978 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1984 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
1985 const ArgList &Args)
1986 : ToolChain(D, Triple, Args), GCCInstallation() {
1987 getProgramPaths().push_back(getDriver().getInstalledDir());
1988 if (getDriver().getInstalledDir() != getDriver().Dir)
1989 getProgramPaths().push_back(getDriver().Dir);
1992 Generic_GCC::~Generic_GCC() {}
1994 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
1996 case Action::PreprocessJobClass:
1998 Preprocess.reset(new tools::gcc::Preprocessor(*this));
1999 return Preprocess.get();
2000 case Action::CompileJobClass:
2002 Compile.reset(new tools::gcc::Compiler(*this));
2003 return Compile.get();
2005 return ToolChain::getTool(AC);
2009 Tool *Generic_GCC::buildAssembler() const {
2010 return new tools::gnutools::Assembler(*this);
2013 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2015 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2016 // Print the information about how we detected the GCC installation.
2017 GCCInstallation.print(OS);
2020 bool Generic_GCC::IsUnwindTablesDefault() const {
2021 return getArch() == llvm::Triple::x86_64;
2024 bool Generic_GCC::isPICDefault() const {
2025 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2028 bool Generic_GCC::isPIEDefault() const { return false; }
2030 bool Generic_GCC::isPICDefaultForced() const {
2031 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2034 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2035 switch (getTriple().getArch()) {
2036 case llvm::Triple::x86:
2037 case llvm::Triple::x86_64:
2038 case llvm::Triple::aarch64:
2039 case llvm::Triple::aarch64_be:
2040 case llvm::Triple::arm:
2041 case llvm::Triple::armeb:
2042 case llvm::Triple::bpfel:
2043 case llvm::Triple::bpfeb:
2044 case llvm::Triple::thumb:
2045 case llvm::Triple::thumbeb:
2046 case llvm::Triple::ppc:
2047 case llvm::Triple::ppc64:
2048 case llvm::Triple::ppc64le:
2049 case llvm::Triple::sparc:
2050 case llvm::Triple::sparcel:
2051 case llvm::Triple::sparcv9:
2052 case llvm::Triple::systemz:
2059 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2060 ArgStringList &CC1Args) const {
2061 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2062 bool UseInitArrayDefault =
2063 getTriple().getArch() == llvm::Triple::aarch64 ||
2064 getTriple().getArch() == llvm::Triple::aarch64_be ||
2065 (getTriple().getOS() == llvm::Triple::Linux &&
2066 (!V.isOlderThan(4, 7, 0) ||
2067 getTriple().getEnvironment() == llvm::Triple::Android)) ||
2068 getTriple().getOS() == llvm::Triple::NaCl;
2070 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2071 options::OPT_fno_use_init_array, UseInitArrayDefault))
2072 CC1Args.push_back("-fuse-init-array");
2075 /// Hexagon Toolchain
2077 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
2078 const ArgList &Args) {
2080 // Locate the rest of the toolchain ...
2081 std::string GccToolchain = getGCCToolchainDir(Args);
2083 if (!GccToolchain.empty())
2084 return GccToolchain;
2086 std::string InstallRelDir = InstalledDir + "/../../gnu";
2087 if (llvm::sys::fs::exists(InstallRelDir))
2088 return InstallRelDir;
2090 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
2091 if (llvm::sys::fs::exists(PrefixRelDir))
2092 return PrefixRelDir;
2094 return InstallRelDir;
2097 const char *Hexagon_TC::GetSmallDataThreshold(const ArgList &Args) {
2100 A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
2101 options::OPT_msmall_data_threshold_EQ);
2103 return A->getValue();
2105 A = Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2113 bool Hexagon_TC::UsesG0(const char *smallDataThreshold) {
2114 return smallDataThreshold && smallDataThreshold[0] == '0';
2117 static void GetHexagonLibraryPaths(const ArgList &Args, const std::string &Ver,
2118 const std::string &MarchString,
2119 const std::string &InstalledDir,
2120 ToolChain::path_list *LibPaths) {
2121 bool buildingLib = Args.hasArg(options::OPT_shared);
2123 //----------------------------------------------------------------------------
2125 //----------------------------------------------------------------------------
2126 for (Arg *A : Args.filtered(options::OPT_L))
2127 for (const char *Value : A->getValues())
2128 LibPaths->push_back(Value);
2130 //----------------------------------------------------------------------------
2131 // Other standard paths
2132 //----------------------------------------------------------------------------
2133 const std::string MarchSuffix = "/" + MarchString;
2134 const std::string G0Suffix = "/G0";
2135 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
2136 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
2138 // lib/gcc/hexagon/...
2139 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
2141 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
2142 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
2144 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
2145 LibPaths->push_back(LibGCCHexagonDir + Ver);
2148 LibPaths->push_back(RootDir + "lib/gcc");
2151 std::string HexagonLibDir = RootDir + "hexagon/lib";
2153 LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
2154 LibPaths->push_back(HexagonLibDir + G0Suffix);
2156 LibPaths->push_back(HexagonLibDir + MarchSuffix);
2157 LibPaths->push_back(HexagonLibDir);
2160 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
2161 const ArgList &Args)
2162 : Linux(D, Triple, Args) {
2163 const std::string InstalledDir(getDriver().getInstalledDir());
2164 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
2166 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2168 const std::string BinDir(GnuDir + "/bin");
2169 if (llvm::sys::fs::exists(BinDir))
2170 getProgramPaths().push_back(BinDir);
2172 // Determine version of GCC libraries and headers to use.
2173 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
2175 GCCVersion MaxVersion = GCCVersion::Parse("0.0.0");
2176 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
2177 !ec && di != de; di = di.increment(ec)) {
2178 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
2179 if (MaxVersion < cv)
2182 GCCLibAndIncVersion = MaxVersion;
2184 ToolChain::path_list *LibPaths = &getFilePaths();
2186 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2187 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2188 // support 'linux' we'll need to fix this up
2191 GetHexagonLibraryPaths(Args, GetGCCLibAndIncVersion(), GetTargetCPU(Args),
2192 InstalledDir, LibPaths);
2195 Hexagon_TC::~Hexagon_TC() {}
2197 Tool *Hexagon_TC::buildAssembler() const {
2198 return new tools::hexagon::Assembler(*this);
2201 Tool *Hexagon_TC::buildLinker() const {
2202 return new tools::hexagon::Linker(*this);
2205 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2206 ArgStringList &CC1Args) const {
2207 const Driver &D = getDriver();
2209 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2210 DriverArgs.hasArg(options::OPT_nostdlibinc))
2213 std::string Ver(GetGCCLibAndIncVersion());
2214 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
2215 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
2216 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
2217 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
2218 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
2221 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2222 ArgStringList &CC1Args) const {
2224 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2225 DriverArgs.hasArg(options::OPT_nostdincxx))
2228 const Driver &D = getDriver();
2229 std::string Ver(GetGCCLibAndIncVersion());
2230 SmallString<128> IncludeDir(
2231 Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
2233 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
2234 llvm::sys::path::append(IncludeDir, Ver);
2235 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
2238 ToolChain::CXXStdlibType
2239 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
2240 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2242 return ToolChain::CST_Libstdcxx;
2244 StringRef Value = A->getValue();
2245 if (Value != "libstdc++") {
2246 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2249 return ToolChain::CST_Libstdcxx;
2252 static int getHexagonVersion(const ArgList &Args) {
2253 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
2254 // Select the default CPU (v4) if none was given.
2258 // FIXME: produce errors if we cannot parse the version.
2259 StringRef WhichHexagon = A->getValue();
2260 if (WhichHexagon.startswith("hexagonv")) {
2262 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
2265 if (WhichHexagon.startswith("v")) {
2267 if (!WhichHexagon.substr(1).getAsInteger(10, Val))
2271 // FIXME: should probably be an error.
2275 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args) {
2276 int V = getHexagonVersion(Args);
2277 // FIXME: We don't support versions < 4. We should error on them.
2280 llvm_unreachable("Unexpected version");
2296 NaCl_TC::NaCl_TC(const Driver &D, const llvm::Triple &Triple,
2297 const ArgList &Args)
2298 : Generic_ELF(D, Triple, Args) {
2300 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
2301 // default paths, and must instead only use the paths provided
2302 // with this toolchain based on architecture.
2303 path_list &file_paths = getFilePaths();
2304 path_list &prog_paths = getProgramPaths();
2309 // Path for library files (libc.a, ...)
2310 std::string FilePath(getDriver().Dir + "/../");
2312 // Path for tools (clang, ld, etc..)
2313 std::string ProgPath(getDriver().Dir + "/../");
2315 // Path for toolchain libraries (libgcc.a, ...)
2316 std::string ToolPath(getDriver().ResourceDir + "/lib/");
2318 switch (Triple.getArch()) {
2319 case llvm::Triple::x86: {
2320 file_paths.push_back(FilePath + "x86_64-nacl/lib32");
2321 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib32");
2322 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2323 file_paths.push_back(ToolPath + "i686-nacl");
2326 case llvm::Triple::x86_64: {
2327 file_paths.push_back(FilePath + "x86_64-nacl/lib");
2328 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
2329 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2330 file_paths.push_back(ToolPath + "x86_64-nacl");
2333 case llvm::Triple::arm: {
2334 file_paths.push_back(FilePath + "arm-nacl/lib");
2335 file_paths.push_back(FilePath + "arm-nacl/usr/lib");
2336 prog_paths.push_back(ProgPath + "arm-nacl/bin");
2337 file_paths.push_back(ToolPath + "arm-nacl");
2344 // Use provided linker, not system linker
2345 Linker = GetProgramPath("ld");
2346 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
2349 void NaCl_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2350 ArgStringList &CC1Args) const {
2351 const Driver &D = getDriver();
2352 if (DriverArgs.hasArg(options::OPT_nostdinc))
2355 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2356 SmallString<128> P(D.ResourceDir);
2357 llvm::sys::path::append(P, "include");
2358 addSystemInclude(DriverArgs, CC1Args, P.str());
2361 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2364 SmallString<128> P(D.Dir + "/../");
2365 switch (getTriple().getArch()) {
2366 case llvm::Triple::arm:
2367 llvm::sys::path::append(P, "arm-nacl/usr/include");
2369 case llvm::Triple::x86:
2370 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2372 case llvm::Triple::x86_64:
2373 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2379 addSystemInclude(DriverArgs, CC1Args, P.str());
2380 llvm::sys::path::remove_filename(P);
2381 llvm::sys::path::remove_filename(P);
2382 llvm::sys::path::append(P, "include");
2383 addSystemInclude(DriverArgs, CC1Args, P.str());
2386 void NaCl_TC::AddCXXStdlibLibArgs(const ArgList &Args,
2387 ArgStringList &CmdArgs) const {
2388 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2389 // if the value is libc++, and emits an error for other values.
2390 GetCXXStdlibType(Args);
2391 CmdArgs.push_back("-lc++");
2394 void NaCl_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2395 ArgStringList &CC1Args) const {
2396 const Driver &D = getDriver();
2397 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2398 DriverArgs.hasArg(options::OPT_nostdincxx))
2401 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2402 // if the value is libc++, and emits an error for other values.
2403 GetCXXStdlibType(DriverArgs);
2405 SmallString<128> P(D.Dir + "/../");
2406 switch (getTriple().getArch()) {
2407 case llvm::Triple::arm:
2408 llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
2409 addSystemInclude(DriverArgs, CC1Args, P.str());
2411 case llvm::Triple::x86:
2412 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2413 addSystemInclude(DriverArgs, CC1Args, P.str());
2415 case llvm::Triple::x86_64:
2416 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2417 addSystemInclude(DriverArgs, CC1Args, P.str());
2424 ToolChain::CXXStdlibType NaCl_TC::GetCXXStdlibType(const ArgList &Args) const {
2425 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2426 StringRef Value = A->getValue();
2427 if (Value == "libc++")
2428 return ToolChain::CST_Libcxx;
2429 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2432 return ToolChain::CST_Libcxx;
2435 std::string NaCl_TC::ComputeEffectiveClangTriple(const ArgList &Args,
2436 types::ID InputType) const {
2437 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
2438 if (TheTriple.getArch() == llvm::Triple::arm &&
2439 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2440 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
2441 return TheTriple.getTriple();
2444 Tool *NaCl_TC::buildLinker() const {
2445 return new tools::nacltools::Linker(*this);
2448 Tool *NaCl_TC::buildAssembler() const {
2449 if (getTriple().getArch() == llvm::Triple::arm)
2450 return new tools::nacltools::AssemblerARM(*this);
2451 return new tools::gnutools::Assembler(*this);
2455 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2456 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2457 /// Currently does not support anything else but compilation.
2459 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
2460 const ArgList &Args)
2461 : ToolChain(D, Triple, Args) {
2462 // Path mangling to find libexec
2463 std::string Path(getDriver().Dir);
2465 Path += "/../libexec";
2466 getProgramPaths().push_back(Path);
2469 TCEToolChain::~TCEToolChain() {}
2471 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
2473 bool TCEToolChain::isPICDefault() const { return false; }
2475 bool TCEToolChain::isPIEDefault() const { return false; }
2477 bool TCEToolChain::isPICDefaultForced() const { return false; }
2479 // CloudABI - CloudABI tool chain which can call ld(1) directly.
2481 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
2482 const ArgList &Args)
2483 : Generic_ELF(D, Triple, Args) {
2484 SmallString<128> P(getDriver().Dir);
2485 llvm::sys::path::append(P, "..", getTriple().str(), "lib");
2486 getFilePaths().push_back(P.str());
2489 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2490 ArgStringList &CC1Args) const {
2491 if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
2492 DriverArgs.hasArg(options::OPT_nostdincxx))
2495 SmallString<128> P(getDriver().Dir);
2496 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
2497 addSystemInclude(DriverArgs, CC1Args, P.str());
2500 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
2501 ArgStringList &CmdArgs) const {
2502 CmdArgs.push_back("-lc++");
2503 CmdArgs.push_back("-lc++abi");
2504 CmdArgs.push_back("-lunwind");
2507 Tool *CloudABI::buildLinker() const {
2508 return new tools::cloudabi::Linker(*this);
2511 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2513 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
2514 const ArgList &Args)
2515 : Generic_ELF(D, Triple, Args) {
2516 getFilePaths().push_back(getDriver().Dir + "/../lib");
2517 getFilePaths().push_back("/usr/lib");
2520 Tool *OpenBSD::buildAssembler() const {
2521 return new tools::openbsd::Assembler(*this);
2524 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
2526 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2528 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2529 : Generic_ELF(D, Triple, Args) {
2530 getFilePaths().push_back(getDriver().Dir + "/../lib");
2531 getFilePaths().push_back("/usr/lib");
2534 Tool *Bitrig::buildAssembler() const {
2535 return new tools::bitrig::Assembler(*this);
2538 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
2540 ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const {
2541 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2542 StringRef Value = A->getValue();
2543 if (Value == "libstdc++")
2544 return ToolChain::CST_Libstdcxx;
2545 if (Value == "libc++")
2546 return ToolChain::CST_Libcxx;
2548 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2550 return ToolChain::CST_Libcxx;
2553 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2554 ArgStringList &CC1Args) const {
2555 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2556 DriverArgs.hasArg(options::OPT_nostdincxx))
2559 switch (GetCXXStdlibType(DriverArgs)) {
2560 case ToolChain::CST_Libcxx:
2561 addSystemInclude(DriverArgs, CC1Args,
2562 getDriver().SysRoot + "/usr/include/c++/v1");
2564 case ToolChain::CST_Libstdcxx:
2565 addSystemInclude(DriverArgs, CC1Args,
2566 getDriver().SysRoot + "/usr/include/c++/stdc++");
2567 addSystemInclude(DriverArgs, CC1Args,
2568 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
2570 StringRef Triple = getTriple().str();
2571 if (Triple.startswith("amd64"))
2572 addSystemInclude(DriverArgs, CC1Args,
2573 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
2576 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
2577 "/usr/include/c++/stdc++/" +
2583 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
2584 ArgStringList &CmdArgs) const {
2585 switch (GetCXXStdlibType(Args)) {
2586 case ToolChain::CST_Libcxx:
2587 CmdArgs.push_back("-lc++");
2588 CmdArgs.push_back("-lc++abi");
2589 CmdArgs.push_back("-lpthread");
2591 case ToolChain::CST_Libstdcxx:
2592 CmdArgs.push_back("-lstdc++");
2597 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
2599 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
2600 const ArgList &Args)
2601 : Generic_ELF(D, Triple, Args) {
2603 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
2604 // back to '/usr/lib' if it doesn't exist.
2605 if ((Triple.getArch() == llvm::Triple::x86 ||
2606 Triple.getArch() == llvm::Triple::ppc) &&
2607 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
2608 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2610 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2613 ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2614 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2615 StringRef Value = A->getValue();
2616 if (Value == "libstdc++")
2617 return ToolChain::CST_Libstdcxx;
2618 if (Value == "libc++")
2619 return ToolChain::CST_Libcxx;
2621 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2623 if (getTriple().getOSMajorVersion() >= 10)
2624 return ToolChain::CST_Libcxx;
2625 return ToolChain::CST_Libstdcxx;
2628 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2629 ArgStringList &CC1Args) const {
2630 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2631 DriverArgs.hasArg(options::OPT_nostdincxx))
2634 switch (GetCXXStdlibType(DriverArgs)) {
2635 case ToolChain::CST_Libcxx:
2636 addSystemInclude(DriverArgs, CC1Args,
2637 getDriver().SysRoot + "/usr/include/c++/v1");
2639 case ToolChain::CST_Libstdcxx:
2640 addSystemInclude(DriverArgs, CC1Args,
2641 getDriver().SysRoot + "/usr/include/c++/4.2");
2642 addSystemInclude(DriverArgs, CC1Args,
2643 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2648 Tool *FreeBSD::buildAssembler() const {
2649 return new tools::freebsd::Assembler(*this);
2652 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
2654 bool FreeBSD::UseSjLjExceptions() const {
2655 // FreeBSD uses SjLj exceptions on ARM oabi.
2656 switch (getTriple().getEnvironment()) {
2657 case llvm::Triple::GNUEABIHF:
2658 case llvm::Triple::GNUEABI:
2659 case llvm::Triple::EABI:
2663 return (getTriple().getArch() == llvm::Triple::arm ||
2664 getTriple().getArch() == llvm::Triple::thumb);
2668 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
2670 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
2672 SanitizerMask FreeBSD::getSupportedSanitizers() const {
2673 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
2674 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2675 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
2676 getTriple().getArch() == llvm::Triple::mips64el;
2677 SanitizerMask Res = ToolChain::getSupportedSanitizers();
2678 Res |= SanitizerKind::Address;
2679 Res |= SanitizerKind::Vptr;
2680 if (IsX86_64 || IsMIPS64) {
2681 Res |= SanitizerKind::Leak;
2682 Res |= SanitizerKind::Thread;
2684 if (IsX86 || IsX86_64) {
2685 Res |= SanitizerKind::SafeStack;
2690 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2692 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2693 : Generic_ELF(D, Triple, Args) {
2695 if (getDriver().UseStdLib) {
2696 // When targeting a 32-bit platform, try the special directory used on
2697 // 64-bit hosts, and only fall back to the main library directory if that
2699 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2700 // what all logic is needed to emulate the '=' prefix here.
2701 switch (Triple.getArch()) {
2702 case llvm::Triple::x86:
2703 getFilePaths().push_back("=/usr/lib/i386");
2705 case llvm::Triple::arm:
2706 case llvm::Triple::armeb:
2707 case llvm::Triple::thumb:
2708 case llvm::Triple::thumbeb:
2709 switch (Triple.getEnvironment()) {
2710 case llvm::Triple::EABI:
2711 case llvm::Triple::GNUEABI:
2712 getFilePaths().push_back("=/usr/lib/eabi");
2714 case llvm::Triple::EABIHF:
2715 case llvm::Triple::GNUEABIHF:
2716 getFilePaths().push_back("=/usr/lib/eabihf");
2719 getFilePaths().push_back("=/usr/lib/oabi");
2723 case llvm::Triple::mips64:
2724 case llvm::Triple::mips64el:
2725 if (tools::mips::hasMipsAbiArg(Args, "o32"))
2726 getFilePaths().push_back("=/usr/lib/o32");
2727 else if (tools::mips::hasMipsAbiArg(Args, "64"))
2728 getFilePaths().push_back("=/usr/lib/64");
2730 case llvm::Triple::ppc:
2731 getFilePaths().push_back("=/usr/lib/powerpc");
2733 case llvm::Triple::sparc:
2734 getFilePaths().push_back("=/usr/lib/sparc");
2740 getFilePaths().push_back("=/usr/lib");
2744 Tool *NetBSD::buildAssembler() const {
2745 return new tools::netbsd::Assembler(*this);
2748 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
2750 ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2751 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2752 StringRef Value = A->getValue();
2753 if (Value == "libstdc++")
2754 return ToolChain::CST_Libstdcxx;
2755 if (Value == "libc++")
2756 return ToolChain::CST_Libcxx;
2758 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2761 unsigned Major, Minor, Micro;
2762 getTriple().getOSVersion(Major, Minor, Micro);
2763 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
2764 switch (getArch()) {
2765 case llvm::Triple::aarch64:
2766 case llvm::Triple::arm:
2767 case llvm::Triple::armeb:
2768 case llvm::Triple::thumb:
2769 case llvm::Triple::thumbeb:
2770 case llvm::Triple::ppc:
2771 case llvm::Triple::ppc64:
2772 case llvm::Triple::ppc64le:
2773 case llvm::Triple::x86:
2774 case llvm::Triple::x86_64:
2775 return ToolChain::CST_Libcxx;
2780 return ToolChain::CST_Libstdcxx;
2783 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2784 ArgStringList &CC1Args) const {
2785 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2786 DriverArgs.hasArg(options::OPT_nostdincxx))
2789 switch (GetCXXStdlibType(DriverArgs)) {
2790 case ToolChain::CST_Libcxx:
2791 addSystemInclude(DriverArgs, CC1Args,
2792 getDriver().SysRoot + "/usr/include/c++/");
2794 case ToolChain::CST_Libstdcxx:
2795 addSystemInclude(DriverArgs, CC1Args,
2796 getDriver().SysRoot + "/usr/include/g++");
2797 addSystemInclude(DriverArgs, CC1Args,
2798 getDriver().SysRoot + "/usr/include/g++/backward");
2803 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2805 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2806 : Generic_ELF(D, Triple, Args) {
2807 getFilePaths().push_back(getDriver().Dir + "/../lib");
2808 getFilePaths().push_back("/usr/lib");
2811 Tool *Minix::buildAssembler() const {
2812 return new tools::minix::Assembler(*this);
2815 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
2817 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2819 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
2820 const ArgList &Args)
2821 : Generic_GCC(D, Triple, Args) {
2823 getProgramPaths().push_back(getDriver().getInstalledDir());
2824 if (getDriver().getInstalledDir() != getDriver().Dir)
2825 getProgramPaths().push_back(getDriver().Dir);
2827 getFilePaths().push_back(getDriver().Dir + "/../lib");
2828 getFilePaths().push_back("/usr/lib");
2831 Tool *Solaris::buildAssembler() const {
2832 return new tools::solaris::Assembler(*this);
2835 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
2837 /// Distribution (very bare-bones at the moment).
2840 // NB: Releases of a particular Linux distro should be kept together
2841 // in this enum, because some tests are done by integer comparison against
2842 // the first and last known member in the family, e.g. IsRedHat().
2874 static bool IsRedhat(enum Distro Distro) {
2875 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
2878 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
2880 static bool IsDebian(enum Distro Distro) {
2881 return Distro >= DebianLenny && Distro <= DebianStretch;
2884 static bool IsUbuntu(enum Distro Distro) {
2885 return Distro >= UbuntuHardy && Distro <= UbuntuVivid;
2888 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2889 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2890 llvm::MemoryBuffer::getFile("/etc/lsb-release");
2892 StringRef Data = File.get()->getBuffer();
2893 SmallVector<StringRef, 16> Lines;
2894 Data.split(Lines, "\n");
2895 Distro Version = UnknownDistro;
2896 for (const StringRef Line : Lines)
2897 if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
2898 Version = llvm::StringSwitch<Distro>(Line.substr(17))
2899 .Case("hardy", UbuntuHardy)
2900 .Case("intrepid", UbuntuIntrepid)
2901 .Case("jaunty", UbuntuJaunty)
2902 .Case("karmic", UbuntuKarmic)
2903 .Case("lucid", UbuntuLucid)
2904 .Case("maverick", UbuntuMaverick)
2905 .Case("natty", UbuntuNatty)
2906 .Case("oneiric", UbuntuOneiric)
2907 .Case("precise", UbuntuPrecise)
2908 .Case("quantal", UbuntuQuantal)
2909 .Case("raring", UbuntuRaring)
2910 .Case("saucy", UbuntuSaucy)
2911 .Case("trusty", UbuntuTrusty)
2912 .Case("utopic", UbuntuUtopic)
2913 .Case("vivid", UbuntuVivid)
2914 .Default(UnknownDistro);
2918 File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
2920 StringRef Data = File.get()->getBuffer();
2921 if (Data.startswith("Fedora release"))
2923 if (Data.startswith("Red Hat Enterprise Linux") ||
2924 Data.startswith("CentOS")) {
2925 if (Data.find("release 7") != StringRef::npos)
2927 else if (Data.find("release 6") != StringRef::npos)
2929 else if (Data.find("release 5") != StringRef::npos)
2931 else if (Data.find("release 4") != StringRef::npos)
2934 return UnknownDistro;
2937 File = llvm::MemoryBuffer::getFile("/etc/debian_version");
2939 StringRef Data = File.get()->getBuffer();
2942 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2943 return DebianSqueeze;
2944 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
2945 return DebianWheezy;
2946 else if (Data.startswith("jessie/sid") || Data[0] == '8')
2947 return DebianJessie;
2948 else if (Data.startswith("stretch/sid") || Data[0] == '9')
2949 return DebianStretch;
2950 return UnknownDistro;
2953 if (llvm::sys::fs::exists("/etc/SuSE-release"))
2956 if (llvm::sys::fs::exists("/etc/exherbo-release"))
2959 if (llvm::sys::fs::exists("/etc/arch-release"))
2962 return UnknownDistro;
2965 /// \brief Get our best guess at the multiarch triple for a target.
2967 /// Debian-based systems are starting to use a multiarch setup where they use
2968 /// a target-triple directory in the library and header search paths.
2969 /// Unfortunately, this triple does not align with the vanilla target triple,
2970 /// so we provide a rough mapping here.
2971 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
2972 StringRef SysRoot) {
2973 llvm::Triple::EnvironmentType TargetEnvironment = TargetTriple.getEnvironment();
2975 // For most architectures, just use whatever we have rather than trying to be
2977 switch (TargetTriple.getArch()) {
2981 // We use the existence of '/lib/<triple>' as a directory to detect some
2982 // common linux triples that don't quite match the Clang triple for both
2983 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2984 // regardless of what the actual target triple is.
2985 case llvm::Triple::arm:
2986 case llvm::Triple::thumb:
2987 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
2988 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2989 return "arm-linux-gnueabihf";
2991 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2992 return "arm-linux-gnueabi";
2995 case llvm::Triple::armeb:
2996 case llvm::Triple::thumbeb:
2997 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
2998 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
2999 return "armeb-linux-gnueabihf";
3001 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3002 return "armeb-linux-gnueabi";
3005 case llvm::Triple::x86:
3006 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
3007 return "i386-linux-gnu";
3009 case llvm::Triple::x86_64:
3010 // We don't want this for x32, otherwise it will match x86_64 libs
3011 if (TargetEnvironment != llvm::Triple::GNUX32 &&
3012 llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
3013 return "x86_64-linux-gnu";
3015 case llvm::Triple::aarch64:
3016 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
3017 return "aarch64-linux-gnu";
3019 case llvm::Triple::aarch64_be:
3020 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3021 return "aarch64_be-linux-gnu";
3023 case llvm::Triple::mips:
3024 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
3025 return "mips-linux-gnu";
3027 case llvm::Triple::mipsel:
3028 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
3029 return "mipsel-linux-gnu";
3031 case llvm::Triple::mips64:
3032 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
3033 return "mips64-linux-gnu";
3034 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3035 return "mips64-linux-gnuabi64";
3037 case llvm::Triple::mips64el:
3038 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
3039 return "mips64el-linux-gnu";
3040 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
3041 return "mips64el-linux-gnuabi64";
3043 case llvm::Triple::ppc:
3044 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
3045 return "powerpc-linux-gnuspe";
3046 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
3047 return "powerpc-linux-gnu";
3049 case llvm::Triple::ppc64:
3050 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
3051 return "powerpc64-linux-gnu";
3053 case llvm::Triple::ppc64le:
3054 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
3055 return "powerpc64le-linux-gnu";
3057 case llvm::Triple::sparc:
3058 if (llvm::sys::fs::exists(SysRoot + "/lib/sparc-linux-gnu"))
3059 return "sparc-linux-gnu";
3061 case llvm::Triple::sparcv9:
3062 if (llvm::sys::fs::exists(SysRoot + "/lib/sparc64-linux-gnu"))
3063 return "sparc64-linux-gnu";
3066 return TargetTriple.str();
3069 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
3070 if (llvm::sys::fs::exists(Path))
3071 Paths.push_back(Path.str());
3074 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
3075 if (isMipsArch(Triple.getArch())) {
3076 // lib32 directory has a special meaning on MIPS targets.
3077 // It contains N32 ABI binaries. Use this folder if produce
3078 // code for N32 ABI only.
3079 if (tools::mips::hasMipsAbiArg(Args, "n32"))
3081 return Triple.isArch32Bit() ? "lib" : "lib64";
3084 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
3085 // using that variant while targeting other architectures causes problems
3086 // because the libraries are laid out in shared system roots that can't cope
3087 // with a 'lib32' library search path being considered. So we only enable
3088 // them when we know we may need it.
3090 // FIXME: This is a bit of a hack. We should really unify this code for
3091 // reasoning about oslibdir spellings with the lib dir spellings in the
3092 // GCCInstallationDetector, but that is a more significant refactoring.
3093 if (Triple.getArch() == llvm::Triple::x86 ||
3094 Triple.getArch() == llvm::Triple::ppc)
3097 if (Triple.getArch() == llvm::Triple::x86_64 &&
3098 Triple.getEnvironment() == llvm::Triple::GNUX32)
3101 return Triple.isArch32Bit() ? "lib" : "lib64";
3104 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3105 : Generic_ELF(D, Triple, Args) {
3106 GCCInstallation.init(D, Triple, Args);
3107 Multilibs = GCCInstallation.getMultilibs();
3108 llvm::Triple::ArchType Arch = Triple.getArch();
3109 std::string SysRoot = computeSysRoot();
3111 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3112 // least) put various tools in a triple-prefixed directory off of the parent
3113 // of the GCC installation. We use the GCC triple here to ensure that we end
3114 // up with tools that support the same amount of cross compiling as the
3115 // detected GCC installation. For example, if we find a GCC installation
3116 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3117 // used to target i386.
3118 // FIXME: This seems unlikely to be Linux-specific.
3119 ToolChain::path_list &PPaths = getProgramPaths();
3120 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3121 GCCInstallation.getTriple().str() + "/bin")
3124 Linker = GetLinkerPath();
3126 Distro Distro = DetectDistro(Arch);
3128 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
3129 ExtraOpts.push_back("-z");
3130 ExtraOpts.push_back("relro");
3133 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
3134 ExtraOpts.push_back("-X");
3136 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
3137 const bool IsMips = isMipsArch(Arch);
3139 if (IsMips && !SysRoot.empty())
3140 ExtraOpts.push_back("--sysroot=" + SysRoot);
3142 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
3143 // and the MIPS ABI require .dynsym to be sorted in different ways.
3144 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
3145 // ABI requires a mapping between the GOT and the symbol table.
3146 // Android loader does not support .gnu.hash.
3147 if (!IsMips && !IsAndroid) {
3148 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
3149 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
3150 ExtraOpts.push_back("--hash-style=gnu");
3152 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
3153 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
3154 ExtraOpts.push_back("--hash-style=both");
3157 if (IsRedhat(Distro))
3158 ExtraOpts.push_back("--no-add-needed");
3160 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
3161 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
3162 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
3163 ExtraOpts.push_back("--build-id");
3165 if (IsOpenSUSE(Distro))
3166 ExtraOpts.push_back("--enable-new-dtags");
3168 // The selection of paths to try here is designed to match the patterns which
3169 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
3170 // This was determined by running GCC in a fake filesystem, creating all
3171 // possible permutations of these directories, and seeing which ones it added
3172 // to the link paths.
3173 path_list &Paths = getFilePaths();
3175 const std::string OSLibDir = getOSLibDir(Triple, Args);
3176 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
3178 // Add the multilib suffixed paths where they are available.
3179 if (GCCInstallation.isValid()) {
3180 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3181 const std::string &LibPath = GCCInstallation.getParentLibPath();
3182 const Multilib &Multilib = GCCInstallation.getMultilib();
3184 // Sourcery CodeBench MIPS toolchain holds some libraries under
3185 // a biarch-like suffix of the GCC installation.
3186 addPathIfExists((GCCInstallation.getInstallPath() + Multilib.gccSuffix()),
3189 // GCC cross compiling toolchains will install target libraries which ship
3190 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3191 // any part of the GCC installation in
3192 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3193 // debatable, but is the reality today. We need to search this tree even
3194 // when we have a sysroot somewhere else. It is the responsibility of
3195 // whomever is doing the cross build targeting a sysroot using a GCC
3196 // installation that is *not* within the system root to ensure two things:
3198 // 1) Any DSOs that are linked in from this tree or from the install path
3199 // above must be present on the system root and found via an
3200 // appropriate rpath.
3201 // 2) There must not be libraries installed into
3202 // <prefix>/<triple>/<libdir> unless they should be preferred over
3203 // those within the system root.
3205 // Note that this matches the GCC behavior. See the below comment for where
3206 // Clang diverges from GCC's behavior.
3207 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3208 Multilib.osSuffix(),
3211 // If the GCC installation we found is inside of the sysroot, we want to
3212 // prefer libraries installed in the parent prefix of the GCC installation.
3213 // It is important to *not* use these paths when the GCC installation is
3214 // outside of the system root as that can pick up unintended libraries.
3215 // This usually happens when there is an external cross compiler on the
3216 // host system, and a more minimal sysroot available that is the target of
3217 // the cross. Note that GCC does include some of these directories in some
3218 // configurations but this seems somewhere between questionable and simply
3220 if (StringRef(LibPath).startswith(SysRoot)) {
3221 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
3222 addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
3226 // Similar to the logic for GCC above, if we currently running Clang inside
3227 // of the requested system root, add its parent library paths to
3229 // FIXME: It's not clear whether we should use the driver's installed
3230 // directory ('Dir' below) or the ResourceDir.
3231 if (StringRef(D.Dir).startswith(SysRoot)) {
3232 addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
3233 addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
3236 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
3237 addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
3238 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3239 addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3241 // Try walking via the GCC triple path in case of biarch or multiarch GCC
3242 // installations with strange symlinks.
3243 if (GCCInstallation.isValid()) {
3244 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3245 "/../../" + OSLibDir,
3248 // Add the 'other' biarch variant path
3249 Multilib BiarchSibling;
3250 if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3252 GCCInstallation.getInstallPath() + BiarchSibling.gccSuffix(), Paths);
3255 // See comments above on the multilib variant for details of why this is
3256 // included even from outside the sysroot.
3257 const std::string &LibPath = GCCInstallation.getParentLibPath();
3258 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3259 const Multilib &Multilib = GCCInstallation.getMultilib();
3260 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib" +
3261 Multilib.osSuffix(),
3264 // See comments above on the multilib variant for details of why this is
3265 // only included from within the sysroot.
3266 if (StringRef(LibPath).startswith(SysRoot))
3267 addPathIfExists(LibPath, Paths);
3270 // Similar to the logic for GCC above, if we are currently running Clang
3271 // inside of the requested system root, add its parent library path to those
3273 // FIXME: It's not clear whether we should use the driver's installed
3274 // directory ('Dir' below) or the ResourceDir.
3275 if (StringRef(D.Dir).startswith(SysRoot))
3276 addPathIfExists(D.Dir + "/../lib", Paths);
3278 addPathIfExists(SysRoot + "/lib", Paths);
3279 addPathIfExists(SysRoot + "/usr/lib", Paths);
3282 bool Linux::HasNativeLLVMSupport() const { return true; }
3284 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
3286 Tool *Linux::buildAssembler() const {
3287 return new tools::gnutools::Assembler(*this);
3290 std::string Linux::computeSysRoot() const {
3291 if (!getDriver().SysRoot.empty())
3292 return getDriver().SysRoot;
3294 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3295 return std::string();
3297 // Standalone MIPS toolchains use different names for sysroot folder
3298 // and put it into different places. Here we try to check some known
3301 const StringRef InstallDir = GCCInstallation.getInstallPath();
3302 const StringRef TripleStr = GCCInstallation.getTriple().str();
3303 const Multilib &Multilib = GCCInstallation.getMultilib();
3306 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
3309 if (llvm::sys::fs::exists(Path))
3312 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3314 if (llvm::sys::fs::exists(Path))
3317 return std::string();
3320 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3321 ArgStringList &CC1Args) const {
3322 const Driver &D = getDriver();
3323 std::string SysRoot = computeSysRoot();
3325 if (DriverArgs.hasArg(options::OPT_nostdinc))
3328 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3329 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3331 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3332 SmallString<128> P(D.ResourceDir);
3333 llvm::sys::path::append(P, "include");
3334 addSystemInclude(DriverArgs, CC1Args, P);
3337 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3340 // Check for configure-time C include directories.
3341 StringRef CIncludeDirs(C_INCLUDE_DIRS);
3342 if (CIncludeDirs != "") {
3343 SmallVector<StringRef, 5> dirs;
3344 CIncludeDirs.split(dirs, ":");
3345 for (StringRef dir : dirs) {
3347 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3348 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3353 // Lacking those, try to detect the correct set of system includes for the
3356 // Add include directories specific to the selected multilib set and multilib.
3357 if (GCCInstallation.isValid()) {
3358 const auto &Callback = Multilibs.includeDirsCallback();
3360 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3361 GCCInstallation.getTriple().str(),
3362 GCCInstallation.getMultilib());
3363 for (const auto &Path : IncludePaths)
3364 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3368 // Implement generic Debian multiarch support.
3369 const StringRef X86_64MultiarchIncludeDirs[] = {
3370 "/usr/include/x86_64-linux-gnu",
3372 // FIXME: These are older forms of multiarch. It's not clear that they're
3373 // in use in any released version of Debian, so we should consider
3375 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
3376 const StringRef X86MultiarchIncludeDirs[] = {
3377 "/usr/include/i386-linux-gnu",
3379 // FIXME: These are older forms of multiarch. It's not clear that they're
3380 // in use in any released version of Debian, so we should consider
3382 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3383 "/usr/include/i486-linux-gnu"};
3384 const StringRef AArch64MultiarchIncludeDirs[] = {
3385 "/usr/include/aarch64-linux-gnu"};
3386 const StringRef ARMMultiarchIncludeDirs[] = {
3387 "/usr/include/arm-linux-gnueabi"};
3388 const StringRef ARMHFMultiarchIncludeDirs[] = {
3389 "/usr/include/arm-linux-gnueabihf"};
3390 const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
3391 const StringRef MIPSELMultiarchIncludeDirs[] = {
3392 "/usr/include/mipsel-linux-gnu"};
3393 const StringRef MIPS64MultiarchIncludeDirs[] = {
3394 "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
3395 const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3396 "/usr/include/mips64el-linux-gnu",
3397 "/usr/include/mips64el-linux-gnuabi64"};
3398 const StringRef PPCMultiarchIncludeDirs[] = {
3399 "/usr/include/powerpc-linux-gnu"};
3400 const StringRef PPC64MultiarchIncludeDirs[] = {
3401 "/usr/include/powerpc64-linux-gnu"};
3402 const StringRef PPC64LEMultiarchIncludeDirs[] = {
3403 "/usr/include/powerpc64le-linux-gnu"};
3404 const StringRef SparcMultiarchIncludeDirs[] = {
3405 "/usr/include/sparc-linux-gnu"};
3406 const StringRef Sparc64MultiarchIncludeDirs[] = {
3407 "/usr/include/sparc64-linux-gnu"};
3408 ArrayRef<StringRef> MultiarchIncludeDirs;
3409 switch (getTriple().getArch()) {
3410 case llvm::Triple::x86_64:
3411 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3413 case llvm::Triple::x86:
3414 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3416 case llvm::Triple::aarch64:
3417 case llvm::Triple::aarch64_be:
3418 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3420 case llvm::Triple::arm:
3421 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3422 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3424 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3426 case llvm::Triple::mips:
3427 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3429 case llvm::Triple::mipsel:
3430 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3432 case llvm::Triple::mips64:
3433 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3435 case llvm::Triple::mips64el:
3436 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3438 case llvm::Triple::ppc:
3439 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3441 case llvm::Triple::ppc64:
3442 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3444 case llvm::Triple::ppc64le:
3445 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3447 case llvm::Triple::sparc:
3448 MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
3450 case llvm::Triple::sparcv9:
3451 MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
3456 for (StringRef Dir : MultiarchIncludeDirs) {
3457 if (llvm::sys::fs::exists(SysRoot + Dir)) {
3458 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
3463 if (getTriple().getOS() == llvm::Triple::RTEMS)
3466 // Add an include of '/include' directly. This isn't provided by default by
3467 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
3468 // add even when Clang is acting as-if it were a system compiler.
3469 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
3471 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
3474 /// \brief Helper to add the variant paths of a libstdc++ installation.
3475 /*static*/ bool Linux::addLibStdCXXIncludePaths(
3476 Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
3477 StringRef TargetMultiarchTriple, Twine IncludeSuffix,
3478 const ArgList &DriverArgs, ArgStringList &CC1Args) {
3479 if (!llvm::sys::fs::exists(Base + Suffix))
3482 addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
3484 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
3485 // that path exists or we have neither a GCC nor target multiarch triple, use
3486 // this vanilla search path.
3487 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
3488 llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
3489 addSystemInclude(DriverArgs, CC1Args,
3490 Base + Suffix + "/" + GCCTriple + IncludeSuffix);
3492 // Otherwise try to use multiarch naming schemes which have normalized the
3493 // triples and put the triple before the suffix.
3495 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
3496 // the target triple, so we support that here.
3497 addSystemInclude(DriverArgs, CC1Args,
3498 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
3499 addSystemInclude(DriverArgs, CC1Args,
3500 Base + "/" + TargetMultiarchTriple + Suffix);
3503 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3507 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3508 ArgStringList &CC1Args) const {
3509 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3510 DriverArgs.hasArg(options::OPT_nostdincxx))
3513 // Check if libc++ has been enabled and provide its include paths if so.
3514 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
3515 const std::string LibCXXIncludePathCandidates[] = {
3516 // The primary location is within the Clang installation.
3517 // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
3518 // newer ABI versions.
3519 getDriver().Dir + "/../include/c++/v1",
3521 // We also check the system as for a long time this is the only place
3523 // FIXME: We should really remove this. It doesn't make any sense.
3524 getDriver().SysRoot + "/usr/include/c++/v1"};
3525 for (const auto &IncludePath : LibCXXIncludePathCandidates) {
3526 if (!llvm::sys::fs::exists(IncludePath))
3528 // Add the first candidate that exists.
3529 addSystemInclude(DriverArgs, CC1Args, IncludePath);
3535 // We need a detected GCC installation on Linux to provide libstdc++'s
3536 // headers. We handled the libc++ case above.
3537 if (!GCCInstallation.isValid())
3540 // By default, look for the C++ headers in an include directory adjacent to
3541 // the lib directory of the GCC installation. Note that this is expect to be
3542 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3543 StringRef LibDir = GCCInstallation.getParentLibPath();
3544 StringRef InstallDir = GCCInstallation.getInstallPath();
3545 StringRef TripleStr = GCCInstallation.getTriple().str();
3546 const Multilib &Multilib = GCCInstallation.getMultilib();
3547 const std::string GCCMultiarchTriple =
3548 getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
3549 const std::string TargetMultiarchTriple =
3550 getMultiarchTriple(getTriple(), getDriver().SysRoot);
3551 const GCCVersion &Version = GCCInstallation.getVersion();
3553 // The primary search for libstdc++ supports multiarch variants.
3554 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3555 "/c++/" + Version.Text, TripleStr,
3556 GCCMultiarchTriple, TargetMultiarchTriple,
3557 Multilib.includeSuffix(), DriverArgs, CC1Args))
3560 // Otherwise, fall back on a bunch of options which don't use multiarch
3561 // layouts for simplicity.
3562 const std::string LibStdCXXIncludePathCandidates[] = {
3563 // Gentoo is weird and places its headers inside the GCC install,
3564 // so if the first attempt to find the headers fails, try these patterns.
3565 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3567 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3568 // Android standalone toolchain has C++ headers in yet another place.
3569 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
3570 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
3571 // without a subdirectory corresponding to the gcc version.
3572 LibDir.str() + "/../include/c++",
3575 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3576 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3577 /*GCCMultiarchTriple*/ "",
3578 /*TargetMultiarchTriple*/ "",
3579 Multilib.includeSuffix(), DriverArgs, CC1Args))
3584 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3586 SanitizerMask Linux::getSupportedSanitizers() const {
3587 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3588 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3589 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3590 getTriple().getArch() == llvm::Triple::mips64el;
3591 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
3592 getTriple().getArch() == llvm::Triple::ppc64le;
3593 SanitizerMask Res = ToolChain::getSupportedSanitizers();
3594 Res |= SanitizerKind::Address;
3595 Res |= SanitizerKind::KernelAddress;
3596 Res |= SanitizerKind::Vptr;
3597 if (IsX86_64 || IsMIPS64) {
3598 Res |= SanitizerKind::DataFlow;
3599 Res |= SanitizerKind::Leak;
3600 Res |= SanitizerKind::Thread;
3602 if (IsX86_64 || IsMIPS64 || IsPowerPC64)
3603 Res |= SanitizerKind::Memory;
3604 if (IsX86 || IsX86_64) {
3605 Res |= SanitizerKind::Function;
3606 Res |= SanitizerKind::SafeStack;
3611 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
3613 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
3614 const ArgList &Args)
3615 : Generic_ELF(D, Triple, Args) {
3617 // Path mangling to find libexec
3618 getProgramPaths().push_back(getDriver().getInstalledDir());
3619 if (getDriver().getInstalledDir() != getDriver().Dir)
3620 getProgramPaths().push_back(getDriver().Dir);
3622 getFilePaths().push_back(getDriver().Dir + "/../lib");
3623 getFilePaths().push_back("/usr/lib");
3624 if (llvm::sys::fs::exists("/usr/lib/gcc47"))
3625 getFilePaths().push_back("/usr/lib/gcc47");
3627 getFilePaths().push_back("/usr/lib/gcc44");
3630 Tool *DragonFly::buildAssembler() const {
3631 return new tools::dragonfly::Assembler(*this);
3634 Tool *DragonFly::buildLinker() const {
3635 return new tools::dragonfly::Linker(*this);
3638 /// XCore tool chain
3639 XCore::XCore(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3640 : ToolChain(D, Triple, Args) {
3641 // ProgramPaths are found via 'PATH' environment variable.
3644 Tool *XCore::buildAssembler() const {
3645 return new tools::XCore::Assembler(*this);
3648 Tool *XCore::buildLinker() const { return new tools::XCore::Linker(*this); }
3650 bool XCore::isPICDefault() const { return false; }
3652 bool XCore::isPIEDefault() const { return false; }
3654 bool XCore::isPICDefaultForced() const { return false; }
3656 bool XCore::SupportsProfiling() const { return false; }
3658 bool XCore::hasBlocksRuntime() const { return false; }
3660 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3661 ArgStringList &CC1Args) const {
3662 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3663 DriverArgs.hasArg(options::OPT_nostdlibinc))
3665 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
3666 SmallVector<StringRef, 4> Dirs;
3667 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
3668 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3669 ArrayRef<StringRef> DirVec(Dirs);
3670 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3674 void XCore::addClangTargetOptions(const ArgList &DriverArgs,
3675 ArgStringList &CC1Args) const {
3676 CC1Args.push_back("-nostdsysteminc");
3679 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3680 ArgStringList &CC1Args) const {
3681 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3682 DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3683 DriverArgs.hasArg(options::OPT_nostdincxx))
3685 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
3686 SmallVector<StringRef, 4> Dirs;
3687 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
3688 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3689 ArrayRef<StringRef> DirVec(Dirs);
3690 addSystemIncludes(DriverArgs, CC1Args, DirVec);
3694 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
3695 ArgStringList &CmdArgs) const {
3696 // We don't output any lib args. This is handled by xcc.
3699 // SHAVEToolChain does not call Clang's C compiler.
3700 // We override SelectTool to avoid testing ShouldUseClangCompiler().
3701 Tool *SHAVEToolChain::SelectTool(const JobAction &JA) const {
3702 switch (JA.getKind()) {
3703 case Action::CompileJobClass:
3705 Compiler.reset(new tools::SHAVE::Compiler(*this));
3706 return Compiler.get();
3707 case Action::AssembleJobClass:
3709 Assembler.reset(new tools::SHAVE::Assembler(*this));
3710 return Assembler.get();
3712 return ToolChain::getTool(JA.getKind());
3716 SHAVEToolChain::SHAVEToolChain(const Driver &D, const llvm::Triple &Triple,
3717 const ArgList &Args)
3718 : Generic_GCC(D, Triple, Args) {}
3720 SHAVEToolChain::~SHAVEToolChain() {}
3722 /// Following are methods necessary to avoid having moviClang be an abstract
3725 Tool *SHAVEToolChain::getTool(Action::ActionClass AC) const {
3726 // SelectTool() must find a tool using the method in the superclass.
3727 // There's nothing we can do if that fails.
3728 llvm_unreachable("SHAVEToolChain can't getTool");
3731 Tool *SHAVEToolChain::buildLinker() const {
3732 // SHAVEToolChain executables can not be linked except by the vendor tools.
3733 llvm_unreachable("SHAVEToolChain can't buildLinker");
3736 Tool *SHAVEToolChain::buildAssembler() const {
3737 // This one you'd think should be reachable since we expose an
3738 // assembler to the driver, except not the way it expects.
3739 llvm_unreachable("SHAVEToolChain can't buildAssembler");