1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===//
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/Basic/VirtualFileSystem.h"
14 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/OptTable.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/ProfileData/InstrProf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/TargetParser.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cstdlib> // ::getenv
37 #include <system_error>
39 using namespace clang::driver;
40 using namespace clang::driver::toolchains;
41 using namespace clang;
42 using namespace llvm::opt;
44 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
45 : ToolChain(D, Triple, Args) {
46 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
47 getProgramPaths().push_back(getDriver().getInstalledDir());
48 if (getDriver().getInstalledDir() != getDriver().Dir)
49 getProgramPaths().push_back(getDriver().Dir);
52 /// Darwin - Darwin tool chain for i386 and x86_64.
53 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
54 : MachO(D, Triple, Args), TargetInitialized(false) {}
56 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
57 types::ID Ty = types::lookupTypeForExtension(Ext);
59 // Darwin always preprocesses assembly files (unless -x is used explicitly).
60 if (Ty == types::TY_PP_Asm)
66 bool MachO::HasNativeLLVMSupport() const { return true; }
68 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
69 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
70 if (isTargetWatchOSBased())
71 return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
72 if (isTargetIOSBased())
73 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
75 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
76 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
79 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
80 bool Darwin::hasBlocksRuntime() const {
81 if (isTargetWatchOSBased())
83 else if (isTargetIOSBased())
84 return !isIPhoneOSVersionLT(3, 2);
86 assert(isTargetMacOS() && "unexpected darwin target");
87 return !isMacosxVersionLT(10, 6);
91 // This is just a MachO name translation routine and there's no
92 // way to join this into ARMTargetParser without breaking all
93 // other assumptions. Maybe MachO should consider standardising
94 // their nomenclature.
95 static const char *ArmMachOArchName(StringRef Arch) {
96 return llvm::StringSwitch<const char *>(Arch)
97 .Case("armv6k", "armv6")
98 .Case("armv6m", "armv6m")
99 .Case("armv5tej", "armv5")
100 .Case("xscale", "xscale")
101 .Case("armv4t", "armv4t")
102 .Case("armv7", "armv7")
103 .Cases("armv7a", "armv7-a", "armv7")
104 .Cases("armv7r", "armv7-r", "armv7")
105 .Cases("armv7em", "armv7e-m", "armv7em")
106 .Cases("armv7k", "armv7-k", "armv7k")
107 .Cases("armv7m", "armv7-m", "armv7m")
108 .Cases("armv7s", "armv7-s", "armv7s")
112 static const char *ArmMachOArchNameCPU(StringRef CPU) {
113 unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
114 if (ArchKind == llvm::ARM::AK_INVALID)
116 StringRef Arch = llvm::ARM::getArchName(ArchKind);
118 // FIXME: Make sure this MachO triple mangling is really necessary.
119 // ARMv5* normalises to ARMv5.
120 if (Arch.startswith("armv5"))
121 Arch = Arch.substr(0, 5);
122 // ARMv6*, except ARMv6M, normalises to ARMv6.
123 else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
124 Arch = Arch.substr(0, 5);
125 // ARMv7A normalises to ARMv7.
126 else if (Arch.endswith("v7a"))
127 Arch = Arch.substr(0, 5);
131 static bool isSoftFloatABI(const ArgList &Args) {
132 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
133 options::OPT_mfloat_abi_EQ);
137 return A->getOption().matches(options::OPT_msoft_float) ||
138 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
139 A->getValue() == StringRef("soft"));
142 StringRef MachO::getMachOArchName(const ArgList &Args) const {
143 switch (getTriple().getArch()) {
145 return getDefaultUniversalArchName();
147 case llvm::Triple::aarch64:
150 case llvm::Triple::thumb:
151 case llvm::Triple::arm:
152 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
153 if (const char *Arch = ArmMachOArchName(A->getValue()))
156 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
157 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
168 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
169 types::ID InputType) const {
170 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
172 return Triple.getTriple();
175 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
176 types::ID InputType) const {
177 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
179 // If the target isn't initialized (e.g., an unknown Darwin platform, return
180 // the default triple).
181 if (!isTargetInitialized())
182 return Triple.getTriple();
185 if (isTargetWatchOSBased())
187 else if (isTargetTvOSBased())
189 else if (isTargetIOSBased())
193 Str += getTargetVersion().getAsString();
194 Triple.setOSName(Str);
196 return Triple.getTriple();
199 void Generic_ELF::anchor() {}
201 Tool *MachO::getTool(Action::ActionClass AC) const {
203 case Action::LipoJobClass:
205 Lipo.reset(new tools::darwin::Lipo(*this));
207 case Action::DsymutilJobClass:
209 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
210 return Dsymutil.get();
211 case Action::VerifyDebugInfoJobClass:
213 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
214 return VerifyDebug.get();
216 return ToolChain::getTool(AC);
220 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
222 Tool *MachO::buildAssembler() const {
223 return new tools::darwin::Assembler(*this);
226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
228 : Darwin(D, Triple, Args) {}
230 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
231 // For modern targets, promote certain warnings to errors.
232 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
233 // Always enable -Wdeprecated-objc-isa-usage and promote it
235 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
236 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
238 // For iOS and watchOS, also error about implicit function declarations,
239 // as that can impact calling conventions.
240 if (!isTargetMacOS())
241 CC1Args.push_back("-Werror=implicit-function-declaration");
245 /// \brief Determine whether Objective-C automated reference counting is
247 static bool isObjCAutoRefCount(const ArgList &Args) {
248 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
251 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
252 ArgStringList &CmdArgs) const {
253 // Avoid linking compatibility stubs on i386 mac.
254 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
257 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
259 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
260 runtime.hasSubscripting())
263 CmdArgs.push_back("-force_load");
264 SmallString<128> P(getDriver().ClangExecutable);
265 llvm::sys::path::remove_filename(P); // 'clang'
266 llvm::sys::path::remove_filename(P); // 'bin'
267 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
268 // Mash in the platform.
269 if (isTargetWatchOSSimulator())
270 P += "watchsimulator";
271 else if (isTargetWatchOS())
273 else if (isTargetTvOSSimulator())
274 P += "appletvsimulator";
275 else if (isTargetTvOS())
277 else if (isTargetIOSSimulator())
278 P += "iphonesimulator";
279 else if (isTargetIPhoneOS())
285 CmdArgs.push_back(Args.MakeArgString(P));
288 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
289 StringRef DarwinLibName, bool AlwaysLink,
290 bool IsEmbedded, bool AddRPath) const {
291 SmallString<128> Dir(getDriver().ResourceDir);
292 llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
294 SmallString<128> P(Dir);
295 llvm::sys::path::append(P, DarwinLibName);
297 // For now, allow missing resource libraries to support developers who may
298 // not have compiler-rt checked out or integrated into their build (unless
299 // we explicitly force linking with this library).
300 if (AlwaysLink || getVFS().exists(P))
301 CmdArgs.push_back(Args.MakeArgString(P));
303 // Adding the rpaths might negatively interact when other rpaths are involved,
304 // so we should make sure we add the rpaths last, after all user-specified
305 // rpaths. This is currently true from this place, but we need to be
306 // careful if this function is ever called before user's rpaths are emitted.
308 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
310 // Add @executable_path to rpath to support having the dylib copied with
312 CmdArgs.push_back("-rpath");
313 CmdArgs.push_back("@executable_path");
315 // Add the path to the resource dir to rpath to support using the dylib
316 // from the default location without copying.
317 CmdArgs.push_back("-rpath");
318 CmdArgs.push_back(Args.MakeArgString(Dir));
322 void Darwin::addProfileRTLibs(const ArgList &Args,
323 ArgStringList &CmdArgs) const {
324 if (!needsProfileRT(Args)) return;
326 // TODO: Clean this up once autoconf is gone
327 SmallString<128> P(getDriver().ResourceDir);
328 llvm::sys::path::append(P, "lib", "darwin");
329 const char *Library = "libclang_rt.profile_osx.a";
331 // Select the appropriate runtime library for the target.
332 if (isTargetWatchOS()) {
333 Library = "libclang_rt.profile_watchos.a";
334 } else if (isTargetWatchOSSimulator()) {
335 llvm::sys::path::append(P, "libclang_rt.profile_watchossim.a");
336 Library = getVFS().exists(P) ? "libclang_rt.profile_watchossim.a"
337 : "libclang_rt.profile_watchos.a";
338 } else if (isTargetTvOS()) {
339 Library = "libclang_rt.profile_tvos.a";
340 } else if (isTargetTvOSSimulator()) {
341 llvm::sys::path::append(P, "libclang_rt.profile_tvossim.a");
342 Library = getVFS().exists(P) ? "libclang_rt.profile_tvossim.a"
343 : "libclang_rt.profile_tvos.a";
344 } else if (isTargetIPhoneOS()) {
345 Library = "libclang_rt.profile_ios.a";
346 } else if (isTargetIOSSimulator()) {
347 llvm::sys::path::append(P, "libclang_rt.profile_iossim.a");
348 Library = getVFS().exists(P) ? "libclang_rt.profile_iossim.a"
349 : "libclang_rt.profile_ios.a";
351 assert(isTargetMacOS() && "unexpected non MacOS platform");
353 AddLinkRuntimeLib(Args, CmdArgs, Library,
354 /*AlwaysLink*/ true);
358 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
359 ArgStringList &CmdArgs,
360 StringRef Sanitizer) const {
361 if (!Args.hasArg(options::OPT_dynamiclib) &&
362 !Args.hasArg(options::OPT_bundle)) {
363 // Sanitizer runtime libraries requires C++.
364 AddCXXStdlibLibArgs(Args, CmdArgs);
366 // ASan is not supported on watchOS.
367 assert(isTargetMacOS() || isTargetIOSSimulator());
368 StringRef OS = isTargetMacOS() ? "osx" : "iossim";
371 (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
372 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
375 if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
376 // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
377 // all RTTI-related symbols that UBSan uses.
378 CmdArgs.push_back("-lc++abi");
382 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
383 ArgStringList &CmdArgs) const {
384 // Darwin only supports the compiler-rt based runtime libraries.
385 switch (GetRuntimeLibType(Args)) {
386 case ToolChain::RLT_CompilerRT:
389 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
390 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
394 // Darwin doesn't support real static executables, don't link any runtime
395 // libraries with -static.
396 if (Args.hasArg(options::OPT_static) ||
397 Args.hasArg(options::OPT_fapple_kext) ||
398 Args.hasArg(options::OPT_mkernel))
401 // Reject -static-libgcc for now, we can deal with this when and if someone
402 // cares. This is useful in situations where someone wants to statically link
403 // something like libstdc++, and needs its runtime support routines.
404 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
405 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
409 const SanitizerArgs &Sanitize = getSanitizerArgs();
410 if (Sanitize.needsAsanRt())
411 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
412 if (Sanitize.needsUbsanRt())
413 AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
414 if (Sanitize.needsTsanRt())
415 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
417 // Otherwise link libSystem, then the dynamic runtime library, and finally any
418 // target specific static runtime library.
419 CmdArgs.push_back("-lSystem");
421 // Select the dynamic runtime library and the target specific static library.
422 if (isTargetWatchOSBased()) {
423 // We currently always need a static runtime library for watchOS.
424 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
425 } else if (isTargetTvOSBased()) {
426 // We currently always need a static runtime library for tvOS.
427 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
428 } else if (isTargetIOSBased()) {
429 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
430 // it never went into the SDK.
431 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
432 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
433 getTriple().getArch() != llvm::Triple::aarch64)
434 CmdArgs.push_back("-lgcc_s.1");
436 // We currently always need a static runtime library for iOS.
437 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
439 assert(isTargetMacOS() && "unexpected non MacOS platform");
440 // The dynamic runtime library was merged with libSystem for 10.6 and
441 // beyond; only 10.4 and 10.5 need an additional runtime library.
442 if (isMacosxVersionLT(10, 5))
443 CmdArgs.push_back("-lgcc_s.10.4");
444 else if (isMacosxVersionLT(10, 6))
445 CmdArgs.push_back("-lgcc_s.10.5");
447 // For OS X, we thought we would only need a static runtime library when
448 // targeting 10.4, to provide versions of the static functions which were
449 // omitted from 10.4.dylib.
451 // Unfortunately, that turned out to not be true, because Darwin system
452 // headers can still use eprintf on i386, and it is not exported from
453 // libSystem. Therefore, we still must provide a runtime library just for
454 // the tiny tiny handful of projects that *might* use that symbol.
455 if (isMacosxVersionLT(10, 5)) {
456 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
458 if (getTriple().getArch() == llvm::Triple::x86)
459 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
460 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
465 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
466 const OptTable &Opts = getDriver().getOpts();
468 // Support allowing the SDKROOT environment variable used by xcrun and other
469 // Xcode tools to define the default sysroot, by making it the default for
471 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
472 // Warn if the path does not exist.
473 if (!getVFS().exists(A->getValue()))
474 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
476 if (char *env = ::getenv("SDKROOT")) {
477 // We only use this value as the default if it is an absolute path,
478 // exists, and it is not the root path.
479 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
480 StringRef(env) != "/") {
481 Args.append(Args.MakeSeparateArg(
482 nullptr, Opts.getOption(options::OPT_isysroot), env));
487 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
488 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
489 Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ);
490 Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ);
492 if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
493 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
494 << OSXVersion->getAsString(Args)
495 << (iOSVersion ? iOSVersion :
496 TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
497 iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
498 } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
499 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
500 << iOSVersion->getAsString(Args)
501 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
502 TvOSVersion = WatchOSVersion = nullptr;
503 } else if (TvOSVersion && WatchOSVersion) {
504 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
505 << TvOSVersion->getAsString(Args)
506 << WatchOSVersion->getAsString(Args);
507 WatchOSVersion = nullptr;
508 } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
509 // If no deployment target was specified on the command line, check for
510 // environment defines.
511 std::string OSXTarget;
512 std::string iOSTarget;
513 std::string TvOSTarget;
514 std::string WatchOSTarget;
516 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
518 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
520 if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
522 if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
525 // If there is no command-line argument to specify the Target version and
526 // no environment variable defined, see if we can set the default based
528 if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
529 TvOSTarget.empty() && Args.hasArg(options::OPT_isysroot)) {
530 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
531 StringRef isysroot = A->getValue();
532 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
533 size_t BeginSDK = isysroot.rfind("SDKs/");
534 size_t EndSDK = isysroot.rfind(".sdk");
535 if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
536 StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
537 // Slice the version number out.
538 // Version number is between the first and the last number.
539 size_t StartVer = SDK.find_first_of("0123456789");
540 size_t EndVer = SDK.find_last_of("0123456789");
541 if (StartVer != StringRef::npos && EndVer > StartVer) {
542 StringRef Version = SDK.slice(StartVer, EndVer + 1);
543 if (SDK.startswith("iPhoneOS") ||
544 SDK.startswith("iPhoneSimulator"))
546 else if (SDK.startswith("MacOSX"))
548 else if (SDK.startswith("WatchOS") ||
549 SDK.startswith("WatchSimulator"))
550 WatchOSTarget = Version;
551 else if (SDK.startswith("AppleTVOS") ||
552 SDK.startswith("AppleTVSimulator"))
553 TvOSTarget = Version;
559 // If no OSX or iOS target has been specified, try to guess platform
560 // from arch name and compute the version from the triple.
561 if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
562 WatchOSTarget.empty()) {
563 StringRef MachOArchName = getMachOArchName(Args);
564 unsigned Major, Minor, Micro;
565 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
566 MachOArchName == "arm64") {
567 getTriple().getiOSVersion(Major, Minor, Micro);
568 llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
570 } else if (MachOArchName == "armv7k") {
571 getTriple().getWatchOSVersion(Major, Minor, Micro);
572 llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
574 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
575 MachOArchName != "armv7em") {
576 if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
577 getDriver().Diag(diag::err_drv_invalid_darwin_version)
578 << getTriple().getOSName();
580 llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
585 // Do not allow conflicts with the watchOS target.
586 if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
587 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
588 << "WATCHOS_DEPLOYMENT_TARGET"
589 << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
590 "TVOS_DEPLOYMENT_TARGET");
593 // Do not allow conflicts with the tvOS target.
594 if (!TvOSTarget.empty() && !iOSTarget.empty()) {
595 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
596 << "TVOS_DEPLOYMENT_TARGET"
597 << "IPHONEOS_DEPLOYMENT_TARGET";
600 // Allow conflicts among OSX and iOS for historical reasons, but choose the
602 if (!OSXTarget.empty() && (!iOSTarget.empty() ||
603 !WatchOSTarget.empty() ||
604 !TvOSTarget.empty())) {
605 if (getTriple().getArch() == llvm::Triple::arm ||
606 getTriple().getArch() == llvm::Triple::aarch64 ||
607 getTriple().getArch() == llvm::Triple::thumb)
610 iOSTarget = WatchOSTarget = TvOSTarget = "";
613 if (!OSXTarget.empty()) {
614 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
615 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
616 Args.append(OSXVersion);
617 } else if (!iOSTarget.empty()) {
618 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
619 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
620 Args.append(iOSVersion);
621 } else if (!TvOSTarget.empty()) {
622 const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
623 TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
624 Args.append(TvOSVersion);
625 } else if (!WatchOSTarget.empty()) {
626 const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
627 WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
628 Args.append(WatchOSVersion);
632 DarwinPlatformKind Platform;
637 else if (TvOSVersion)
639 else if (WatchOSVersion)
642 llvm_unreachable("Unable to infer Darwin variant");
644 // Set the tool chain target information.
645 unsigned Major, Minor, Micro;
647 if (Platform == MacOS) {
648 assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
649 "Unknown target platform!");
650 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
652 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
653 getDriver().Diag(diag::err_drv_invalid_version_number)
654 << OSXVersion->getAsString(Args);
655 } else if (Platform == IPhoneOS) {
656 assert(iOSVersion && "Unknown target platform!");
657 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
659 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
660 getDriver().Diag(diag::err_drv_invalid_version_number)
661 << iOSVersion->getAsString(Args);
662 } else if (Platform == TvOS) {
663 if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
664 Micro, HadExtra) || HadExtra ||
665 Major >= 10 || Minor >= 100 || Micro >= 100)
666 getDriver().Diag(diag::err_drv_invalid_version_number)
667 << TvOSVersion->getAsString(Args);
668 } else if (Platform == WatchOS) {
669 if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
670 Micro, HadExtra) || HadExtra ||
671 Major >= 10 || Minor >= 100 || Micro >= 100)
672 getDriver().Diag(diag::err_drv_invalid_version_number)
673 << WatchOSVersion->getAsString(Args);
675 llvm_unreachable("unknown kind of Darwin platform");
677 // Recognize iOS targets with an x86 architecture as the iOS simulator.
678 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
679 getTriple().getArch() == llvm::Triple::x86_64))
680 Platform = IPhoneOSSimulator;
681 if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
682 getTriple().getArch() == llvm::Triple::x86_64))
683 Platform = TvOSSimulator;
684 if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
685 getTriple().getArch() == llvm::Triple::x86_64))
686 Platform = WatchOSSimulator;
688 setTarget(Platform, Major, Minor, Micro);
691 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
692 ArgStringList &CmdArgs) const {
693 CXXStdlibType Type = GetCXXStdlibType(Args);
696 case ToolChain::CST_Libcxx:
697 CmdArgs.push_back("-lc++");
700 case ToolChain::CST_Libstdcxx:
701 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
702 // it was previously found in the gcc lib dir. However, for all the Darwin
703 // platforms we care about it was -lstdc++.6, so we search for that
704 // explicitly if we can't see an obvious -lstdc++ candidate.
706 // Check in the sysroot first.
707 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
708 SmallString<128> P(A->getValue());
709 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
711 if (!getVFS().exists(P)) {
712 llvm::sys::path::remove_filename(P);
713 llvm::sys::path::append(P, "libstdc++.6.dylib");
714 if (getVFS().exists(P)) {
715 CmdArgs.push_back(Args.MakeArgString(P));
721 // Otherwise, look in the root.
722 // FIXME: This should be removed someday when we don't have to care about
723 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
724 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
725 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
726 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
730 // Otherwise, let the linker search.
731 CmdArgs.push_back("-lstdc++");
736 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
737 ArgStringList &CmdArgs) const {
739 // For Darwin platforms, use the compiler-rt-based support library
740 // instead of the gcc-provided one (which is also incidentally
741 // only present in the gcc lib dir, which makes it hard to find).
743 SmallString<128> P(getDriver().ResourceDir);
744 llvm::sys::path::append(P, "lib", "darwin");
746 // Use the newer cc_kext for iOS ARM after 6.0.
747 if (isTargetWatchOS()) {
748 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
749 } else if (isTargetTvOS()) {
750 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
751 } else if (isTargetIPhoneOS()) {
752 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
754 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
757 // For now, allow missing resource libraries to support developers who may
758 // not have compiler-rt checked out or integrated into their build.
759 if (getVFS().exists(P))
760 CmdArgs.push_back(Args.MakeArgString(P));
763 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
764 const char *BoundArch) const {
765 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
766 const OptTable &Opts = getDriver().getOpts();
768 // FIXME: We really want to get out of the tool chain level argument
769 // translation business, as it makes the driver functionality much
770 // more opaque. For now, we follow gcc closely solely for the
771 // purpose of easily achieving feature parity & testability. Once we
772 // have something that works, we should reevaluate each translation
773 // and try to push it down into tool specific logic.
775 for (Arg *A : Args) {
776 if (A->getOption().matches(options::OPT_Xarch__)) {
777 // Skip this argument unless the architecture matches either the toolchain
778 // triple arch, or the arch being bound.
779 llvm::Triple::ArchType XarchArch =
780 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
781 if (!(XarchArch == getArch() ||
784 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
787 Arg *OriginalArg = A;
788 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
789 unsigned Prev = Index;
790 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
792 // If the argument parsing failed or more than one argument was
793 // consumed, the -Xarch_ argument's parameter tried to consume
794 // extra arguments. Emit an error and ignore.
796 // We also want to disallow any options which would alter the
797 // driver behavior; that isn't going to work in our model. We
798 // use isDriverOption() as an approximation, although things
799 // like -O4 are going to slip through.
800 if (!XarchArg || Index > Prev + 1) {
801 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
802 << A->getAsString(Args);
804 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
805 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
806 << A->getAsString(Args);
810 XarchArg->setBaseArg(A);
812 A = XarchArg.release();
813 DAL->AddSynthesizedArg(A);
815 // Linker input arguments require custom handling. The problem is that we
816 // have already constructed the phase actions, so we can not treat them as
817 // "input arguments".
818 if (A->getOption().hasFlag(options::LinkerInput)) {
819 // Convert the argument into individual Zlinker_input_args.
820 for (const char *Value : A->getValues()) {
822 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
828 // Sob. These is strictly gcc compatible for the time being. Apple
829 // gcc translates options twice, which means that self-expanding
830 // options add duplicates.
831 switch ((options::ID)A->getOption().getID()) {
836 case options::OPT_mkernel:
837 case options::OPT_fapple_kext:
839 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
842 case options::OPT_dependency_file:
843 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
846 case options::OPT_gfull:
847 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
849 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
852 case options::OPT_gused:
853 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
855 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
858 case options::OPT_shared:
859 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
862 case options::OPT_fconstant_cfstrings:
863 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
866 case options::OPT_fno_constant_cfstrings:
867 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
870 case options::OPT_Wnonportable_cfstrings:
872 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
875 case options::OPT_Wno_nonportable_cfstrings:
877 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
880 case options::OPT_fpascal_strings:
881 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
884 case options::OPT_fno_pascal_strings:
885 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
890 if (getTriple().getArch() == llvm::Triple::x86 ||
891 getTriple().getArch() == llvm::Triple::x86_64)
892 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
893 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
896 // Add the arch options based on the particular spelling of -arch, to match
897 // how the driver driver works.
899 StringRef Name = BoundArch;
900 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
901 const Option MArch = Opts.getOption(options::OPT_march_EQ);
903 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
904 // which defines the list of which architectures we accept.
907 else if (Name == "ppc601")
908 DAL->AddJoinedArg(nullptr, MCpu, "601");
909 else if (Name == "ppc603")
910 DAL->AddJoinedArg(nullptr, MCpu, "603");
911 else if (Name == "ppc604")
912 DAL->AddJoinedArg(nullptr, MCpu, "604");
913 else if (Name == "ppc604e")
914 DAL->AddJoinedArg(nullptr, MCpu, "604e");
915 else if (Name == "ppc750")
916 DAL->AddJoinedArg(nullptr, MCpu, "750");
917 else if (Name == "ppc7400")
918 DAL->AddJoinedArg(nullptr, MCpu, "7400");
919 else if (Name == "ppc7450")
920 DAL->AddJoinedArg(nullptr, MCpu, "7450");
921 else if (Name == "ppc970")
922 DAL->AddJoinedArg(nullptr, MCpu, "970");
924 else if (Name == "ppc64" || Name == "ppc64le")
925 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
927 else if (Name == "i386")
929 else if (Name == "i486")
930 DAL->AddJoinedArg(nullptr, MArch, "i486");
931 else if (Name == "i586")
932 DAL->AddJoinedArg(nullptr, MArch, "i586");
933 else if (Name == "i686")
934 DAL->AddJoinedArg(nullptr, MArch, "i686");
935 else if (Name == "pentium")
936 DAL->AddJoinedArg(nullptr, MArch, "pentium");
937 else if (Name == "pentium2")
938 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
939 else if (Name == "pentpro")
940 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
941 else if (Name == "pentIIm3")
942 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
944 else if (Name == "x86_64")
945 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
946 else if (Name == "x86_64h") {
947 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
948 DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
951 else if (Name == "arm")
952 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
953 else if (Name == "armv4t")
954 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
955 else if (Name == "armv5")
956 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
957 else if (Name == "xscale")
958 DAL->AddJoinedArg(nullptr, MArch, "xscale");
959 else if (Name == "armv6")
960 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
961 else if (Name == "armv6m")
962 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
963 else if (Name == "armv7")
964 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
965 else if (Name == "armv7em")
966 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
967 else if (Name == "armv7k")
968 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
969 else if (Name == "armv7m")
970 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
971 else if (Name == "armv7s")
972 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
978 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
979 ArgStringList &CmdArgs) const {
980 // Embedded targets are simple at the moment, not supporting sanitizers and
981 // with different libraries for each member of the product { static, PIC } x
982 // { hard-float, soft-float }
983 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
985 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
988 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
990 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
993 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
994 const char *BoundArch) const {
995 // First get the generic Apple args, before moving onto Darwin-specific ones.
996 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
997 const OptTable &Opts = getDriver().getOpts();
999 // If no architecture is bound, none of the translations here are relevant.
1003 // Add an explicit version min argument for the deployment target. We do this
1004 // after argument translation because -Xarch_ arguments may add a version min
1006 AddDeploymentTarget(*DAL);
1008 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1009 // FIXME: It would be far better to avoid inserting those -static arguments,
1010 // but we can't check the deployment target in the translation code until
1012 if (isTargetWatchOSBased() ||
1013 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1014 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1017 if (A->getOption().getID() != options::OPT_mkernel &&
1018 A->getOption().getID() != options::OPT_fapple_kext)
1020 assert(it != ie && "unexpected argument translation");
1022 assert(A->getOption().getID() == options::OPT_static &&
1023 "missing expected -static argument");
1024 it = DAL->getArgs().erase(it);
1028 // Default to use libc++ on OS X 10.9+ and iOS 7+.
1029 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
1030 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
1031 isTargetWatchOSBased()) &&
1032 !Args.getLastArg(options::OPT_stdlib_EQ))
1033 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1036 // Validate the C++ standard library choice.
1037 CXXStdlibType Type = GetCXXStdlibType(*DAL);
1038 if (Type == ToolChain::CST_Libcxx) {
1039 // Check whether the target provides libc++.
1042 // Complain about targeting iOS < 5.0 in any way.
1043 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1046 if (where != StringRef()) {
1047 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1054 bool MachO::IsUnwindTablesDefault() const {
1055 return getArch() == llvm::Triple::x86_64;
1058 bool MachO::UseDwarfDebugFlags() const {
1059 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1060 return S[0] != '\0';
1064 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1065 // Darwin uses SjLj exceptions on ARM.
1066 if (getTriple().getArch() != llvm::Triple::arm &&
1067 getTriple().getArch() != llvm::Triple::thumb)
1070 // Only watchOS uses the new DWARF/Compact unwinding method.
1071 return !isTargetWatchOS();
1074 bool MachO::isPICDefault() const { return true; }
1076 bool MachO::isPIEDefault() const { return false; }
1078 bool MachO::isPICDefaultForced() const {
1079 return (getArch() == llvm::Triple::x86_64 ||
1080 getArch() == llvm::Triple::aarch64);
1083 bool MachO::SupportsProfiling() const {
1084 // Profiling instrumentation is only supported on x86.
1085 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1088 void Darwin::addMinVersionArgs(const ArgList &Args,
1089 ArgStringList &CmdArgs) const {
1090 VersionTuple TargetVersion = getTargetVersion();
1092 if (isTargetWatchOS())
1093 CmdArgs.push_back("-watchos_version_min");
1094 else if (isTargetWatchOSSimulator())
1095 CmdArgs.push_back("-watchos_simulator_version_min");
1096 else if (isTargetTvOS())
1097 CmdArgs.push_back("-tvos_version_min");
1098 else if (isTargetTvOSSimulator())
1099 CmdArgs.push_back("-tvos_simulator_version_min");
1100 else if (isTargetIOSSimulator())
1101 CmdArgs.push_back("-ios_simulator_version_min");
1102 else if (isTargetIOSBased())
1103 CmdArgs.push_back("-iphoneos_version_min");
1105 assert(isTargetMacOS() && "unexpected target");
1106 CmdArgs.push_back("-macosx_version_min");
1109 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1112 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1113 ArgStringList &CmdArgs) const {
1114 // Derived from startfile spec.
1115 if (Args.hasArg(options::OPT_dynamiclib)) {
1116 // Derived from darwin_dylib1 spec.
1117 if (isTargetWatchOSBased()) {
1118 ; // watchOS does not need dylib1.o.
1119 } else if (isTargetIOSSimulator()) {
1120 ; // iOS simulator does not need dylib1.o.
1121 } else if (isTargetIPhoneOS()) {
1122 if (isIPhoneOSVersionLT(3, 1))
1123 CmdArgs.push_back("-ldylib1.o");
1125 if (isMacosxVersionLT(10, 5))
1126 CmdArgs.push_back("-ldylib1.o");
1127 else if (isMacosxVersionLT(10, 6))
1128 CmdArgs.push_back("-ldylib1.10.5.o");
1131 if (Args.hasArg(options::OPT_bundle)) {
1132 if (!Args.hasArg(options::OPT_static)) {
1133 // Derived from darwin_bundle1 spec.
1134 if (isTargetWatchOSBased()) {
1135 ; // watchOS does not need bundle1.o.
1136 } else if (isTargetIOSSimulator()) {
1137 ; // iOS simulator does not need bundle1.o.
1138 } else if (isTargetIPhoneOS()) {
1139 if (isIPhoneOSVersionLT(3, 1))
1140 CmdArgs.push_back("-lbundle1.o");
1142 if (isMacosxVersionLT(10, 6))
1143 CmdArgs.push_back("-lbundle1.o");
1147 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1148 if (Args.hasArg(options::OPT_static) ||
1149 Args.hasArg(options::OPT_object) ||
1150 Args.hasArg(options::OPT_preload)) {
1151 CmdArgs.push_back("-lgcrt0.o");
1153 CmdArgs.push_back("-lgcrt1.o");
1155 // darwin_crt2 spec is empty.
1157 // By default on OS X 10.8 and later, we don't link with a crt1.o
1158 // file and the linker knows to use _main as the entry point. But,
1159 // when compiling with -pg, we need to link with the gcrt1.o file,
1160 // so pass the -no_new_main option to tell the linker to use the
1161 // "start" symbol as the entry point.
1162 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1163 CmdArgs.push_back("-no_new_main");
1165 if (Args.hasArg(options::OPT_static) ||
1166 Args.hasArg(options::OPT_object) ||
1167 Args.hasArg(options::OPT_preload)) {
1168 CmdArgs.push_back("-lcrt0.o");
1170 // Derived from darwin_crt1 spec.
1171 if (isTargetWatchOSBased()) {
1172 ; // watchOS does not need crt1.o.
1173 } else if (isTargetIOSSimulator()) {
1174 ; // iOS simulator does not need crt1.o.
1175 } else if (isTargetIPhoneOS()) {
1176 if (getArch() == llvm::Triple::aarch64)
1177 ; // iOS does not need any crt1 files for arm64
1178 else if (isIPhoneOSVersionLT(3, 1))
1179 CmdArgs.push_back("-lcrt1.o");
1180 else if (isIPhoneOSVersionLT(6, 0))
1181 CmdArgs.push_back("-lcrt1.3.1.o");
1183 if (isMacosxVersionLT(10, 5))
1184 CmdArgs.push_back("-lcrt1.o");
1185 else if (isMacosxVersionLT(10, 6))
1186 CmdArgs.push_back("-lcrt1.10.5.o");
1187 else if (isMacosxVersionLT(10, 8))
1188 CmdArgs.push_back("-lcrt1.10.6.o");
1190 // darwin_crt2 spec is empty.
1197 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1198 !isTargetWatchOS() &&
1199 isMacosxVersionLT(10, 5)) {
1200 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1201 CmdArgs.push_back(Str);
1205 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1207 void Darwin::CheckObjCARC() const {
1208 if (isTargetIOSBased() || isTargetWatchOSBased() ||
1209 (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1211 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1214 SanitizerMask Darwin::getSupportedSanitizers() const {
1215 SanitizerMask Res = ToolChain::getSupportedSanitizers();
1216 if (isTargetMacOS() || isTargetIOSSimulator())
1217 Res |= SanitizerKind::Address;
1218 if (isTargetMacOS()) {
1219 if (!isMacosxVersionLT(10, 9))
1220 Res |= SanitizerKind::Vptr;
1221 Res |= SanitizerKind::SafeStack;
1222 Res |= SanitizerKind::Thread;
1227 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1228 /// all subcommands; this relies on gcc translating the majority of
1229 /// command line options.
1231 /// \brief Parse a GCCVersion object out of a string of text.
1233 /// This is the primary means of forming GCCVersion objects.
1235 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1236 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1237 std::pair<StringRef, StringRef> First = VersionText.split('.');
1238 std::pair<StringRef, StringRef> Second = First.second.split('.');
1240 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1241 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1243 GoodVersion.MajorStr = First.first.str();
1244 if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1246 GoodVersion.MinorStr = Second.first.str();
1248 // First look for a number prefix and parse that if present. Otherwise just
1249 // stash the entire patch string in the suffix, and leave the number
1250 // unspecified. This covers versions strings such as:
1256 // And retains any patch number it finds.
1257 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1258 if (!PatchText.empty()) {
1259 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1260 // Try to parse the number and any suffix.
1261 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1262 GoodVersion.Patch < 0)
1264 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1271 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1272 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1274 StringRef RHSPatchSuffix) const {
1275 if (Major != RHSMajor)
1276 return Major < RHSMajor;
1277 if (Minor != RHSMinor)
1278 return Minor < RHSMinor;
1279 if (Patch != RHSPatch) {
1280 // Note that versions without a specified patch sort higher than those with
1287 // Otherwise just sort on the patch itself.
1288 return Patch < RHSPatch;
1290 if (PatchSuffix != RHSPatchSuffix) {
1291 // Sort empty suffixes higher.
1292 if (RHSPatchSuffix.empty())
1294 if (PatchSuffix.empty())
1297 // Provide a lexicographic sort to make this a total ordering.
1298 return PatchSuffix < RHSPatchSuffix;
1301 // The versions are equal.
1305 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1306 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1308 return A->getValue();
1309 return GCC_INSTALL_PREFIX;
1312 /// \brief Initialize a GCCInstallationDetector from the driver.
1314 /// This performs all of the autodetection and sets up the various paths.
1315 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1317 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1318 /// should instead pull the target out of the driver. This is currently
1319 /// necessary because the driver doesn't store the final version of the target
1321 void Generic_GCC::GCCInstallationDetector::init(
1322 const llvm::Triple &TargetTriple, const ArgList &Args,
1323 ArrayRef<std::string> ExtraTripleAliases) {
1324 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1325 ? TargetTriple.get64BitArchVariant()
1326 : TargetTriple.get32BitArchVariant();
1327 // The library directories which may contain GCC installations.
1328 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1329 // The compatible GCC triples for this particular architecture.
1330 SmallVector<StringRef, 16> CandidateTripleAliases;
1331 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1332 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1333 CandidateTripleAliases, CandidateBiarchLibDirs,
1334 CandidateBiarchTripleAliases);
1336 // Compute the set of prefixes for our search.
1337 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1338 D.PrefixDirs.end());
1340 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1341 if (GCCToolchainDir != "") {
1342 if (GCCToolchainDir.back() == '/')
1343 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1345 Prefixes.push_back(GCCToolchainDir);
1347 // If we have a SysRoot, try that first.
1348 if (!D.SysRoot.empty()) {
1349 Prefixes.push_back(D.SysRoot);
1350 Prefixes.push_back(D.SysRoot + "/usr");
1353 // Then look for gcc installed alongside clang.
1354 Prefixes.push_back(D.InstalledDir + "/..");
1356 // And finally in /usr.
1357 if (D.SysRoot.empty())
1358 Prefixes.push_back("/usr");
1361 // Loop over the various components which exist and select the best GCC
1362 // installation available. GCC installs are ranked by version number.
1363 Version = GCCVersion::Parse("0.0.0");
1364 for (const std::string &Prefix : Prefixes) {
1365 if (!D.getVFS().exists(Prefix))
1367 for (StringRef Suffix : CandidateLibDirs) {
1368 const std::string LibDir = Prefix + Suffix.str();
1369 if (!D.getVFS().exists(LibDir))
1371 for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1372 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1373 for (StringRef Candidate : CandidateTripleAliases)
1374 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1376 for (StringRef Suffix : CandidateBiarchLibDirs) {
1377 const std::string LibDir = Prefix + Suffix.str();
1378 if (!D.getVFS().exists(LibDir))
1380 for (StringRef Candidate : CandidateBiarchTripleAliases)
1381 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1382 /*NeedsBiarchSuffix=*/ true);
1387 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1388 for (const auto &InstallPath : CandidateGCCInstallPaths)
1389 OS << "Found candidate GCC installation: " << InstallPath << "\n";
1391 if (!GCCInstallPath.empty())
1392 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1394 for (const auto &Multilib : Multilibs)
1395 OS << "Candidate multilib: " << Multilib << "\n";
1397 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1398 OS << "Selected multilib: " << SelectedMultilib << "\n";
1401 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1402 if (BiarchSibling.hasValue()) {
1403 M = BiarchSibling.getValue();
1409 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1410 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1411 SmallVectorImpl<StringRef> &LibDirs,
1412 SmallVectorImpl<StringRef> &TripleAliases,
1413 SmallVectorImpl<StringRef> &BiarchLibDirs,
1414 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1415 // Declare a bunch of static data sets that we'll select between below. These
1416 // are specifically designed to always refer to string literals to avoid any
1417 // lifetime or initialization issues.
1418 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1419 static const char *const AArch64Triples[] = {
1420 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1421 "aarch64-redhat-linux"};
1422 static const char *const AArch64beLibDirs[] = {"/lib"};
1423 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1424 "aarch64_be-linux-gnu"};
1426 static const char *const ARMLibDirs[] = {"/lib"};
1427 static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1428 "arm-linux-androideabi"};
1429 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1430 "armv7hl-redhat-linux-gnueabi"};
1431 static const char *const ARMebLibDirs[] = {"/lib"};
1432 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1433 "armeb-linux-androideabi"};
1434 static const char *const ARMebHFTriples[] = {
1435 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1437 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1438 static const char *const X86_64Triples[] = {
1439 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1440 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1441 "x86_64-redhat-linux", "x86_64-suse-linux",
1442 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1443 "x86_64-slackware-linux", "x86_64-linux-android",
1444 "x86_64-unknown-linux"};
1445 static const char *const X32LibDirs[] = {"/libx32"};
1446 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1447 static const char *const X86Triples[] = {
1448 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1449 "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1450 "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1451 "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1454 static const char *const MIPSLibDirs[] = {"/lib"};
1455 static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1456 "mips-mti-linux-gnu",
1457 "mips-img-linux-gnu"};
1458 static const char *const MIPSELLibDirs[] = {"/lib"};
1459 static const char *const MIPSELTriples[] = {
1460 "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
1462 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1463 static const char *const MIPS64Triples[] = {
1464 "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1465 "mips64-linux-gnuabi64"};
1466 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1467 static const char *const MIPS64ELTriples[] = {
1468 "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1469 "mips64el-linux-android", "mips64el-linux-gnuabi64"};
1471 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1472 static const char *const PPCTriples[] = {
1473 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1474 "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1475 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1476 static const char *const PPC64Triples[] = {
1477 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1478 "powerpc64-suse-linux", "ppc64-redhat-linux"};
1479 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1480 static const char *const PPC64LETriples[] = {
1481 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1482 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1484 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1485 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1486 "sparcv8-linux-gnu"};
1487 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1488 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1489 "sparcv9-linux-gnu"};
1491 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1492 static const char *const SystemZTriples[] = {
1493 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1494 "s390x-suse-linux", "s390x-redhat-linux"};
1497 static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
1498 static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
1499 "i386-pc-solaris2.11"};
1504 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1505 LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
1506 TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
1510 switch (TargetTriple.getArch()) {
1511 case llvm::Triple::aarch64:
1512 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1513 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1514 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1515 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1517 case llvm::Triple::aarch64_be:
1518 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1519 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1520 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1521 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1523 case llvm::Triple::arm:
1524 case llvm::Triple::thumb:
1525 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1526 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1527 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1529 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1532 case llvm::Triple::armeb:
1533 case llvm::Triple::thumbeb:
1534 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1535 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1536 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1538 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1541 case llvm::Triple::x86_64:
1542 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1543 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1544 // x32 is always available when x86_64 is available, so adding it as
1545 // secondary arch with x86_64 triples
1546 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1547 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1548 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1550 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1551 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1554 case llvm::Triple::x86:
1555 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1556 TripleAliases.append(begin(X86Triples), end(X86Triples));
1557 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1558 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1560 case llvm::Triple::mips:
1561 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1562 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1563 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1564 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1566 case llvm::Triple::mipsel:
1567 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1568 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1569 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1570 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1571 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1573 case llvm::Triple::mips64:
1574 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1575 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1576 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1577 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1579 case llvm::Triple::mips64el:
1580 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1581 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1582 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1583 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1584 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1586 case llvm::Triple::ppc:
1587 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1588 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1589 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1590 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1592 case llvm::Triple::ppc64:
1593 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1594 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1595 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1596 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1598 case llvm::Triple::ppc64le:
1599 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1600 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1602 case llvm::Triple::sparc:
1603 case llvm::Triple::sparcel:
1604 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1605 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1606 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1607 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1609 case llvm::Triple::sparcv9:
1610 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1611 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1612 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1613 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1615 case llvm::Triple::systemz:
1616 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1617 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1620 // By default, just rely on the standard lib directories and the original
1625 // Always append the drivers target triple to the end, in case it doesn't
1626 // match any of our aliases.
1627 TripleAliases.push_back(TargetTriple.str());
1629 // Also include the multiarch variant if it's different.
1630 if (TargetTriple.str() != BiarchTriple.str())
1631 BiarchTripleAliases.push_back(BiarchTriple.str());
1634 // \brief -- try common CUDA installation paths looking for files we need for
1635 // CUDA compilation.
1637 void Generic_GCC::CudaInstallationDetector::init(
1638 const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args) {
1639 SmallVector<std::string, 4> CudaPathCandidates;
1641 if (Args.hasArg(options::OPT_cuda_path_EQ))
1642 CudaPathCandidates.push_back(
1643 Args.getLastArgValue(options::OPT_cuda_path_EQ));
1645 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1646 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.5");
1647 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.0");
1650 for (const auto &CudaPath : CudaPathCandidates) {
1651 if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1654 CudaInstallPath = CudaPath;
1655 CudaIncludePath = CudaInstallPath + "/include";
1656 CudaLibDevicePath = CudaInstallPath + "/nvvm/libdevice";
1658 CudaInstallPath + (TargetTriple.isArch64Bit() ? "/lib64" : "/lib");
1660 if (!(D.getVFS().exists(CudaIncludePath) &&
1661 D.getVFS().exists(CudaLibPath) &&
1662 D.getVFS().exists(CudaLibDevicePath)))
1666 for (llvm::sys::fs::directory_iterator LI(CudaLibDevicePath, EC), LE;
1667 !EC && LI != LE; LI = LI.increment(EC)) {
1668 StringRef FilePath = LI->path();
1669 StringRef FileName = llvm::sys::path::filename(FilePath);
1670 // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1671 const StringRef LibDeviceName = "libdevice.";
1672 if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1674 StringRef GpuArch = FileName.slice(
1675 LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1676 CudaLibDeviceMap[GpuArch] = FilePath.str();
1677 // Insert map entries for specifc devices with this compute capability.
1678 if (GpuArch == "compute_20") {
1679 CudaLibDeviceMap["sm_20"] = FilePath;
1680 CudaLibDeviceMap["sm_21"] = FilePath;
1681 } else if (GpuArch == "compute_30") {
1682 CudaLibDeviceMap["sm_30"] = FilePath;
1683 CudaLibDeviceMap["sm_32"] = FilePath;
1684 } else if (GpuArch == "compute_35") {
1685 CudaLibDeviceMap["sm_35"] = FilePath;
1686 CudaLibDeviceMap["sm_37"] = FilePath;
1695 void Generic_GCC::CudaInstallationDetector::print(raw_ostream &OS) const {
1697 OS << "Found CUDA installation: " << CudaInstallPath << "\n";
1701 // Filter to remove Multilibs that don't exist as a suffix to Path
1702 class FilterNonExistent {
1704 vfs::FileSystem &VFS;
1707 FilterNonExistent(StringRef Base, vfs::FileSystem &VFS)
1708 : Base(Base), VFS(VFS) {}
1709 bool operator()(const Multilib &M) {
1710 return !VFS.exists(Base + M.gccSuffix() + "/crtbegin.o");
1713 } // end anonymous namespace
1715 static void addMultilibFlag(bool Enabled, const char *const Flag,
1716 std::vector<std::string> &Flags) {
1718 Flags.push_back(std::string("+") + Flag);
1720 Flags.push_back(std::string("-") + Flag);
1723 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1724 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1725 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1728 static bool isMips32(llvm::Triple::ArchType Arch) {
1729 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1732 static bool isMips64(llvm::Triple::ArchType Arch) {
1733 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1736 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1737 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1740 static bool isMips16(const ArgList &Args) {
1741 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1742 return A && A->getOption().matches(options::OPT_mips16);
1745 static bool isMicroMips(const ArgList &Args) {
1746 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1747 return A && A->getOption().matches(options::OPT_mmicromips);
1751 struct DetectedMultilibs {
1752 /// The set of multilibs that the detected installation supports.
1753 MultilibSet Multilibs;
1755 /// The primary multilib appropriate for the given flags.
1756 Multilib SelectedMultilib;
1758 /// On Biarch systems, this corresponds to the default multilib when
1759 /// targeting the non-default multilib. Otherwise, it is empty.
1760 llvm::Optional<Multilib> BiarchSibling;
1762 } // end anonymous namespace
1764 static Multilib makeMultilib(StringRef commonSuffix) {
1765 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1768 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1769 StringRef Path, const ArgList &Args,
1770 DetectedMultilibs &Result) {
1771 // Some MIPS toolchains put libraries and object files compiled
1772 // using different options in to the sub-directoris which names
1773 // reflects the flags used for compilation. For example sysroot
1774 // directory might looks like the following examples:
1777 // /lib <= crt*.o files compiled with '-mips32'
1780 // /lib <= crt*.o files compiled with '-mips16'
1783 // /lib <= crt*.o files compiled with '-mips16 -EL'
1788 // /lib <= crt*.o files compiled with '-mips32r2'
1791 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1794 // /lib <= crt*.o files compiled with '-mips32'
1796 FilterNonExistent NonExistent(Path, D.getVFS());
1798 // Check for FSF toolchain multilibs
1799 MultilibSet FSFMipsMultilibs;
1801 auto MArchMips32 = makeMultilib("/mips32")
1804 .flag("-mmicromips")
1805 .flag("+march=mips32");
1807 auto MArchMicroMips = makeMultilib("/micromips")
1810 .flag("+mmicromips");
1812 auto MArchMips64r2 = makeMultilib("/mips64r2")
1815 .flag("+march=mips64r2");
1817 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1820 auto MArchDefault = makeMultilib("")
1823 .flag("-mmicromips")
1824 .flag("+march=mips32r2");
1826 auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1828 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1831 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1833 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1835 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1837 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1839 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1843 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1847 .FilterOut("/mips64/mips16")
1848 .FilterOut("/mips64r2/mips16")
1849 .FilterOut("/micromips/mips16")
1851 .FilterOut("/micromips/64")
1852 .FilterOut("/mips32/64")
1854 .FilterOut("/mips16/64")
1855 .Either(BigEndian, LittleEndian)
1858 .FilterOut(".*sof/nan2008")
1859 .FilterOut(NonExistent)
1860 .setIncludeDirsCallback([](StringRef InstallDir,
1861 StringRef TripleStr, const Multilib &M) {
1862 std::vector<std::string> Dirs;
1863 Dirs.push_back((InstallDir + "/include").str());
1864 std::string SysRootInc =
1865 InstallDir.str() + "/../../../../sysroot";
1866 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1867 Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1869 Dirs.push_back(SysRootInc + "/usr/include");
1874 // Check for Musl toolchain multilibs
1875 MultilibSet MuslMipsMultilibs;
1877 auto MArchMipsR2 = makeMultilib("")
1878 .osSuffix("/mips-r2-hard-musl")
1881 .flag("+march=mips32r2");
1883 auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1886 .flag("+march=mips32r2");
1888 MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1890 // Specify the callback that computes the include directories.
1891 MuslMipsMultilibs.setIncludeDirsCallback([](
1892 StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1893 std::vector<std::string> Dirs;
1895 (InstallDir + "/../sysroot" + M.osSuffix() + "/usr/include").str());
1900 // Check for Code Sourcery toolchain multilibs
1901 MultilibSet CSMipsMultilibs;
1903 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1905 auto MArchMicroMips =
1906 makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1908 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1910 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1912 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1914 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1917 makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1919 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1921 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1923 // Note that this one's osSuffix is ""
1924 auto MAbi64 = makeMultilib("")
1926 .includeSuffix("/64")
1933 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1935 .Either(SoftFloat, Nan2008, DefaultFloat)
1936 .FilterOut("/micromips/nan2008")
1937 .FilterOut("/mips16/nan2008")
1938 .Either(BigEndian, LittleEndian)
1940 .FilterOut("/mips16.*/64")
1941 .FilterOut("/micromips.*/64")
1942 .FilterOut(NonExistent)
1943 .setIncludeDirsCallback([](StringRef InstallDir,
1944 StringRef TripleStr, const Multilib &M) {
1945 std::vector<std::string> Dirs;
1946 Dirs.push_back((InstallDir + "/include").str());
1947 std::string SysRootInc =
1948 InstallDir.str() + "/../../../../" + TripleStr.str();
1949 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1950 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1952 Dirs.push_back(SysRootInc + "/libc/usr/include");
1957 MultilibSet AndroidMipsMultilibs =
1959 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1960 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1961 .FilterOut(NonExistent);
1963 MultilibSet DebianMipsMultilibs;
1966 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1968 Multilib M64 = Multilib()
1970 .includeSuffix("/64")
1975 Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1977 DebianMipsMultilibs =
1978 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1981 MultilibSet ImgMultilibs;
1983 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1985 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1988 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1994 .Maybe(LittleEndian)
1995 .FilterOut(NonExistent)
1996 .setIncludeDirsCallback([](StringRef InstallDir,
1997 StringRef TripleStr, const Multilib &M) {
1998 std::vector<std::string> Dirs;
1999 Dirs.push_back((InstallDir + "/include").str());
2001 (InstallDir + "/../../../../sysroot/usr/include").str());
2008 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2010 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2012 Multilib::flags_list Flags;
2013 addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2014 addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2015 addMultilibFlag(isMips16(Args), "mips16", Flags);
2016 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2017 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2018 CPUName == "mips32r5" || CPUName == "p5600",
2019 "march=mips32r2", Flags);
2020 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2021 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2022 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2023 CPUName == "mips64r5" || CPUName == "octeon",
2024 "march=mips64r2", Flags);
2025 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2026 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2027 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2029 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2030 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2031 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2032 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2033 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2034 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2036 if (TargetTriple.isAndroid()) {
2037 // Select Android toolchain. It's the only choice in that case.
2038 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2039 Result.Multilibs = AndroidMipsMultilibs;
2045 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2046 TargetTriple.getOS() == llvm::Triple::Linux &&
2047 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) {
2048 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2049 Result.Multilibs = MuslMipsMultilibs;
2055 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2056 TargetTriple.getOS() == llvm::Triple::Linux &&
2057 TargetTriple.getEnvironment() == llvm::Triple::GNU) {
2058 // Select mips-img-linux-gnu toolchain.
2059 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
2060 Result.Multilibs = ImgMultilibs;
2066 // Sort candidates. Toolchain that best meets the directories goes first.
2067 // Then select the first toolchains matches command line flags.
2068 MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
2071 std::begin(candidates), std::end(candidates),
2072 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
2073 for (const auto &candidate : candidates) {
2074 if (candidate->select(Flags, Result.SelectedMultilib)) {
2075 if (candidate == &DebianMipsMultilibs)
2076 Result.BiarchSibling = Multilib();
2077 Result.Multilibs = *candidate;
2083 // Fallback to the regular toolchain-tree structure.
2085 Result.Multilibs.push_back(Default);
2086 Result.Multilibs.FilterOut(NonExistent);
2088 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2089 Result.BiarchSibling = Multilib();
2097 static bool findBiarchMultilibs(const Driver &D,
2098 const llvm::Triple &TargetTriple,
2099 StringRef Path, const ArgList &Args,
2100 bool NeedsBiarchSuffix,
2101 DetectedMultilibs &Result) {
2102 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2103 // in what would normally be GCCInstallPath and put the 64-bit
2104 // libs in a subdirectory named 64. The simple logic we follow is that
2105 // *if* there is a subdirectory of the right name with crtbegin.o in it,
2106 // we use that. If not, and if not a biarch triple alias, we look for
2107 // crtbegin.o without the subdirectory.
2110 Multilib Alt64 = Multilib()
2112 .includeSuffix("/64")
2116 Multilib Alt32 = Multilib()
2118 .includeSuffix("/32")
2122 Multilib Altx32 = Multilib()
2124 .includeSuffix("/x32")
2129 FilterNonExistent NonExistent(Path, D.getVFS());
2131 // Determine default multilib from: 32, 64, x32
2132 // Also handle cases such as 64 on 32, 32 on 64, etc.
2133 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2134 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2135 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2137 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2139 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2142 if (TargetTriple.isArch32Bit())
2143 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2145 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2147 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2151 Default.flag("+m32").flag("-m64").flag("-mx32");
2152 else if (Want == WANT64)
2153 Default.flag("-m32").flag("+m64").flag("-mx32");
2154 else if (Want == WANTX32)
2155 Default.flag("-m32").flag("-m64").flag("+mx32");
2159 Result.Multilibs.push_back(Default);
2160 Result.Multilibs.push_back(Alt64);
2161 Result.Multilibs.push_back(Alt32);
2162 Result.Multilibs.push_back(Altx32);
2164 Result.Multilibs.FilterOut(NonExistent);
2166 Multilib::flags_list Flags;
2167 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2168 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2169 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2171 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2174 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2175 Result.SelectedMultilib == Altx32)
2176 Result.BiarchSibling = Default;
2181 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2182 const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2183 const std::string &LibDir, StringRef CandidateTriple,
2184 bool NeedsBiarchSuffix) {
2185 // Solaris is a special case. The GCC installation is under
2186 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2187 // need to iterate twice.
2189 for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2190 !EC && LI != LE; LI = LI.increment(EC)) {
2191 StringRef VersionText = llvm::sys::path::filename(LI->getName());
2192 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2194 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2195 if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2196 continue; // Saw this path before; no need to look at it again.
2197 if (CandidateVersion.isOlderThan(4, 1, 1))
2199 if (CandidateVersion <= Version)
2203 LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2204 if (!D.getVFS().exists(GCCInstallPath))
2207 // If we make it here there has to be at least one GCC version, let's just
2208 // use the latest one.
2209 std::error_code EEC;
2210 for (vfs::directory_iterator
2211 LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2213 !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2215 StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2216 GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2218 if (CandidateSubVersion > Version)
2219 Version = CandidateSubVersion;
2222 GCCTriple.setTriple(CandidateTriple);
2224 GCCInstallPath += "/" + Version.Text;
2225 GCCParentLibPath = GCCInstallPath + "/../../../../";
2231 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2232 const llvm::Triple &TargetTriple, const ArgList &Args,
2233 const std::string &LibDir, StringRef CandidateTriple,
2234 bool NeedsBiarchSuffix) {
2235 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2236 // There are various different suffixes involving the triple we
2237 // check for. We also record what is necessary to walk from each back
2238 // up to the lib directory. Specifically, the number of "up" steps
2239 // in the second half of each row is 1 + the number of path separators
2240 // in the first half.
2241 const std::string LibAndInstallSuffixes[][2] = {
2242 {"/gcc/" + CandidateTriple.str(), "/../../.."},
2244 // Debian puts cross-compilers in gcc-cross
2245 {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2247 {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2250 // The Freescale PPC SDK has the gcc libraries in
2251 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2252 {"/" + CandidateTriple.str(), "/../.."},
2254 // Ubuntu has a strange mis-matched pair of triples that this happens to
2256 // FIXME: It may be worthwhile to generalize this and look for a second
2258 {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2260 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2261 scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2266 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2267 const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2268 (TargetArch != llvm::Triple::x86));
2269 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2270 StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2272 for (vfs::directory_iterator
2273 LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2275 !EC && LI != LE; LI = LI.increment(EC)) {
2276 StringRef VersionText = llvm::sys::path::filename(LI->getName());
2277 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2278 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2279 if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2280 continue; // Saw this path before; no need to look at it again.
2281 if (CandidateVersion.isOlderThan(4, 1, 1))
2283 if (CandidateVersion <= Version)
2286 DetectedMultilibs Detected;
2288 // Debian mips multilibs behave more like the rest of the biarch ones,
2289 // so handle them there
2290 if (isMipsArch(TargetArch)) {
2291 if (!findMIPSMultilibs(D, TargetTriple, LI->getName(), Args, Detected))
2293 } else if (!findBiarchMultilibs(D, TargetTriple, LI->getName(), Args,
2294 NeedsBiarchSuffix, Detected)) {
2298 Multilibs = Detected.Multilibs;
2299 SelectedMultilib = Detected.SelectedMultilib;
2300 BiarchSibling = Detected.BiarchSibling;
2301 Version = CandidateVersion;
2302 GCCTriple.setTriple(CandidateTriple);
2303 // FIXME: We hack together the directory name here instead of
2304 // using LI to ensure stable path separators across Windows and
2307 LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2308 GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2314 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2315 const ArgList &Args)
2316 : ToolChain(D, Triple, Args), GCCInstallation(D), CudaInstallation(D) {
2317 getProgramPaths().push_back(getDriver().getInstalledDir());
2318 if (getDriver().getInstalledDir() != getDriver().Dir)
2319 getProgramPaths().push_back(getDriver().Dir);
2322 Generic_GCC::~Generic_GCC() {}
2324 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2326 case Action::PreprocessJobClass:
2328 Preprocess.reset(new tools::gcc::Preprocessor(*this));
2329 return Preprocess.get();
2330 case Action::CompileJobClass:
2332 Compile.reset(new tools::gcc::Compiler(*this));
2333 return Compile.get();
2335 return ToolChain::getTool(AC);
2339 Tool *Generic_GCC::buildAssembler() const {
2340 return new tools::gnutools::Assembler(*this);
2343 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2345 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2346 // Print the information about how we detected the GCC installation.
2347 GCCInstallation.print(OS);
2348 CudaInstallation.print(OS);
2351 bool Generic_GCC::IsUnwindTablesDefault() const {
2352 return getArch() == llvm::Triple::x86_64;
2355 bool Generic_GCC::isPICDefault() const {
2356 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2359 bool Generic_GCC::isPIEDefault() const { return false; }
2361 bool Generic_GCC::isPICDefaultForced() const {
2362 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2365 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2366 switch (getTriple().getArch()) {
2367 case llvm::Triple::x86:
2368 case llvm::Triple::x86_64:
2369 case llvm::Triple::aarch64:
2370 case llvm::Triple::aarch64_be:
2371 case llvm::Triple::arm:
2372 case llvm::Triple::armeb:
2373 case llvm::Triple::bpfel:
2374 case llvm::Triple::bpfeb:
2375 case llvm::Triple::thumb:
2376 case llvm::Triple::thumbeb:
2377 case llvm::Triple::ppc:
2378 case llvm::Triple::ppc64:
2379 case llvm::Triple::ppc64le:
2380 case llvm::Triple::systemz:
2387 /// \brief Helper to add the variant paths of a libstdc++ installation.
2388 bool Generic_GCC::addLibStdCXXIncludePaths(
2389 Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2390 StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2391 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2392 if (!getVFS().exists(Base + Suffix))
2395 addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2397 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2398 // that path exists or we have neither a GCC nor target multiarch triple, use
2399 // this vanilla search path.
2400 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2401 getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2402 addSystemInclude(DriverArgs, CC1Args,
2403 Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2405 // Otherwise try to use multiarch naming schemes which have normalized the
2406 // triples and put the triple before the suffix.
2408 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2409 // the target triple, so we support that here.
2410 addSystemInclude(DriverArgs, CC1Args,
2411 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2412 addSystemInclude(DriverArgs, CC1Args,
2413 Base + "/" + TargetMultiarchTriple + Suffix);
2416 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2421 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2422 ArgStringList &CC1Args) const {
2423 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2424 bool UseInitArrayDefault =
2425 getTriple().getArch() == llvm::Triple::aarch64 ||
2426 getTriple().getArch() == llvm::Triple::aarch64_be ||
2427 (getTriple().getOS() == llvm::Triple::Linux &&
2428 (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
2429 getTriple().getOS() == llvm::Triple::NaCl ||
2430 (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
2431 !getTriple().hasEnvironment());
2433 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2434 options::OPT_fno_use_init_array, UseInitArrayDefault))
2435 CC1Args.push_back("-fuse-init-array");
2439 MipsLLVMToolChain::MipsLLVMToolChain(const Driver &D,
2440 const llvm::Triple &Triple,
2441 const ArgList &Args)
2442 : Linux(D, Triple, Args) {
2443 // Select the correct multilib according to the given arguments.
2444 DetectedMultilibs Result;
2445 findMIPSMultilibs(D, Triple, "", Args, Result);
2446 Multilibs = Result.Multilibs;
2447 SelectedMultilib = Result.SelectedMultilib;
2449 // Find out the library suffix based on the ABI.
2450 LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
2451 getFilePaths().clear();
2452 getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
2454 // Use LLD by default.
2455 DefaultLinker = "lld";
2458 void MipsLLVMToolChain::AddClangSystemIncludeArgs(
2459 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2460 if (DriverArgs.hasArg(options::OPT_nostdinc))
2463 const Driver &D = getDriver();
2465 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2466 SmallString<128> P(D.ResourceDir);
2467 llvm::sys::path::append(P, "include");
2468 addSystemInclude(DriverArgs, CC1Args, P);
2471 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2474 const auto &Callback = Multilibs.includeDirsCallback();
2476 const auto IncludePaths =
2477 Callback(D.getInstalledDir(), getTripleString(), SelectedMultilib);
2478 for (const auto &Path : IncludePaths)
2479 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
2483 Tool *MipsLLVMToolChain::buildLinker() const {
2484 return new tools::gnutools::Linker(*this);
2487 std::string MipsLLVMToolChain::computeSysRoot() const {
2488 if (!getDriver().SysRoot.empty())
2489 return getDriver().SysRoot + SelectedMultilib.osSuffix();
2491 const std::string InstalledDir(getDriver().getInstalledDir());
2492 std::string SysRootPath =
2493 InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
2494 if (llvm::sys::fs::exists(SysRootPath))
2497 return std::string();
2500 ToolChain::CXXStdlibType
2501 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
2502 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2504 StringRef Value = A->getValue();
2505 if (Value != "libc++")
2506 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2507 << A->getAsString(Args);
2510 return ToolChain::CST_Libcxx;
2513 void MipsLLVMToolChain::AddClangCXXStdlibIncludeArgs(
2514 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2515 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2516 DriverArgs.hasArg(options::OPT_nostdincxx))
2519 assert((GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) &&
2520 "Only -lc++ (aka libcxx) is suported in this toolchain.");
2522 const auto &Callback = Multilibs.includeDirsCallback();
2524 const auto IncludePaths = Callback(getDriver().getInstalledDir(),
2525 getTripleString(), SelectedMultilib);
2526 for (const auto &Path : IncludePaths) {
2527 if (llvm::sys::fs::exists(Path + "/c++/v1")) {
2528 addSystemInclude(DriverArgs, CC1Args, Path + "/c++/v1");
2535 void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
2536 ArgStringList &CmdArgs) const {
2537 assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
2538 "Only -lc++ (aka libxx) is suported in this toolchain.");
2540 CmdArgs.push_back("-lc++");
2541 CmdArgs.push_back("-lc++abi");
2542 CmdArgs.push_back("-lunwind");
2545 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
2546 StringRef Component,
2547 bool Shared) const {
2548 SmallString<128> Path(getDriver().ResourceDir);
2549 llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
2551 llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
2552 "mips" + (Shared ? ".so" : ".a")));
2556 /// Hexagon Toolchain
2558 std::string HexagonToolChain::getHexagonTargetDir(
2559 const std::string &InstalledDir,
2560 const SmallVectorImpl<std::string> &PrefixDirs) const {
2561 std::string InstallRelDir;
2562 const Driver &D = getDriver();
2564 // Locate the rest of the toolchain ...
2565 for (auto &I : PrefixDirs)
2566 if (D.getVFS().exists(I))
2569 if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
2570 return InstallRelDir;
2572 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/target";
2573 if (getVFS().exists(PrefixRelDir))
2574 return PrefixRelDir;
2576 return InstallRelDir;
2580 Optional<unsigned> HexagonToolChain::getSmallDataThreshold(
2581 const ArgList &Args) {
2583 if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
2584 options::OPT_msmall_data_threshold_EQ)) {
2586 } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2587 options::OPT_fPIC)) {
2592 if (!Gn.getAsInteger(10, G))
2599 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
2600 ToolChain::path_list &LibPaths) const {
2601 const Driver &D = getDriver();
2603 //----------------------------------------------------------------------------
2605 //----------------------------------------------------------------------------
2606 for (Arg *A : Args.filtered(options::OPT_L))
2607 for (const char *Value : A->getValues())
2608 LibPaths.push_back(Value);
2610 //----------------------------------------------------------------------------
2611 // Other standard paths
2612 //----------------------------------------------------------------------------
2613 std::vector<std::string> RootDirs;
2614 std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
2615 std::back_inserter(RootDirs));
2617 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2619 if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
2620 RootDirs.push_back(TargetDir);
2622 bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
2623 // Assume G0 with -shared.
2624 bool HasG0 = Args.hasArg(options::OPT_shared);
2625 if (auto G = getSmallDataThreshold(Args))
2626 HasG0 = G.getValue() == 0;
2628 const std::string CpuVer = GetTargetCPUVersion(Args).str();
2629 for (auto &Dir : RootDirs) {
2630 std::string LibDir = Dir + "/hexagon/lib";
2631 std::string LibDirCpu = LibDir + '/' + CpuVer;
2634 LibPaths.push_back(LibDirCpu + "/G0/pic");
2635 LibPaths.push_back(LibDirCpu + "/G0");
2637 LibPaths.push_back(LibDirCpu);
2638 LibPaths.push_back(LibDir);
2642 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
2643 const llvm::opt::ArgList &Args)
2644 : Linux(D, Triple, Args) {
2645 const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2648 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2650 const std::string BinDir(TargetDir + "/bin");
2651 if (D.getVFS().exists(BinDir))
2652 getProgramPaths().push_back(BinDir);
2654 ToolChain::path_list &LibPaths = getFilePaths();
2656 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2657 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2658 // support 'linux' we'll need to fix this up
2660 getHexagonLibraryPaths(Args, LibPaths);
2663 HexagonToolChain::~HexagonToolChain() {}
2665 Tool *HexagonToolChain::buildAssembler() const {
2666 return new tools::hexagon::Assembler(*this);
2669 Tool *HexagonToolChain::buildLinker() const {
2670 return new tools::hexagon::Linker(*this);
2673 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2674 ArgStringList &CC1Args) const {
2675 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2676 DriverArgs.hasArg(options::OPT_nostdlibinc))
2679 const Driver &D = getDriver();
2680 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2682 addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
2685 void HexagonToolChain::AddClangCXXStdlibIncludeArgs(
2686 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2687 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2688 DriverArgs.hasArg(options::OPT_nostdincxx))
2691 const Driver &D = getDriver();
2692 std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
2693 addSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include/c++");
2696 ToolChain::CXXStdlibType
2697 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
2698 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2700 return ToolChain::CST_Libstdcxx;
2702 StringRef Value = A->getValue();
2703 if (Value != "libstdc++")
2704 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2706 return ToolChain::CST_Libstdcxx;
2710 // Returns the default CPU for Hexagon. This is the default compilation target
2711 // if no Hexagon processor is selected at the command-line.
2713 const StringRef HexagonToolChain::GetDefaultCPU() {
2714 return "hexagonv60";
2717 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
2718 Arg *CpuArg = nullptr;
2719 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ, options::OPT_march_EQ))
2722 StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
2723 if (CPU.startswith("hexagon"))
2724 return CPU.substr(sizeof("hexagon") - 1);
2729 /// AMDGPU Toolchain
2730 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
2731 const ArgList &Args)
2732 : Generic_ELF(D, Triple, Args) { }
2734 Tool *AMDGPUToolChain::buildLinker() const {
2735 return new tools::amdgpu::Linker(*this);
2740 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
2741 const ArgList &Args)
2742 : Generic_ELF(D, Triple, Args) {
2744 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
2745 // default paths, and must instead only use the paths provided
2746 // with this toolchain based on architecture.
2747 path_list &file_paths = getFilePaths();
2748 path_list &prog_paths = getProgramPaths();
2753 // Path for library files (libc.a, ...)
2754 std::string FilePath(getDriver().Dir + "/../");
2756 // Path for tools (clang, ld, etc..)
2757 std::string ProgPath(getDriver().Dir + "/../");
2759 // Path for toolchain libraries (libgcc.a, ...)
2760 std::string ToolPath(getDriver().ResourceDir + "/lib/");
2762 switch (Triple.getArch()) {
2763 case llvm::Triple::x86:
2764 file_paths.push_back(FilePath + "x86_64-nacl/lib32");
2765 file_paths.push_back(FilePath + "i686-nacl/usr/lib");
2766 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2767 file_paths.push_back(ToolPath + "i686-nacl");
2769 case llvm::Triple::x86_64:
2770 file_paths.push_back(FilePath + "x86_64-nacl/lib");
2771 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
2772 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2773 file_paths.push_back(ToolPath + "x86_64-nacl");
2775 case llvm::Triple::arm:
2776 file_paths.push_back(FilePath + "arm-nacl/lib");
2777 file_paths.push_back(FilePath + "arm-nacl/usr/lib");
2778 prog_paths.push_back(ProgPath + "arm-nacl/bin");
2779 file_paths.push_back(ToolPath + "arm-nacl");
2781 case llvm::Triple::mipsel:
2782 file_paths.push_back(FilePath + "mipsel-nacl/lib");
2783 file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
2784 prog_paths.push_back(ProgPath + "bin");
2785 file_paths.push_back(ToolPath + "mipsel-nacl");
2791 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
2794 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2795 ArgStringList &CC1Args) const {
2796 const Driver &D = getDriver();
2797 if (DriverArgs.hasArg(options::OPT_nostdinc))
2800 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2801 SmallString<128> P(D.ResourceDir);
2802 llvm::sys::path::append(P, "include");
2803 addSystemInclude(DriverArgs, CC1Args, P.str());
2806 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2809 SmallString<128> P(D.Dir + "/../");
2810 switch (getTriple().getArch()) {
2811 case llvm::Triple::x86:
2812 // x86 is special because multilib style uses x86_64-nacl/include for libc
2813 // headers but the SDK wants i686-nacl/usr/include. The other architectures
2814 // have the same substring.
2815 llvm::sys::path::append(P, "i686-nacl/usr/include");
2816 addSystemInclude(DriverArgs, CC1Args, P.str());
2817 llvm::sys::path::remove_filename(P);
2818 llvm::sys::path::remove_filename(P);
2819 llvm::sys::path::remove_filename(P);
2820 llvm::sys::path::append(P, "x86_64-nacl/include");
2821 addSystemInclude(DriverArgs, CC1Args, P.str());
2823 case llvm::Triple::arm:
2824 llvm::sys::path::append(P, "arm-nacl/usr/include");
2826 case llvm::Triple::x86_64:
2827 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2829 case llvm::Triple::mipsel:
2830 llvm::sys::path::append(P, "mipsel-nacl/usr/include");
2836 addSystemInclude(DriverArgs, CC1Args, P.str());
2837 llvm::sys::path::remove_filename(P);
2838 llvm::sys::path::remove_filename(P);
2839 llvm::sys::path::append(P, "include");
2840 addSystemInclude(DriverArgs, CC1Args, P.str());
2843 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
2844 ArgStringList &CmdArgs) const {
2845 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2846 // if the value is libc++, and emits an error for other values.
2847 GetCXXStdlibType(Args);
2848 CmdArgs.push_back("-lc++");
2851 void NaClToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2852 ArgStringList &CC1Args) const {
2853 const Driver &D = getDriver();
2854 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2855 DriverArgs.hasArg(options::OPT_nostdincxx))
2858 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2859 // if the value is libc++, and emits an error for other values.
2860 GetCXXStdlibType(DriverArgs);
2862 SmallString<128> P(D.Dir + "/../");
2863 switch (getTriple().getArch()) {
2864 case llvm::Triple::arm:
2865 llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
2866 addSystemInclude(DriverArgs, CC1Args, P.str());
2868 case llvm::Triple::x86:
2869 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2870 addSystemInclude(DriverArgs, CC1Args, P.str());
2872 case llvm::Triple::x86_64:
2873 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2874 addSystemInclude(DriverArgs, CC1Args, P.str());
2876 case llvm::Triple::mipsel:
2877 llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
2878 addSystemInclude(DriverArgs, CC1Args, P.str());
2885 ToolChain::CXXStdlibType
2886 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
2887 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2888 StringRef Value = A->getValue();
2889 if (Value == "libc++")
2890 return ToolChain::CST_Libcxx;
2891 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2894 return ToolChain::CST_Libcxx;
2898 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
2899 types::ID InputType) const {
2900 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
2901 if (TheTriple.getArch() == llvm::Triple::arm &&
2902 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2903 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
2904 return TheTriple.getTriple();
2907 Tool *NaClToolChain::buildLinker() const {
2908 return new tools::nacltools::Linker(*this);
2911 Tool *NaClToolChain::buildAssembler() const {
2912 if (getTriple().getArch() == llvm::Triple::arm)
2913 return new tools::nacltools::AssemblerARM(*this);
2914 return new tools::gnutools::Assembler(*this);
2918 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2919 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2920 /// Currently does not support anything else but compilation.
2922 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
2923 const ArgList &Args)
2924 : ToolChain(D, Triple, Args) {
2925 // Path mangling to find libexec
2926 std::string Path(getDriver().Dir);
2928 Path += "/../libexec";
2929 getProgramPaths().push_back(Path);
2932 TCEToolChain::~TCEToolChain() {}
2934 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
2936 bool TCEToolChain::isPICDefault() const { return false; }
2938 bool TCEToolChain::isPIEDefault() const { return false; }
2940 bool TCEToolChain::isPICDefaultForced() const { return false; }
2942 // CloudABI - CloudABI tool chain which can call ld(1) directly.
2944 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
2945 const ArgList &Args)
2946 : Generic_ELF(D, Triple, Args) {
2947 SmallString<128> P(getDriver().Dir);
2948 llvm::sys::path::append(P, "..", getTriple().str(), "lib");
2949 getFilePaths().push_back(P.str());
2952 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2953 ArgStringList &CC1Args) const {
2954 if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
2955 DriverArgs.hasArg(options::OPT_nostdincxx))
2958 SmallString<128> P(getDriver().Dir);
2959 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
2960 addSystemInclude(DriverArgs, CC1Args, P.str());
2963 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
2964 ArgStringList &CmdArgs) const {
2965 CmdArgs.push_back("-lc++");
2966 CmdArgs.push_back("-lc++abi");
2967 CmdArgs.push_back("-lunwind");
2970 Tool *CloudABI::buildLinker() const {
2971 return new tools::cloudabi::Linker(*this);
2974 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2976 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
2977 const ArgList &Args)
2978 : Generic_ELF(D, Triple, Args) {
2979 getFilePaths().push_back(getDriver().Dir + "/../lib");
2980 getFilePaths().push_back("/usr/lib");
2983 Tool *OpenBSD::buildAssembler() const {
2984 return new tools::openbsd::Assembler(*this);
2987 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
2989 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2991 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2992 : Generic_ELF(D, Triple, Args) {
2993 getFilePaths().push_back(getDriver().Dir + "/../lib");
2994 getFilePaths().push_back("/usr/lib");
2997 Tool *Bitrig::buildAssembler() const {
2998 return new tools::bitrig::Assembler(*this);
3001 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3003 ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const {
3004 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3005 StringRef Value = A->getValue();
3006 if (Value == "libstdc++")
3007 return ToolChain::CST_Libstdcxx;
3008 if (Value == "libc++")
3009 return ToolChain::CST_Libcxx;
3011 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3013 return ToolChain::CST_Libcxx;
3016 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3017 ArgStringList &CC1Args) const {
3018 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3019 DriverArgs.hasArg(options::OPT_nostdincxx))
3022 switch (GetCXXStdlibType(DriverArgs)) {
3023 case ToolChain::CST_Libcxx:
3024 addSystemInclude(DriverArgs, CC1Args,
3025 getDriver().SysRoot + "/usr/include/c++/v1");
3027 case ToolChain::CST_Libstdcxx:
3028 addSystemInclude(DriverArgs, CC1Args,
3029 getDriver().SysRoot + "/usr/include/c++/stdc++");
3030 addSystemInclude(DriverArgs, CC1Args,
3031 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
3033 StringRef Triple = getTriple().str();
3034 if (Triple.startswith("amd64"))
3035 addSystemInclude(DriverArgs, CC1Args,
3036 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
3039 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
3040 "/usr/include/c++/stdc++/" +
3046 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3047 ArgStringList &CmdArgs) const {
3048 switch (GetCXXStdlibType(Args)) {
3049 case ToolChain::CST_Libcxx:
3050 CmdArgs.push_back("-lc++");
3051 CmdArgs.push_back("-lc++abi");
3052 CmdArgs.push_back("-lpthread");
3054 case ToolChain::CST_Libstdcxx:
3055 CmdArgs.push_back("-lstdc++");
3060 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3062 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3063 const ArgList &Args)
3064 : Generic_ELF(D, Triple, Args) {
3066 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3067 // back to '/usr/lib' if it doesn't exist.
3068 if ((Triple.getArch() == llvm::Triple::x86 ||
3069 Triple.getArch() == llvm::Triple::ppc) &&
3070 D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3071 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3073 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3076 ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
3077 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3078 StringRef Value = A->getValue();
3079 if (Value == "libstdc++")
3080 return ToolChain::CST_Libstdcxx;
3081 if (Value == "libc++")
3082 return ToolChain::CST_Libcxx;
3084 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3086 if (getTriple().getOSMajorVersion() >= 10)
3087 return ToolChain::CST_Libcxx;
3088 return ToolChain::CST_Libstdcxx;
3091 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3092 ArgStringList &CC1Args) const {
3093 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3094 DriverArgs.hasArg(options::OPT_nostdincxx))
3097 switch (GetCXXStdlibType(DriverArgs)) {
3098 case ToolChain::CST_Libcxx:
3099 addSystemInclude(DriverArgs, CC1Args,
3100 getDriver().SysRoot + "/usr/include/c++/v1");
3102 case ToolChain::CST_Libstdcxx:
3103 addSystemInclude(DriverArgs, CC1Args,
3104 getDriver().SysRoot + "/usr/include/c++/4.2");
3105 addSystemInclude(DriverArgs, CC1Args,
3106 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
3111 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
3112 ArgStringList &CmdArgs) const {
3113 CXXStdlibType Type = GetCXXStdlibType(Args);
3114 bool Profiling = Args.hasArg(options::OPT_pg);
3117 case ToolChain::CST_Libcxx:
3118 CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
3121 case ToolChain::CST_Libstdcxx:
3122 CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++");
3127 Tool *FreeBSD::buildAssembler() const {
3128 return new tools::freebsd::Assembler(*this);
3131 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3133 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3134 // FreeBSD uses SjLj exceptions on ARM oabi.
3135 switch (getTriple().getEnvironment()) {
3136 case llvm::Triple::GNUEABIHF:
3137 case llvm::Triple::GNUEABI:
3138 case llvm::Triple::EABI:
3142 return (getTriple().getArch() == llvm::Triple::arm ||
3143 getTriple().getArch() == llvm::Triple::thumb);
3147 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3149 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3151 SanitizerMask FreeBSD::getSupportedSanitizers() const {
3152 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3153 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3154 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3155 getTriple().getArch() == llvm::Triple::mips64el;
3156 SanitizerMask Res = ToolChain::getSupportedSanitizers();
3157 Res |= SanitizerKind::Address;
3158 Res |= SanitizerKind::Vptr;
3159 if (IsX86_64 || IsMIPS64) {
3160 Res |= SanitizerKind::Leak;
3161 Res |= SanitizerKind::Thread;
3163 if (IsX86 || IsX86_64) {
3164 Res |= SanitizerKind::SafeStack;
3169 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3171 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3172 : Generic_ELF(D, Triple, Args) {
3174 if (getDriver().UseStdLib) {
3175 // When targeting a 32-bit platform, try the special directory used on
3176 // 64-bit hosts, and only fall back to the main library directory if that
3178 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3179 // what all logic is needed to emulate the '=' prefix here.
3180 switch (Triple.getArch()) {
3181 case llvm::Triple::x86:
3182 getFilePaths().push_back("=/usr/lib/i386");
3184 case llvm::Triple::arm:
3185 case llvm::Triple::armeb:
3186 case llvm::Triple::thumb:
3187 case llvm::Triple::thumbeb:
3188 switch (Triple.getEnvironment()) {
3189 case llvm::Triple::EABI:
3190 case llvm::Triple::GNUEABI:
3191 getFilePaths().push_back("=/usr/lib/eabi");
3193 case llvm::Triple::EABIHF:
3194 case llvm::Triple::GNUEABIHF:
3195 getFilePaths().push_back("=/usr/lib/eabihf");
3198 getFilePaths().push_back("=/usr/lib/oabi");
3202 case llvm::Triple::mips64:
3203 case llvm::Triple::mips64el:
3204 if (tools::mips::hasMipsAbiArg(Args, "o32"))
3205 getFilePaths().push_back("=/usr/lib/o32");
3206 else if (tools::mips::hasMipsAbiArg(Args, "64"))
3207 getFilePaths().push_back("=/usr/lib/64");
3209 case llvm::Triple::ppc:
3210 getFilePaths().push_back("=/usr/lib/powerpc");
3212 case llvm::Triple::sparc:
3213 getFilePaths().push_back("=/usr/lib/sparc");
3219 getFilePaths().push_back("=/usr/lib");
3223 Tool *NetBSD::buildAssembler() const {
3224 return new tools::netbsd::Assembler(*this);
3227 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3229 ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const {
3230 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3231 StringRef Value = A->getValue();
3232 if (Value == "libstdc++")
3233 return ToolChain::CST_Libstdcxx;
3234 if (Value == "libc++")
3235 return ToolChain::CST_Libcxx;
3237 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3240 unsigned Major, Minor, Micro;
3241 getTriple().getOSVersion(Major, Minor, Micro);
3242 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
3243 switch (getArch()) {
3244 case llvm::Triple::aarch64:
3245 case llvm::Triple::arm:
3246 case llvm::Triple::armeb:
3247 case llvm::Triple::thumb:
3248 case llvm::Triple::thumbeb:
3249 case llvm::Triple::ppc:
3250 case llvm::Triple::ppc64:
3251 case llvm::Triple::ppc64le:
3252 case llvm::Triple::sparc:
3253 case llvm::Triple::sparcv9:
3254 case llvm::Triple::x86:
3255 case llvm::Triple::x86_64:
3256 return ToolChain::CST_Libcxx;
3261 return ToolChain::CST_Libstdcxx;
3264 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3265 ArgStringList &CC1Args) const {
3266 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3267 DriverArgs.hasArg(options::OPT_nostdincxx))
3270 switch (GetCXXStdlibType(DriverArgs)) {
3271 case ToolChain::CST_Libcxx:
3272 addSystemInclude(DriverArgs, CC1Args,
3273 getDriver().SysRoot + "/usr/include/c++/");
3275 case ToolChain::CST_Libstdcxx:
3276 addSystemInclude(DriverArgs, CC1Args,
3277 getDriver().SysRoot + "/usr/include/g++");
3278 addSystemInclude(DriverArgs, CC1Args,
3279 getDriver().SysRoot + "/usr/include/g++/backward");
3284 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3286 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3287 : Generic_ELF(D, Triple, Args) {
3288 getFilePaths().push_back(getDriver().Dir + "/../lib");
3289 getFilePaths().push_back("/usr/lib");
3292 Tool *Minix::buildAssembler() const {
3293 return new tools::minix::Assembler(*this);
3296 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3298 static void addPathIfExists(const Driver &D, const Twine &Path,
3299 ToolChain::path_list &Paths) {
3300 if (D.getVFS().exists(Path))
3301 Paths.push_back(Path.str());
3304 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3306 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3307 const ArgList &Args)
3308 : Generic_GCC(D, Triple, Args) {
3310 GCCInstallation.init(Triple, Args);
3312 path_list &Paths = getFilePaths();
3313 if (GCCInstallation.isValid())
3314 addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
3316 addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3317 if (getDriver().getInstalledDir() != getDriver().Dir)
3318 addPathIfExists(D, getDriver().Dir, Paths);
3320 addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3322 std::string LibPath = "/usr/lib/";
3323 switch (Triple.getArch()) {
3324 case llvm::Triple::x86:
3325 case llvm::Triple::sparc:
3327 case llvm::Triple::x86_64:
3328 LibPath += "amd64/";
3330 case llvm::Triple::sparcv9:
3331 LibPath += "sparcv9/";
3334 llvm_unreachable("Unsupported architecture");
3337 addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3340 Tool *Solaris::buildAssembler() const {
3341 return new tools::solaris::Assembler(*this);
3344 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3346 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3347 ArgStringList &CC1Args) const {
3348 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3349 DriverArgs.hasArg(options::OPT_nostdincxx))
3352 // Include the support directory for things like xlocale and fudged system
3354 addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3356 if (GCCInstallation.isValid()) {
3357 GCCVersion Version = GCCInstallation.getVersion();
3358 addSystemInclude(DriverArgs, CC1Args,
3359 getDriver().SysRoot + "/usr/gcc/" +
3360 Version.MajorStr + "." +
3362 "/include/c++/" + Version.Text);
3363 addSystemInclude(DriverArgs, CC1Args,
3364 getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3365 "." + Version.MinorStr + "/include/c++/" +
3366 Version.Text + "/" +
3367 GCCInstallation.getTriple().str());
3371 /// Distribution (very bare-bones at the moment).
3374 // NB: Releases of a particular Linux distro should be kept together
3375 // in this enum, because some tests are done by integer comparison against
3376 // the first and last known member in the family, e.g. IsRedHat().
3410 static bool IsRedhat(enum Distro Distro) {
3411 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
3414 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
3416 static bool IsDebian(enum Distro Distro) {
3417 return Distro >= DebianLenny && Distro <= DebianStretch;
3420 static bool IsUbuntu(enum Distro Distro) {
3421 return Distro >= UbuntuHardy && Distro <= UbuntuXenial;
3424 static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch) {
3425 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
3426 llvm::MemoryBuffer::getFile("/etc/lsb-release");
3428 StringRef Data = File.get()->getBuffer();
3429 SmallVector<StringRef, 16> Lines;
3430 Data.split(Lines, "\n");
3431 Distro Version = UnknownDistro;
3432 for (StringRef Line : Lines)
3433 if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
3434 Version = llvm::StringSwitch<Distro>(Line.substr(17))
3435 .Case("hardy", UbuntuHardy)
3436 .Case("intrepid", UbuntuIntrepid)
3437 .Case("jaunty", UbuntuJaunty)
3438 .Case("karmic", UbuntuKarmic)
3439 .Case("lucid", UbuntuLucid)
3440 .Case("maverick", UbuntuMaverick)
3441 .Case("natty", UbuntuNatty)
3442 .Case("oneiric", UbuntuOneiric)
3443 .Case("precise", UbuntuPrecise)
3444 .Case("quantal", UbuntuQuantal)
3445 .Case("raring", UbuntuRaring)
3446 .Case("saucy", UbuntuSaucy)
3447 .Case("trusty", UbuntuTrusty)
3448 .Case("utopic", UbuntuUtopic)
3449 .Case("vivid", UbuntuVivid)
3450 .Case("wily", UbuntuWily)
3451 .Case("xenial", UbuntuXenial)
3452 .Default(UnknownDistro);
3456 File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
3458 StringRef Data = File.get()->getBuffer();
3459 if (Data.startswith("Fedora release"))
3461 if (Data.startswith("Red Hat Enterprise Linux") ||
3462 Data.startswith("CentOS")) {
3463 if (Data.find("release 7") != StringRef::npos)
3465 else if (Data.find("release 6") != StringRef::npos)
3467 else if (Data.find("release 5") != StringRef::npos)
3469 else if (Data.find("release 4") != StringRef::npos)
3472 return UnknownDistro;
3475 File = llvm::MemoryBuffer::getFile("/etc/debian_version");
3477 StringRef Data = File.get()->getBuffer();
3480 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
3481 return DebianSqueeze;
3482 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
3483 return DebianWheezy;
3484 else if (Data.startswith("jessie/sid") || Data[0] == '8')
3485 return DebianJessie;
3486 else if (Data.startswith("stretch/sid") || Data[0] == '9')
3487 return DebianStretch;
3488 return UnknownDistro;
3491 if (D.getVFS().exists("/etc/SuSE-release"))
3494 if (D.getVFS().exists("/etc/exherbo-release"))
3497 if (D.getVFS().exists("/etc/arch-release"))
3500 return UnknownDistro;
3503 /// \brief Get our best guess at the multiarch triple for a target.
3505 /// Debian-based systems are starting to use a multiarch setup where they use
3506 /// a target-triple directory in the library and header search paths.
3507 /// Unfortunately, this triple does not align with the vanilla target triple,
3508 /// so we provide a rough mapping here.
3509 static std::string getMultiarchTriple(const Driver &D,
3510 const llvm::Triple &TargetTriple,
3511 StringRef SysRoot) {
3512 llvm::Triple::EnvironmentType TargetEnvironment =
3513 TargetTriple.getEnvironment();
3515 // For most architectures, just use whatever we have rather than trying to be
3517 switch (TargetTriple.getArch()) {
3521 // We use the existence of '/lib/<triple>' as a directory to detect some
3522 // common linux triples that don't quite match the Clang triple for both
3523 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3524 // regardless of what the actual target triple is.
3525 case llvm::Triple::arm:
3526 case llvm::Triple::thumb:
3527 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3528 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3529 return "arm-linux-gnueabihf";
3531 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3532 return "arm-linux-gnueabi";
3535 case llvm::Triple::armeb:
3536 case llvm::Triple::thumbeb:
3537 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3538 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3539 return "armeb-linux-gnueabihf";
3541 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3542 return "armeb-linux-gnueabi";
3545 case llvm::Triple::x86:
3546 if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3547 return "i386-linux-gnu";
3549 case llvm::Triple::x86_64:
3550 // We don't want this for x32, otherwise it will match x86_64 libs
3551 if (TargetEnvironment != llvm::Triple::GNUX32 &&
3552 D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3553 return "x86_64-linux-gnu";
3555 case llvm::Triple::aarch64:
3556 if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3557 return "aarch64-linux-gnu";
3559 case llvm::Triple::aarch64_be:
3560 if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3561 return "aarch64_be-linux-gnu";
3563 case llvm::Triple::mips:
3564 if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3565 return "mips-linux-gnu";
3567 case llvm::Triple::mipsel:
3568 if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
3569 return "mipsel-linux-gnu";
3571 case llvm::Triple::mips64:
3572 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
3573 return "mips64-linux-gnu";
3574 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3575 return "mips64-linux-gnuabi64";
3577 case llvm::Triple::mips64el:
3578 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
3579 return "mips64el-linux-gnu";
3580 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
3581 return "mips64el-linux-gnuabi64";
3583 case llvm::Triple::ppc:
3584 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
3585 return "powerpc-linux-gnuspe";
3586 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
3587 return "powerpc-linux-gnu";
3589 case llvm::Triple::ppc64:
3590 if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
3591 return "powerpc64-linux-gnu";
3593 case llvm::Triple::ppc64le:
3594 if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
3595 return "powerpc64le-linux-gnu";
3597 case llvm::Triple::sparc:
3598 if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
3599 return "sparc-linux-gnu";
3601 case llvm::Triple::sparcv9:
3602 if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
3603 return "sparc64-linux-gnu";
3605 case llvm::Triple::systemz:
3606 if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
3607 return "s390x-linux-gnu";
3610 return TargetTriple.str();
3613 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
3614 if (isMipsArch(Triple.getArch())) {
3615 // lib32 directory has a special meaning on MIPS targets.
3616 // It contains N32 ABI binaries. Use this folder if produce
3617 // code for N32 ABI only.
3618 if (tools::mips::hasMipsAbiArg(Args, "n32"))
3620 return Triple.isArch32Bit() ? "lib" : "lib64";
3623 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
3624 // using that variant while targeting other architectures causes problems
3625 // because the libraries are laid out in shared system roots that can't cope
3626 // with a 'lib32' library search path being considered. So we only enable
3627 // them when we know we may need it.
3629 // FIXME: This is a bit of a hack. We should really unify this code for
3630 // reasoning about oslibdir spellings with the lib dir spellings in the
3631 // GCCInstallationDetector, but that is a more significant refactoring.
3632 if (Triple.getArch() == llvm::Triple::x86 ||
3633 Triple.getArch() == llvm::Triple::ppc)
3636 if (Triple.getArch() == llvm::Triple::x86_64 &&
3637 Triple.getEnvironment() == llvm::Triple::GNUX32)
3640 return Triple.isArch32Bit() ? "lib" : "lib64";
3643 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3644 : Generic_ELF(D, Triple, Args) {
3645 GCCInstallation.init(Triple, Args);
3646 CudaInstallation.init(Triple, Args);
3647 Multilibs = GCCInstallation.getMultilibs();
3648 llvm::Triple::ArchType Arch = Triple.getArch();
3649 std::string SysRoot = computeSysRoot();
3651 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3652 // least) put various tools in a triple-prefixed directory off of the parent
3653 // of the GCC installation. We use the GCC triple here to ensure that we end
3654 // up with tools that support the same amount of cross compiling as the
3655 // detected GCC installation. For example, if we find a GCC installation
3656 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3657 // used to target i386.
3658 // FIXME: This seems unlikely to be Linux-specific.
3659 ToolChain::path_list &PPaths = getProgramPaths();
3660 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3661 GCCInstallation.getTriple().str() + "/bin")
3664 Distro Distro = DetectDistro(D, Arch);
3666 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
3667 ExtraOpts.push_back("-z");
3668 ExtraOpts.push_back("relro");
3671 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
3672 ExtraOpts.push_back("-X");
3674 const bool IsAndroid = Triple.isAndroid();
3675 const bool IsMips = isMipsArch(Arch);
3677 if (IsMips && !SysRoot.empty())
3678 ExtraOpts.push_back("--sysroot=" + SysRoot);
3680 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
3681 // and the MIPS ABI require .dynsym to be sorted in different ways.
3682 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
3683 // ABI requires a mapping between the GOT and the symbol table.
3684 // Android loader does not support .gnu.hash.
3685 if (!IsMips && !IsAndroid) {
3686 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
3687 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
3688 ExtraOpts.push_back("--hash-style=gnu");
3690 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
3691 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
3692 ExtraOpts.push_back("--hash-style=both");
3695 if (IsRedhat(Distro))
3696 ExtraOpts.push_back("--no-add-needed");
3698 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
3699 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
3700 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
3701 ExtraOpts.push_back("--build-id");
3703 if (IsOpenSUSE(Distro))
3704 ExtraOpts.push_back("--enable-new-dtags");
3706 // The selection of paths to try here is designed to match the patterns which
3707 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
3708 // This was determined by running GCC in a fake filesystem, creating all
3709 // possible permutations of these directories, and seeing which ones it added
3710 // to the link paths.
3711 path_list &Paths = getFilePaths();
3713 const std::string OSLibDir = getOSLibDir(Triple, Args);
3714 const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
3716 // Add the multilib suffixed paths where they are available.
3717 if (GCCInstallation.isValid()) {
3718 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3719 const std::string &LibPath = GCCInstallation.getParentLibPath();
3720 const Multilib &Multilib = GCCInstallation.getMultilib();
3722 // Sourcery CodeBench MIPS toolchain holds some libraries under
3723 // a biarch-like suffix of the GCC installation.
3724 addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
3727 // GCC cross compiling toolchains will install target libraries which ship
3728 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3729 // any part of the GCC installation in
3730 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3731 // debatable, but is the reality today. We need to search this tree even
3732 // when we have a sysroot somewhere else. It is the responsibility of
3733 // whomever is doing the cross build targeting a sysroot using a GCC
3734 // installation that is *not* within the system root to ensure two things:
3736 // 1) Any DSOs that are linked in from this tree or from the install path
3737 // above must be present on the system root and found via an
3738 // appropriate rpath.
3739 // 2) There must not be libraries installed into
3740 // <prefix>/<triple>/<libdir> unless they should be preferred over
3741 // those within the system root.
3743 // Note that this matches the GCC behavior. See the below comment for where
3744 // Clang diverges from GCC's behavior.
3745 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
3746 OSLibDir + Multilib.osSuffix(),
3749 // If the GCC installation we found is inside of the sysroot, we want to
3750 // prefer libraries installed in the parent prefix of the GCC installation.
3751 // It is important to *not* use these paths when the GCC installation is
3752 // outside of the system root as that can pick up unintended libraries.
3753 // This usually happens when there is an external cross compiler on the
3754 // host system, and a more minimal sysroot available that is the target of
3755 // the cross. Note that GCC does include some of these directories in some
3756 // configurations but this seems somewhere between questionable and simply
3758 if (StringRef(LibPath).startswith(SysRoot)) {
3759 addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
3760 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3764 // Similar to the logic for GCC above, if we currently running Clang inside
3765 // of the requested system root, add its parent library paths to
3767 // FIXME: It's not clear whether we should use the driver's installed
3768 // directory ('Dir' below) or the ResourceDir.
3769 if (StringRef(D.Dir).startswith(SysRoot)) {
3770 addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
3771 addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
3774 addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
3775 addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
3776 addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3777 addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3779 // Try walking via the GCC triple path in case of biarch or multiarch GCC
3780 // installations with strange symlinks.
3781 if (GCCInstallation.isValid()) {
3783 SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3784 "/../../" + OSLibDir,
3787 // Add the 'other' biarch variant path
3788 Multilib BiarchSibling;
3789 if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3790 addPathIfExists(D, GCCInstallation.getInstallPath() +
3791 BiarchSibling.gccSuffix(),
3795 // See comments above on the multilib variant for details of why this is
3796 // included even from outside the sysroot.
3797 const std::string &LibPath = GCCInstallation.getParentLibPath();
3798 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3799 const Multilib &Multilib = GCCInstallation.getMultilib();
3800 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
3801 Multilib.osSuffix(),
3804 // See comments above on the multilib variant for details of why this is
3805 // only included from within the sysroot.
3806 if (StringRef(LibPath).startswith(SysRoot))
3807 addPathIfExists(D, LibPath, Paths);
3810 // Similar to the logic for GCC above, if we are currently running Clang
3811 // inside of the requested system root, add its parent library path to those
3813 // FIXME: It's not clear whether we should use the driver's installed
3814 // directory ('Dir' below) or the ResourceDir.
3815 if (StringRef(D.Dir).startswith(SysRoot))
3816 addPathIfExists(D, D.Dir + "/../lib", Paths);
3818 addPathIfExists(D, SysRoot + "/lib", Paths);
3819 addPathIfExists(D, SysRoot + "/usr/lib", Paths);
3822 bool Linux::HasNativeLLVMSupport() const { return true; }
3824 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
3826 Tool *Linux::buildAssembler() const {
3827 return new tools::gnutools::Assembler(*this);
3830 std::string Linux::computeSysRoot() const {
3831 if (!getDriver().SysRoot.empty())
3832 return getDriver().SysRoot;
3834 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3835 return std::string();
3837 // Standalone MIPS toolchains use different names for sysroot folder
3838 // and put it into different places. Here we try to check some known
3841 const StringRef InstallDir = GCCInstallation.getInstallPath();
3842 const StringRef TripleStr = GCCInstallation.getTriple().str();
3843 const Multilib &Multilib = GCCInstallation.getMultilib();
3846 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
3849 if (getVFS().exists(Path))
3852 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3854 if (getVFS().exists(Path))
3857 return std::string();
3860 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3861 ArgStringList &CC1Args) const {
3862 const Driver &D = getDriver();
3863 std::string SysRoot = computeSysRoot();
3865 if (DriverArgs.hasArg(options::OPT_nostdinc))
3868 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3869 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3871 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3872 SmallString<128> P(D.ResourceDir);
3873 llvm::sys::path::append(P, "include");
3874 addSystemInclude(DriverArgs, CC1Args, P);
3877 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3880 // Check for configure-time C include directories.
3881 StringRef CIncludeDirs(C_INCLUDE_DIRS);
3882 if (CIncludeDirs != "") {
3883 SmallVector<StringRef, 5> dirs;
3884 CIncludeDirs.split(dirs, ":");
3885 for (StringRef dir : dirs) {
3887 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3888 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3893 // Lacking those, try to detect the correct set of system includes for the
3896 // Add include directories specific to the selected multilib set and multilib.
3897 if (GCCInstallation.isValid()) {
3898 const auto &Callback = Multilibs.includeDirsCallback();
3900 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3901 GCCInstallation.getTriple().str(),
3902 GCCInstallation.getMultilib());
3903 for (const auto &Path : IncludePaths)
3904 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3908 // Implement generic Debian multiarch support.
3909 const StringRef X86_64MultiarchIncludeDirs[] = {
3910 "/usr/include/x86_64-linux-gnu",
3912 // FIXME: These are older forms of multiarch. It's not clear that they're
3913 // in use in any released version of Debian, so we should consider
3915 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
3916 const StringRef X86MultiarchIncludeDirs[] = {
3917 "/usr/include/i386-linux-gnu",
3919 // FIXME: These are older forms of multiarch. It's not clear that they're
3920 // in use in any released version of Debian, so we should consider
3922 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3923 "/usr/include/i486-linux-gnu"};
3924 const StringRef AArch64MultiarchIncludeDirs[] = {
3925 "/usr/include/aarch64-linux-gnu"};
3926 const StringRef ARMMultiarchIncludeDirs[] = {
3927 "/usr/include/arm-linux-gnueabi"};
3928 const StringRef ARMHFMultiarchIncludeDirs[] = {
3929 "/usr/include/arm-linux-gnueabihf"};
3930 const StringRef ARMEBMultiarchIncludeDirs[] = {
3931 "/usr/include/armeb-linux-gnueabi"};
3932 const StringRef ARMEBHFMultiarchIncludeDirs[] = {
3933 "/usr/include/armeb-linux-gnueabihf"};
3934 const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
3935 const StringRef MIPSELMultiarchIncludeDirs[] = {
3936 "/usr/include/mipsel-linux-gnu"};
3937 const StringRef MIPS64MultiarchIncludeDirs[] = {
3938 "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
3939 const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3940 "/usr/include/mips64el-linux-gnu",
3941 "/usr/include/mips64el-linux-gnuabi64"};
3942 const StringRef PPCMultiarchIncludeDirs[] = {
3943 "/usr/include/powerpc-linux-gnu"};
3944 const StringRef PPC64MultiarchIncludeDirs[] = {
3945 "/usr/include/powerpc64-linux-gnu"};
3946 const StringRef PPC64LEMultiarchIncludeDirs[] = {
3947 "/usr/include/powerpc64le-linux-gnu"};
3948 const StringRef SparcMultiarchIncludeDirs[] = {
3949 "/usr/include/sparc-linux-gnu"};
3950 const StringRef Sparc64MultiarchIncludeDirs[] = {
3951 "/usr/include/sparc64-linux-gnu"};
3952 const StringRef SYSTEMZMultiarchIncludeDirs[] = {
3953 "/usr/include/s390x-linux-gnu"};
3954 ArrayRef<StringRef> MultiarchIncludeDirs;
3955 switch (getTriple().getArch()) {
3956 case llvm::Triple::x86_64:
3957 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3959 case llvm::Triple::x86:
3960 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3962 case llvm::Triple::aarch64:
3963 case llvm::Triple::aarch64_be:
3964 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3966 case llvm::Triple::arm:
3967 case llvm::Triple::thumb:
3968 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3969 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3971 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3973 case llvm::Triple::armeb:
3974 case llvm::Triple::thumbeb:
3975 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3976 MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
3978 MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
3980 case llvm::Triple::mips:
3981 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3983 case llvm::Triple::mipsel:
3984 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3986 case llvm::Triple::mips64:
3987 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3989 case llvm::Triple::mips64el:
3990 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3992 case llvm::Triple::ppc:
3993 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3995 case llvm::Triple::ppc64:
3996 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3998 case llvm::Triple::ppc64le:
3999 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
4001 case llvm::Triple::sparc:
4002 MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
4004 case llvm::Triple::sparcv9:
4005 MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
4007 case llvm::Triple::systemz:
4008 MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4013 for (StringRef Dir : MultiarchIncludeDirs) {
4014 if (D.getVFS().exists(SysRoot + Dir)) {
4015 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4020 if (getTriple().getOS() == llvm::Triple::RTEMS)
4023 // Add an include of '/include' directly. This isn't provided by default by
4024 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4025 // add even when Clang is acting as-if it were a system compiler.
4026 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4028 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4032 static std::string DetectLibcxxIncludePath(StringRef base) {
4035 std::string MaxVersionString = "";
4036 for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4037 LI = LI.increment(EC)) {
4038 StringRef VersionText = llvm::sys::path::filename(LI->path());
4040 if (VersionText[0] == 'v' &&
4041 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4042 if (Version > MaxVersion) {
4043 MaxVersion = Version;
4044 MaxVersionString = VersionText;
4048 return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4051 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
4052 ArgStringList &CC1Args) const {
4053 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4054 DriverArgs.hasArg(options::OPT_nostdincxx))
4057 // Check if libc++ has been enabled and provide its include paths if so.
4058 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
4059 const std::string LibCXXIncludePathCandidates[] = {
4060 DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4062 // We also check the system as for a long time this is the only place
4064 // FIXME: We should really remove this. It doesn't make any sense.
4065 DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++")};
4066 for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4067 if (IncludePath.empty() || !getVFS().exists(IncludePath))
4069 // Add the first candidate that exists.
4070 addSystemInclude(DriverArgs, CC1Args, IncludePath);
4076 // We need a detected GCC installation on Linux to provide libstdc++'s
4077 // headers. We handled the libc++ case above.
4078 if (!GCCInstallation.isValid())
4081 // By default, look for the C++ headers in an include directory adjacent to
4082 // the lib directory of the GCC installation. Note that this is expect to be
4083 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4084 StringRef LibDir = GCCInstallation.getParentLibPath();
4085 StringRef InstallDir = GCCInstallation.getInstallPath();
4086 StringRef TripleStr = GCCInstallation.getTriple().str();
4087 const Multilib &Multilib = GCCInstallation.getMultilib();
4088 const std::string GCCMultiarchTriple = getMultiarchTriple(
4089 getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
4090 const std::string TargetMultiarchTriple =
4091 getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
4092 const GCCVersion &Version = GCCInstallation.getVersion();
4094 // The primary search for libstdc++ supports multiarch variants.
4095 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4096 "/c++/" + Version.Text, TripleStr,
4097 GCCMultiarchTriple, TargetMultiarchTriple,
4098 Multilib.includeSuffix(), DriverArgs, CC1Args))
4101 // Otherwise, fall back on a bunch of options which don't use multiarch
4102 // layouts for simplicity.
4103 const std::string LibStdCXXIncludePathCandidates[] = {
4104 // Gentoo is weird and places its headers inside the GCC install,
4105 // so if the first attempt to find the headers fails, try these patterns.
4106 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4108 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4109 // Android standalone toolchain has C++ headers in yet another place.
4110 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4111 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4112 // without a subdirectory corresponding to the gcc version.
4113 LibDir.str() + "/../include/c++",
4116 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4117 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4118 /*GCCMultiarchTriple*/ "",
4119 /*TargetMultiarchTriple*/ "",
4120 Multilib.includeSuffix(), DriverArgs, CC1Args))
4125 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4126 ArgStringList &CC1Args) const {
4127 if (DriverArgs.hasArg(options::OPT_nocudainc))
4130 if (CudaInstallation.isValid()) {
4131 addSystemInclude(DriverArgs, CC1Args, CudaInstallation.getIncludePath());
4132 CC1Args.push_back("-include");
4133 CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
4137 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
4139 SanitizerMask Linux::getSupportedSanitizers() const {
4140 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4141 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4142 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4143 getTriple().getArch() == llvm::Triple::mips64el;
4144 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4145 getTriple().getArch() == llvm::Triple::ppc64le;
4146 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4147 getTriple().getArch() == llvm::Triple::aarch64_be;
4148 SanitizerMask Res = ToolChain::getSupportedSanitizers();
4149 Res |= SanitizerKind::Address;
4150 Res |= SanitizerKind::KernelAddress;
4151 Res |= SanitizerKind::Vptr;
4152 Res |= SanitizerKind::SafeStack;
4153 if (IsX86_64 || IsMIPS64 || IsAArch64)
4154 Res |= SanitizerKind::DataFlow;
4155 if (IsX86_64 || IsMIPS64 || IsAArch64)
4156 Res |= SanitizerKind::Leak;
4157 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4158 Res |= SanitizerKind::Thread;
4159 if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4160 Res |= SanitizerKind::Memory;
4161 if (IsX86 || IsX86_64) {
4162 Res |= SanitizerKind::Function;
4167 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4168 llvm::opt::ArgStringList &CmdArgs) const {
4169 if (!needsProfileRT(Args)) return;
4171 // Add linker option -u__llvm_runtime_variable to cause runtime
4172 // initialization module to be linked in.
4173 if (!Args.hasArg(options::OPT_coverage))
4174 CmdArgs.push_back(Args.MakeArgString(
4175 Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4176 ToolChain::addProfileRTLibs(Args, CmdArgs);
4179 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4181 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4182 const ArgList &Args)
4183 : Generic_ELF(D, Triple, Args) {
4185 // Path mangling to find libexec
4186 getProgramPaths().push_back(getDriver().getInstalledDir());
4187 if (getDriver().getInstalledDir() != getDriver().Dir)
4188 getProgramPaths().push_back(getDriver().Dir);
4190 getFilePaths().push_back(getDriver().Dir + "/../lib");
4191 getFilePaths().push_back("/usr/lib");
4192 getFilePaths().push_back("/usr/lib/gcc50");
4195 Tool *DragonFly::buildAssembler() const {
4196 return new tools::dragonfly::Assembler(*this);
4199 Tool *DragonFly::buildLinker() const {
4200 return new tools::dragonfly::Linker(*this);
4203 /// Stub for CUDA toolchain. At the moment we don't have assembler or
4204 /// linker and need toolchain mainly to propagate device-side options
4207 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4208 const ArgList &Args)
4209 : Linux(D, Triple, Args) {}
4212 CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
4213 llvm::opt::ArgStringList &CC1Args) const {
4214 Linux::addClangTargetOptions(DriverArgs, CC1Args);
4215 CC1Args.push_back("-fcuda-is-device");
4217 if (DriverArgs.hasArg(options::OPT_nocudalib))
4220 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(
4221 DriverArgs.getLastArgValue(options::OPT_march_EQ));
4222 if (!LibDeviceFile.empty()) {
4223 CC1Args.push_back("-mlink-cuda-bitcode");
4224 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4226 // Libdevice in CUDA-7.0 requires PTX version that's more recent
4227 // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4228 // came with CUDA-7.0.
4229 CC1Args.push_back("-target-feature");
4230 CC1Args.push_back("+ptx42");
4234 llvm::opt::DerivedArgList *
4235 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4236 const char *BoundArch) const {
4237 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
4238 const OptTable &Opts = getDriver().getOpts();
4240 for (Arg *A : Args) {
4241 if (A->getOption().matches(options::OPT_Xarch__)) {
4242 // Skip this argument unless the architecture matches BoundArch
4243 if (A->getValue(0) != StringRef(BoundArch))
4246 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4247 unsigned Prev = Index;
4248 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4250 // If the argument parsing failed or more than one argument was
4251 // consumed, the -Xarch_ argument's parameter tried to consume
4252 // extra arguments. Emit an error and ignore.
4254 // We also want to disallow any options which would alter the
4255 // driver behavior; that isn't going to work in our model. We
4256 // use isDriverOption() as an approximation, although things
4257 // like -O4 are going to slip through.
4258 if (!XarchArg || Index > Prev + 1) {
4259 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4260 << A->getAsString(Args);
4262 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4263 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4264 << A->getAsString(Args);
4267 XarchArg->setBaseArg(A);
4268 A = XarchArg.release();
4269 DAL->AddSynthesizedArg(A);
4274 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4278 /// XCore tool chain
4279 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
4280 const ArgList &Args)
4281 : ToolChain(D, Triple, Args) {
4282 // ProgramPaths are found via 'PATH' environment variable.
4285 Tool *XCoreToolChain::buildAssembler() const {
4286 return new tools::XCore::Assembler(*this);
4289 Tool *XCoreToolChain::buildLinker() const {
4290 return new tools::XCore::Linker(*this);
4293 bool XCoreToolChain::isPICDefault() const { return false; }
4295 bool XCoreToolChain::isPIEDefault() const { return false; }
4297 bool XCoreToolChain::isPICDefaultForced() const { return false; }
4299 bool XCoreToolChain::SupportsProfiling() const { return false; }
4301 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
4303 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4304 ArgStringList &CC1Args) const {
4305 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4306 DriverArgs.hasArg(options::OPT_nostdlibinc))
4308 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
4309 SmallVector<StringRef, 4> Dirs;
4310 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4311 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4312 ArrayRef<StringRef> DirVec(Dirs);
4313 addSystemIncludes(DriverArgs, CC1Args, DirVec);
4317 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
4318 ArgStringList &CC1Args) const {
4319 CC1Args.push_back("-nostdsysteminc");
4322 void XCoreToolChain::AddClangCXXStdlibIncludeArgs(
4323 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4324 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4325 DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4326 DriverArgs.hasArg(options::OPT_nostdincxx))
4328 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
4329 SmallVector<StringRef, 4> Dirs;
4330 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4331 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4332 ArrayRef<StringRef> DirVec(Dirs);
4333 addSystemIncludes(DriverArgs, CC1Args, DirVec);
4337 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
4338 ArgStringList &CmdArgs) const {
4339 // We don't output any lib args. This is handled by xcc.
4342 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
4343 const ArgList &Args)
4344 : Generic_GCC(D, Triple, Args) {
4345 // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
4346 // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
4347 // This won't work to find gcc. Instead we give the installation detector an
4348 // extra triple, which is preferable to further hacks of the logic that at
4349 // present is based solely on getArch(). In particular, it would be wrong to
4350 // choose the myriad installation when targeting a non-myriad sparc install.
4351 switch (Triple.getArch()) {
4353 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4355 case llvm::Triple::sparc:
4356 case llvm::Triple::sparcel:
4357 case llvm::Triple::shave:
4358 GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
4361 if (GCCInstallation.isValid()) {
4362 // The contents of LibDir are independent of the version of gcc.
4363 // This contains libc, libg (a superset of libc), libm, libstdc++, libssp.
4364 SmallString<128> LibDir(GCCInstallation.getParentLibPath());
4365 if (Triple.getArch() == llvm::Triple::sparcel)
4366 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib/le");
4368 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib");
4369 addPathIfExists(D, LibDir, getFilePaths());
4371 // This directory contains crt{i,n,begin,end}.o as well as libgcc.
4372 // These files are tied to a particular version of gcc.
4373 SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
4374 // There are actually 4 choices: {le,be} x {fpu,nofpu}
4375 // but as this toolchain is for LEON sparc, it can assume FPU.
4376 if (Triple.getArch() == llvm::Triple::sparcel)
4377 llvm::sys::path::append(CompilerSupportDir, "le");
4378 addPathIfExists(D, CompilerSupportDir, getFilePaths());
4382 MyriadToolChain::~MyriadToolChain() {}
4384 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4385 ArgStringList &CC1Args) const {
4386 if (!DriverArgs.hasArg(options::OPT_nostdinc))
4387 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
4390 void MyriadToolChain::AddClangCXXStdlibIncludeArgs(
4391 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4392 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4393 DriverArgs.hasArg(options::OPT_nostdincxx))
4396 // Only libstdc++, for now.
4397 StringRef LibDir = GCCInstallation.getParentLibPath();
4398 const GCCVersion &Version = GCCInstallation.getVersion();
4399 StringRef TripleStr = GCCInstallation.getTriple().str();
4400 const Multilib &Multilib = GCCInstallation.getMultilib();
4402 addLibStdCXXIncludePaths(
4403 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4404 "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
4407 // MyriadToolChain handles several triples:
4408 // {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
4409 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const {
4410 // The inherited method works fine if not targeting the SHAVE.
4411 if (!isShaveCompilation(getTriple()))
4412 return ToolChain::SelectTool(JA);
4413 switch (JA.getKind()) {
4414 case Action::PreprocessJobClass:
4415 case Action::CompileJobClass:
4417 Compiler.reset(new tools::SHAVE::Compiler(*this));
4418 return Compiler.get();
4419 case Action::AssembleJobClass:
4421 Assembler.reset(new tools::SHAVE::Assembler(*this));
4422 return Assembler.get();
4424 return ToolChain::getTool(JA.getKind());
4428 Tool *MyriadToolChain::buildLinker() const {
4429 return new tools::Myriad::Linker(*this);
4432 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
4433 const llvm::opt::ArgList &Args)
4434 : ToolChain(D, Triple, Args) {
4435 // Use LLD by default.
4436 DefaultLinker = "lld";
4439 bool WebAssembly::IsMathErrnoDefault() const { return false; }
4441 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
4443 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
4445 bool WebAssembly::isPICDefault() const { return false; }
4447 bool WebAssembly::isPIEDefault() const { return false; }
4449 bool WebAssembly::isPICDefaultForced() const { return false; }
4451 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
4453 // TODO: Support Objective C stuff.
4454 bool WebAssembly::SupportsObjCGC() const { return false; }
4456 bool WebAssembly::hasBlocksRuntime() const { return false; }
4458 // TODO: Support profiling.
4459 bool WebAssembly::SupportsProfiling() const { return false; }
4461 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
4463 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
4464 ArgStringList &CC1Args) const {
4465 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4466 options::OPT_fno_use_init_array, true))
4467 CC1Args.push_back("-fuse-init-array");
4470 Tool *WebAssembly::buildLinker() const {
4471 return new tools::wasm::Linker(*this);
4474 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4475 : Generic_ELF(D, Triple, Args) {
4476 if (Args.hasArg(options::OPT_static))
4477 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
4479 // Determine where to find the PS4 libraries. We use SCE_PS4_SDK_DIR
4480 // if it exists; otherwise use the driver's installation path, which
4481 // should be <SDK_DIR>/host_tools/bin.
4483 SmallString<512> PS4SDKDir;
4484 if (const char *EnvValue = getenv("SCE_PS4_SDK_DIR")) {
4485 if (!llvm::sys::fs::exists(EnvValue))
4486 getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
4487 PS4SDKDir = EnvValue;
4489 PS4SDKDir = getDriver().Dir;
4490 llvm::sys::path::append(PS4SDKDir, "/../../");
4493 // By default, the driver won't report a warning if it can't find
4494 // PS4's include or lib directories. This behavior could be changed if
4495 // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
4496 // If -isysroot was passed, use that as the SDK base path.
4497 std::string PrefixDir;
4498 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4499 PrefixDir = A->getValue();
4500 if (!llvm::sys::fs::exists(PrefixDir))
4501 getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
4503 PrefixDir = PS4SDKDir.str();
4505 SmallString<512> PS4SDKIncludeDir(PrefixDir);
4506 llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
4507 if (!Args.hasArg(options::OPT_nostdinc) &&
4508 !Args.hasArg(options::OPT_nostdlibinc) &&
4509 !Args.hasArg(options::OPT_isysroot) &&
4510 !Args.hasArg(options::OPT__sysroot_EQ) &&
4511 !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
4512 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4513 << "PS4 system headers" << PS4SDKIncludeDir;
4516 SmallString<512> PS4SDKLibDir(PS4SDKDir);
4517 llvm::sys::path::append(PS4SDKLibDir, "target/lib");
4518 if (!Args.hasArg(options::OPT_nostdlib) &&
4519 !Args.hasArg(options::OPT_nodefaultlibs) &&
4520 !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
4521 !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
4522 !Args.hasArg(options::OPT_emit_ast) &&
4523 !llvm::sys::fs::exists(PS4SDKLibDir)) {
4524 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4525 << "PS4 system libraries" << PS4SDKLibDir;
4528 getFilePaths().push_back(PS4SDKLibDir.str());
4531 Tool *PS4CPU::buildAssembler() const {
4532 return new tools::PS4cpu::Assemble(*this);
4535 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
4537 bool PS4CPU::isPICDefault() const { return true; }
4539 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
4541 SanitizerMask PS4CPU::getSupportedSanitizers() const {
4542 SanitizerMask Res = ToolChain::getSupportedSanitizers();
4543 Res |= SanitizerKind::Address;
4544 Res |= SanitizerKind::Vptr;