1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ToolChains.h"
11 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/Driver.h"
15 #include "clang/Driver/DriverDiagnostic.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/SanitizerArgs.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/OptTable.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/system_error.h"
32 #include "llvm/Support/Program.h"
34 // FIXME: This needs to be listed last until we fix the broken include guards
35 // in these files and the LLVM config.h files.
36 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
38 #include <cstdlib> // ::getenv
40 using namespace clang::driver;
41 using namespace clang::driver::toolchains;
42 using namespace clang;
43 using namespace llvm::opt;
45 /// Darwin - Darwin tool chain for i386 and x86_64.
47 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
48 : ToolChain(D, Triple, Args), TargetInitialized(false)
50 // Compute the initial Darwin version from the triple
51 unsigned Major, Minor, Micro;
52 if (!Triple.getMacOSXVersion(Major, Minor, Micro))
53 getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
55 llvm::raw_string_ostream(MacosxVersionMin)
56 << Major << '.' << Minor << '.' << Micro;
58 // FIXME: DarwinVersion is only used to find GCC's libexec directory.
59 // It should be removed when we stop supporting that.
60 DarwinVersion[0] = Minor + 4;
61 DarwinVersion[1] = Micro;
64 // Compute the initial iOS version from the triple
65 Triple.getiOSVersion(Major, Minor, Micro);
66 llvm::raw_string_ostream(iOSVersionMin)
67 << Major << '.' << Minor << '.' << Micro;
70 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
71 types::ID Ty = types::lookupTypeForExtension(Ext);
73 // Darwin always preprocesses assembly files (unless -x is used explicitly).
74 if (Ty == types::TY_PP_Asm)
80 bool Darwin::HasNativeLLVMSupport() const {
84 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
85 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
86 if (isTargetIPhoneOS())
87 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
89 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
90 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
93 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
94 bool Darwin::hasBlocksRuntime() const {
95 if (isTargetIPhoneOS())
96 return !isIPhoneOSVersionLT(3, 2);
98 return !isMacosxVersionLT(10, 6);
101 static const char *GetArmArchForMArch(StringRef Value) {
102 return llvm::StringSwitch<const char*>(Value)
103 .Case("armv6k", "armv6")
104 .Case("armv6m", "armv6m")
105 .Case("armv5tej", "armv5")
106 .Case("xscale", "xscale")
107 .Case("armv4t", "armv4t")
108 .Case("armv7", "armv7")
109 .Cases("armv7a", "armv7-a", "armv7")
110 .Cases("armv7r", "armv7-r", "armv7")
111 .Cases("armv7em", "armv7e-m", "armv7em")
112 .Cases("armv7f", "armv7-f", "armv7f")
113 .Cases("armv7k", "armv7-k", "armv7k")
114 .Cases("armv7m", "armv7-m", "armv7m")
115 .Cases("armv7s", "armv7-s", "armv7s")
119 static const char *GetArmArchForMCpu(StringRef Value) {
120 return llvm::StringSwitch<const char *>(Value)
121 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
122 .Cases("arm10e", "arm10tdmi", "armv5")
123 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
124 .Case("xscale", "xscale")
125 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
126 .Case("cortex-m0", "armv6m")
127 .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
128 .Cases("cortex-a9", "cortex-a12", "cortex-a15", "armv7")
129 .Cases("cortex-r4", "cortex-r5", "armv7r")
130 .Case("cortex-a9-mp", "armv7f")
131 .Case("cortex-m3", "armv7m")
132 .Case("cortex-m4", "armv7em")
133 .Case("swift", "armv7s")
137 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
138 switch (getTriple().getArch()) {
140 return getArchName();
142 case llvm::Triple::thumb:
143 case llvm::Triple::arm: {
144 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
145 if (const char *Arch = GetArmArchForMArch(A->getValue()))
148 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
149 if (const char *Arch = GetArmArchForMCpu(A->getValue()))
160 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
161 types::ID InputType) const {
162 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
164 // If the target isn't initialized (e.g., an unknown Darwin platform, return
165 // the default triple).
166 if (!isTargetInitialized())
167 return Triple.getTriple();
169 if (Triple.getArchName() == "thumbv6m" ||
170 Triple.getArchName() == "thumbv7m" ||
171 Triple.getArchName() == "thumbv7em") {
172 // OS is ios or macosx unless it's the v6m or v7m.
173 Triple.setOS(llvm::Triple::Darwin);
174 Triple.setEnvironment(llvm::Triple::EABI);
177 Str += isTargetIPhoneOS() ? "ios" : "macosx";
178 Str += getTargetVersion().getAsString();
179 Triple.setOSName(Str);
182 return Triple.getTriple();
185 void Generic_ELF::anchor() {}
187 Tool *Darwin::getTool(Action::ActionClass AC) const {
189 case Action::LipoJobClass:
191 Lipo.reset(new tools::darwin::Lipo(*this));
193 case Action::DsymutilJobClass:
195 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
196 return Dsymutil.get();
197 case Action::VerifyJobClass:
199 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
200 return VerifyDebug.get();
202 return ToolChain::getTool(AC);
206 Tool *Darwin::buildLinker() const {
207 return new tools::darwin::Link(*this);
210 Tool *Darwin::buildAssembler() const {
211 return new tools::darwin::Assemble(*this);
214 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
216 : Darwin(D, Triple, Args)
218 getProgramPaths().push_back(getDriver().getInstalledDir());
219 if (getDriver().getInstalledDir() != getDriver().Dir)
220 getProgramPaths().push_back(getDriver().Dir);
222 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
223 getProgramPaths().push_back(getDriver().getInstalledDir());
224 if (getDriver().getInstalledDir() != getDriver().Dir)
225 getProgramPaths().push_back(getDriver().Dir);
228 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
229 ArgStringList &CmdArgs) const {
231 CmdArgs.push_back("-force_load");
232 SmallString<128> P(getDriver().ClangExecutable);
233 llvm::sys::path::remove_filename(P); // 'clang'
234 llvm::sys::path::remove_filename(P); // 'bin'
235 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
236 // Mash in the platform.
237 if (isTargetIOSSimulator())
238 P += "iphonesimulator";
239 else if (isTargetIPhoneOS())
245 CmdArgs.push_back(Args.MakeArgString(P));
248 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
249 ArgStringList &CmdArgs,
250 const char *DarwinStaticLib,
251 bool AlwaysLink) const {
252 SmallString<128> P(getDriver().ResourceDir);
253 llvm::sys::path::append(P, "lib", "darwin", DarwinStaticLib);
255 // For now, allow missing resource libraries to support developers who may
256 // not have compiler-rt checked out or integrated into their build (unless
257 // we explicitly force linking with this library).
258 if (AlwaysLink || llvm::sys::fs::exists(P.str()))
259 CmdArgs.push_back(Args.MakeArgString(P.str()));
262 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
263 ArgStringList &CmdArgs) const {
264 // Darwin only supports the compiler-rt based runtime libraries.
265 switch (GetRuntimeLibType(Args)) {
266 case ToolChain::RLT_CompilerRT:
269 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
270 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
274 // Darwin doesn't support real static executables, don't link any runtime
275 // libraries with -static.
276 if (Args.hasArg(options::OPT_static) ||
277 Args.hasArg(options::OPT_fapple_kext) ||
278 Args.hasArg(options::OPT_mkernel))
281 // Reject -static-libgcc for now, we can deal with this when and if someone
282 // cares. This is useful in situations where someone wants to statically link
283 // something like libstdc++, and needs its runtime support routines.
284 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
285 getDriver().Diag(diag::err_drv_unsupported_opt)
286 << A->getAsString(Args);
290 // If we are building profile support, link that library in.
291 if (Args.hasArg(options::OPT_fprofile_arcs) ||
292 Args.hasArg(options::OPT_fprofile_generate) ||
293 Args.hasArg(options::OPT_fcreate_profile) ||
294 Args.hasArg(options::OPT_coverage)) {
295 // Select the appropriate runtime library for the target.
296 if (isTargetIPhoneOS()) {
297 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
299 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
303 const SanitizerArgs &Sanitize = getSanitizerArgs();
305 // Add Ubsan runtime library, if required.
306 if (Sanitize.needsUbsanRt()) {
307 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
308 if (isTargetIPhoneOS()) {
309 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
310 << "-fsanitize=undefined";
312 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
314 // The Ubsan runtime library requires C++.
315 AddCXXStdlibLibArgs(Args, CmdArgs);
319 // Add ASAN runtime library, if required. Dynamic libraries and bundles
320 // should not be linked with the runtime library.
321 if (Sanitize.needsAsanRt()) {
322 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
323 if (isTargetIPhoneOS() && !isTargetIOSSimulator()) {
324 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
325 << "-fsanitize=address";
327 if (!Args.hasArg(options::OPT_dynamiclib) &&
328 !Args.hasArg(options::OPT_bundle)) {
329 // The ASAN runtime library requires C++.
330 AddCXXStdlibLibArgs(Args, CmdArgs);
332 if (isTargetMacOS()) {
333 AddLinkRuntimeLib(Args, CmdArgs,
334 "libclang_rt.asan_osx_dynamic.dylib",
337 if (isTargetIOSSimulator()) {
338 AddLinkRuntimeLib(Args, CmdArgs,
339 "libclang_rt.asan_iossim_dynamic.dylib",
346 // Otherwise link libSystem, then the dynamic runtime library, and finally any
347 // target specific static runtime library.
348 CmdArgs.push_back("-lSystem");
350 // Select the dynamic runtime library and the target specific static library.
351 if (isTargetIPhoneOS()) {
352 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
353 // it never went into the SDK.
354 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
355 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
356 CmdArgs.push_back("-lgcc_s.1");
358 // We currently always need a static runtime library for iOS.
359 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
361 // The dynamic runtime library was merged with libSystem for 10.6 and
362 // beyond; only 10.4 and 10.5 need an additional runtime library.
363 if (isMacosxVersionLT(10, 5))
364 CmdArgs.push_back("-lgcc_s.10.4");
365 else if (isMacosxVersionLT(10, 6))
366 CmdArgs.push_back("-lgcc_s.10.5");
368 // For OS X, we thought we would only need a static runtime library when
369 // targeting 10.4, to provide versions of the static functions which were
370 // omitted from 10.4.dylib.
372 // Unfortunately, that turned out to not be true, because Darwin system
373 // headers can still use eprintf on i386, and it is not exported from
374 // libSystem. Therefore, we still must provide a runtime library just for
375 // the tiny tiny handful of projects that *might* use that symbol.
376 if (isMacosxVersionLT(10, 5)) {
377 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
379 if (getTriple().getArch() == llvm::Triple::x86)
380 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
381 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
386 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
387 const OptTable &Opts = getDriver().getOpts();
389 // Support allowing the SDKROOT environment variable used by xcrun and other
390 // Xcode tools to define the default sysroot, by making it the default for
392 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
393 // Warn if the path does not exist.
394 if (!llvm::sys::fs::exists(A->getValue()))
395 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
397 if (char *env = ::getenv("SDKROOT")) {
398 // We only use this value as the default if it is an absolute path,
399 // exists, and it is not the root path.
400 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
401 StringRef(env) != "/") {
402 Args.append(Args.MakeSeparateArg(
403 0, Opts.getOption(options::OPT_isysroot), env));
408 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
409 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
410 Arg *iOSSimVersion = Args.getLastArg(
411 options::OPT_mios_simulator_version_min_EQ);
413 if (OSXVersion && (iOSVersion || iOSSimVersion)) {
414 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
415 << OSXVersion->getAsString(Args)
416 << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
417 iOSVersion = iOSSimVersion = 0;
418 } else if (iOSVersion && iOSSimVersion) {
419 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
420 << iOSVersion->getAsString(Args)
421 << iOSSimVersion->getAsString(Args);
423 } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
424 // If no deployment target was specified on the command line, check for
425 // environment defines.
428 StringRef iOSSimTarget;
429 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
431 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
433 if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
436 // If no '-miphoneos-version-min' specified on the command line and
437 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
438 // based on -isysroot.
439 if (iOSTarget.empty()) {
440 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
441 StringRef first, second;
442 StringRef isysroot = A->getValue();
443 llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
445 iOSTarget = second.substr(0,3);
449 // If no OSX or iOS target has been specified and we're compiling for armv7,
450 // go ahead as assume we're targeting iOS.
451 if (OSXTarget.empty() && iOSTarget.empty() &&
452 (getDarwinArchName(Args) == "armv7" ||
453 getDarwinArchName(Args) == "armv7s"))
454 iOSTarget = iOSVersionMin;
456 // Handle conflicting deployment targets
458 // FIXME: Don't hardcode default here.
460 // Do not allow conflicts with the iOS simulator target.
461 if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
462 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
463 << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
464 << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
465 "IPHONEOS_DEPLOYMENT_TARGET");
468 // Allow conflicts among OSX and iOS for historical reasons, but choose the
470 if (!OSXTarget.empty() && !iOSTarget.empty()) {
471 if (getTriple().getArch() == llvm::Triple::arm ||
472 getTriple().getArch() == llvm::Triple::thumb)
478 if (!OSXTarget.empty()) {
479 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
480 OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
481 Args.append(OSXVersion);
482 } else if (!iOSTarget.empty()) {
483 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
484 iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
485 Args.append(iOSVersion);
486 } else if (!iOSSimTarget.empty()) {
487 const Option O = Opts.getOption(
488 options::OPT_mios_simulator_version_min_EQ);
489 iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
490 Args.append(iOSSimVersion);
492 // Otherwise, assume we are targeting OS X.
493 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
494 OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
495 Args.append(OSXVersion);
499 // Reject invalid architecture combinations.
500 if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
501 getTriple().getArch() != llvm::Triple::x86_64)) {
502 getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
503 << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
506 // Set the tool chain target information.
507 unsigned Major, Minor, Micro;
510 assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
511 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
512 Micro, HadExtra) || HadExtra ||
513 Major != 10 || Minor >= 100 || Micro >= 100)
514 getDriver().Diag(diag::err_drv_invalid_version_number)
515 << OSXVersion->getAsString(Args);
517 const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
518 assert(Version && "Unknown target platform!");
519 if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
520 Micro, HadExtra) || HadExtra ||
521 Major >= 10 || Minor >= 100 || Micro >= 100)
522 getDriver().Diag(diag::err_drv_invalid_version_number)
523 << Version->getAsString(Args);
526 bool IsIOSSim = bool(iOSSimVersion);
528 // In GCC, the simulator historically was treated as being OS X in some
529 // contexts, like determining the link logic, despite generally being called
530 // with an iOS deployment target. For compatibility, we detect the
531 // simulator as iOS + x86, and treat it differently in a few contexts.
532 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
533 getTriple().getArch() == llvm::Triple::x86_64))
536 setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
539 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
540 ArgStringList &CmdArgs) const {
541 CXXStdlibType Type = GetCXXStdlibType(Args);
544 case ToolChain::CST_Libcxx:
545 CmdArgs.push_back("-lc++");
548 case ToolChain::CST_Libstdcxx: {
549 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
550 // it was previously found in the gcc lib dir. However, for all the Darwin
551 // platforms we care about it was -lstdc++.6, so we search for that
552 // explicitly if we can't see an obvious -lstdc++ candidate.
554 // Check in the sysroot first.
555 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
556 SmallString<128> P(A->getValue());
557 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
559 if (!llvm::sys::fs::exists(P.str())) {
560 llvm::sys::path::remove_filename(P);
561 llvm::sys::path::append(P, "libstdc++.6.dylib");
562 if (llvm::sys::fs::exists(P.str())) {
563 CmdArgs.push_back(Args.MakeArgString(P.str()));
569 // Otherwise, look in the root.
570 // FIXME: This should be removed someday when we don't have to care about
571 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
572 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
573 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
574 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
578 // Otherwise, let the linker search.
579 CmdArgs.push_back("-lstdc++");
585 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
586 ArgStringList &CmdArgs) const {
588 // For Darwin platforms, use the compiler-rt-based support library
589 // instead of the gcc-provided one (which is also incidentally
590 // only present in the gcc lib dir, which makes it hard to find).
592 SmallString<128> P(getDriver().ResourceDir);
593 llvm::sys::path::append(P, "lib", "darwin");
595 // Use the newer cc_kext for iOS ARM after 6.0.
596 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
597 !isIPhoneOSVersionLT(6, 0)) {
598 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
600 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
603 // For now, allow missing resource libraries to support developers who may
604 // not have compiler-rt checked out or integrated into their build.
605 if (llvm::sys::fs::exists(P.str()))
606 CmdArgs.push_back(Args.MakeArgString(P.str()));
609 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
610 const char *BoundArch) const {
611 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
612 const OptTable &Opts = getDriver().getOpts();
614 // FIXME: We really want to get out of the tool chain level argument
615 // translation business, as it makes the driver functionality much
616 // more opaque. For now, we follow gcc closely solely for the
617 // purpose of easily achieving feature parity & testability. Once we
618 // have something that works, we should reevaluate each translation
619 // and try to push it down into tool specific logic.
621 for (ArgList::const_iterator it = Args.begin(),
622 ie = Args.end(); it != ie; ++it) {
625 if (A->getOption().matches(options::OPT_Xarch__)) {
626 // Skip this argument unless the architecture matches either the toolchain
627 // triple arch, or the arch being bound.
628 llvm::Triple::ArchType XarchArch =
629 tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
630 if (!(XarchArch == getArch() ||
631 (BoundArch && XarchArch ==
632 tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
635 Arg *OriginalArg = A;
636 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
637 unsigned Prev = Index;
638 Arg *XarchArg = Opts.ParseOneArg(Args, Index);
640 // If the argument parsing failed or more than one argument was
641 // consumed, the -Xarch_ argument's parameter tried to consume
642 // extra arguments. Emit an error and ignore.
644 // We also want to disallow any options which would alter the
645 // driver behavior; that isn't going to work in our model. We
646 // use isDriverOption() as an approximation, although things
647 // like -O4 are going to slip through.
648 if (!XarchArg || Index > Prev + 1) {
649 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
650 << A->getAsString(Args);
652 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
653 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
654 << A->getAsString(Args);
658 XarchArg->setBaseArg(A);
661 DAL->AddSynthesizedArg(A);
663 // Linker input arguments require custom handling. The problem is that we
664 // have already constructed the phase actions, so we can not treat them as
665 // "input arguments".
666 if (A->getOption().hasFlag(options::LinkerInput)) {
667 // Convert the argument into individual Zlinker_input_args.
668 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
669 DAL->AddSeparateArg(OriginalArg,
670 Opts.getOption(options::OPT_Zlinker_input),
678 // Sob. These is strictly gcc compatible for the time being. Apple
679 // gcc translates options twice, which means that self-expanding
680 // options add duplicates.
681 switch ((options::ID) A->getOption().getID()) {
686 case options::OPT_mkernel:
687 case options::OPT_fapple_kext:
689 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
692 case options::OPT_dependency_file:
693 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
697 case options::OPT_gfull:
698 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
700 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
703 case options::OPT_gused:
704 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
706 Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
709 case options::OPT_shared:
710 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
713 case options::OPT_fconstant_cfstrings:
714 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
717 case options::OPT_fno_constant_cfstrings:
718 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
721 case options::OPT_Wnonportable_cfstrings:
723 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
726 case options::OPT_Wno_nonportable_cfstrings:
728 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
731 case options::OPT_fpascal_strings:
732 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
735 case options::OPT_fno_pascal_strings:
736 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
741 if (getTriple().getArch() == llvm::Triple::x86 ||
742 getTriple().getArch() == llvm::Triple::x86_64)
743 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
744 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
746 // Add the arch options based on the particular spelling of -arch, to match
747 // how the driver driver works.
749 StringRef Name = BoundArch;
750 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
751 const Option MArch = Opts.getOption(options::OPT_march_EQ);
753 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
754 // which defines the list of which architectures we accept.
757 else if (Name == "ppc601")
758 DAL->AddJoinedArg(0, MCpu, "601");
759 else if (Name == "ppc603")
760 DAL->AddJoinedArg(0, MCpu, "603");
761 else if (Name == "ppc604")
762 DAL->AddJoinedArg(0, MCpu, "604");
763 else if (Name == "ppc604e")
764 DAL->AddJoinedArg(0, MCpu, "604e");
765 else if (Name == "ppc750")
766 DAL->AddJoinedArg(0, MCpu, "750");
767 else if (Name == "ppc7400")
768 DAL->AddJoinedArg(0, MCpu, "7400");
769 else if (Name == "ppc7450")
770 DAL->AddJoinedArg(0, MCpu, "7450");
771 else if (Name == "ppc970")
772 DAL->AddJoinedArg(0, MCpu, "970");
774 else if (Name == "ppc64" || Name == "ppc64le")
775 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
777 else if (Name == "i386")
779 else if (Name == "i486")
780 DAL->AddJoinedArg(0, MArch, "i486");
781 else if (Name == "i586")
782 DAL->AddJoinedArg(0, MArch, "i586");
783 else if (Name == "i686")
784 DAL->AddJoinedArg(0, MArch, "i686");
785 else if (Name == "pentium")
786 DAL->AddJoinedArg(0, MArch, "pentium");
787 else if (Name == "pentium2")
788 DAL->AddJoinedArg(0, MArch, "pentium2");
789 else if (Name == "pentpro")
790 DAL->AddJoinedArg(0, MArch, "pentiumpro");
791 else if (Name == "pentIIm3")
792 DAL->AddJoinedArg(0, MArch, "pentium2");
794 else if (Name == "x86_64")
795 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
796 else if (Name == "x86_64h") {
797 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
798 DAL->AddJoinedArg(0, MArch, "x86_64h");
801 else if (Name == "arm")
802 DAL->AddJoinedArg(0, MArch, "armv4t");
803 else if (Name == "armv4t")
804 DAL->AddJoinedArg(0, MArch, "armv4t");
805 else if (Name == "armv5")
806 DAL->AddJoinedArg(0, MArch, "armv5tej");
807 else if (Name == "xscale")
808 DAL->AddJoinedArg(0, MArch, "xscale");
809 else if (Name == "armv6")
810 DAL->AddJoinedArg(0, MArch, "armv6k");
811 else if (Name == "armv6m")
812 DAL->AddJoinedArg(0, MArch, "armv6m");
813 else if (Name == "armv7")
814 DAL->AddJoinedArg(0, MArch, "armv7a");
815 else if (Name == "armv7em")
816 DAL->AddJoinedArg(0, MArch, "armv7em");
817 else if (Name == "armv7f")
818 DAL->AddJoinedArg(0, MArch, "armv7f");
819 else if (Name == "armv7k")
820 DAL->AddJoinedArg(0, MArch, "armv7k");
821 else if (Name == "armv7m")
822 DAL->AddJoinedArg(0, MArch, "armv7m");
823 else if (Name == "armv7s")
824 DAL->AddJoinedArg(0, MArch, "armv7s");
827 llvm_unreachable("invalid Darwin arch");
830 // Add an explicit version min argument for the deployment target. We do this
831 // after argument translation because -Xarch_ arguments may add a version min
834 AddDeploymentTarget(*DAL);
836 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
837 // FIXME: It would be far better to avoid inserting those -static arguments,
838 // but we can't check the deployment target in the translation code until
840 if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
841 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
844 if (A->getOption().getID() != options::OPT_mkernel &&
845 A->getOption().getID() != options::OPT_fapple_kext)
847 assert(it != ie && "unexpected argument translation");
849 assert(A->getOption().getID() == options::OPT_static &&
850 "missing expected -static argument");
851 it = DAL->getArgs().erase(it);
855 // Default to use libc++ on OS X 10.9+ and iOS 7+.
856 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
857 (isTargetIPhoneOS() && !isIPhoneOSVersionLT(7, 0))) &&
858 !Args.getLastArg(options::OPT_stdlib_EQ))
859 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_stdlib_EQ), "libc++");
861 // Validate the C++ standard library choice.
862 CXXStdlibType Type = GetCXXStdlibType(*DAL);
863 if (Type == ToolChain::CST_Libcxx) {
864 // Check whether the target provides libc++.
867 // Complain about targetting iOS < 5.0 in any way.
868 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
871 if (where != StringRef()) {
872 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
880 bool Darwin::IsUnwindTablesDefault() const {
881 return getArch() == llvm::Triple::x86_64;
884 bool Darwin::UseDwarfDebugFlags() const {
885 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
890 bool Darwin::UseSjLjExceptions() const {
891 // Darwin uses SjLj exceptions on ARM.
892 return (getTriple().getArch() == llvm::Triple::arm ||
893 getTriple().getArch() == llvm::Triple::thumb);
896 bool Darwin::isPICDefault() const {
900 bool Darwin::isPIEDefault() const {
904 bool Darwin::isPICDefaultForced() const {
905 return getArch() == llvm::Triple::x86_64;
908 bool Darwin::SupportsProfiling() const {
909 // Profiling instrumentation is only supported on x86.
910 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
913 bool Darwin::SupportsObjCGC() const {
914 // Garbage collection is supported everywhere except on iPhone OS.
915 return !isTargetIPhoneOS();
918 void Darwin::CheckObjCARC() const {
919 if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
921 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
925 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
926 types::ID InputType) const {
927 return ComputeLLVMTriple(Args, InputType);
930 /// Generic_GCC - A tool chain using the 'gcc' command to perform
931 /// all subcommands; this relies on gcc translating the majority of
932 /// command line options.
934 /// \brief Parse a GCCVersion object out of a string of text.
936 /// This is the primary means of forming GCCVersion objects.
938 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
939 const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
940 std::pair<StringRef, StringRef> First = VersionText.split('.');
941 std::pair<StringRef, StringRef> Second = First.second.split('.');
943 GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
944 if (First.first.getAsInteger(10, GoodVersion.Major) ||
945 GoodVersion.Major < 0)
947 GoodVersion.MajorStr = First.first.str();
948 if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
949 GoodVersion.Minor < 0)
951 GoodVersion.MinorStr = Second.first.str();
953 // First look for a number prefix and parse that if present. Otherwise just
954 // stash the entire patch string in the suffix, and leave the number
955 // unspecified. This covers versions strings such as:
961 // And retains any patch number it finds.
962 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
963 if (!PatchText.empty()) {
964 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
965 // Try to parse the number and any suffix.
966 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
967 GoodVersion.Patch < 0)
969 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
976 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
977 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
979 StringRef RHSPatchSuffix) const {
980 if (Major != RHSMajor)
981 return Major < RHSMajor;
982 if (Minor != RHSMinor)
983 return Minor < RHSMinor;
984 if (Patch != RHSPatch) {
985 // Note that versions without a specified patch sort higher than those with
992 // Otherwise just sort on the patch itself.
993 return Patch < RHSPatch;
995 if (PatchSuffix != RHSPatchSuffix) {
996 // Sort empty suffixes higher.
997 if (RHSPatchSuffix.empty())
999 if (PatchSuffix.empty())
1002 // Provide a lexicographic sort to make this a total ordering.
1003 return PatchSuffix < RHSPatchSuffix;
1006 // The versions are equal.
1010 static StringRef getGCCToolchainDir(const ArgList &Args) {
1011 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1013 return A->getValue();
1014 return GCC_INSTALL_PREFIX;
1017 /// \brief Construct a GCCInstallationDetector from the driver.
1019 /// This performs all of the autodetection and sets up the various paths.
1020 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1022 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1023 /// should instead pull the target out of the driver. This is currently
1024 /// necessary because the driver doesn't store the final version of the target
1026 Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
1027 const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args)
1028 : IsValid(false), D(D) {
1029 llvm::Triple BiarchVariantTriple =
1030 TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1031 : TargetTriple.get32BitArchVariant();
1032 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1033 // The library directories which may contain GCC installations.
1034 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1035 // The compatible GCC triples for this particular architecture.
1036 SmallVector<StringRef, 10> CandidateTripleAliases;
1037 SmallVector<StringRef, 10> CandidateBiarchTripleAliases;
1038 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1039 CandidateTripleAliases, CandidateBiarchLibDirs,
1040 CandidateBiarchTripleAliases);
1042 // Compute the set of prefixes for our search.
1043 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1044 D.PrefixDirs.end());
1046 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1047 if (GCCToolchainDir != "") {
1048 if (GCCToolchainDir.back() == '/')
1049 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1051 Prefixes.push_back(GCCToolchainDir);
1053 // If we have a SysRoot, try that first.
1054 if (!D.SysRoot.empty()) {
1055 Prefixes.push_back(D.SysRoot);
1056 Prefixes.push_back(D.SysRoot + "/usr");
1059 // Then look for gcc installed alongside clang.
1060 Prefixes.push_back(D.InstalledDir + "/..");
1062 // And finally in /usr.
1063 if (D.SysRoot.empty())
1064 Prefixes.push_back("/usr");
1067 // Loop over the various components which exist and select the best GCC
1068 // installation available. GCC installs are ranked by version number.
1069 Version = GCCVersion::Parse("0.0.0");
1070 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1071 if (!llvm::sys::fs::exists(Prefixes[i]))
1073 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1074 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1075 if (!llvm::sys::fs::exists(LibDir))
1077 for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1078 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1079 CandidateTripleAliases[k]);
1081 for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1082 const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1083 if (!llvm::sys::fs::exists(LibDir))
1085 for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1087 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1088 CandidateBiarchTripleAliases[k],
1089 /*NeedsBiarchSuffix=*/ true);
1094 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1095 for (std::set<std::string>::const_iterator
1096 I = CandidateGCCInstallPaths.begin(),
1097 E = CandidateGCCInstallPaths.end();
1099 OS << "Found candidate GCC installation: " << *I << "\n";
1101 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1104 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1105 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1106 SmallVectorImpl<StringRef> &LibDirs,
1107 SmallVectorImpl<StringRef> &TripleAliases,
1108 SmallVectorImpl<StringRef> &BiarchLibDirs,
1109 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1110 // Declare a bunch of static data sets that we'll select between below. These
1111 // are specifically designed to always refer to string literals to avoid any
1112 // lifetime or initialization issues.
1113 static const char *const AArch64LibDirs[] = { "/lib" };
1114 static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1115 "aarch64-linux-gnu" };
1117 static const char *const ARMLibDirs[] = { "/lib" };
1118 static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1119 "arm-linux-androideabi" };
1120 static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1121 "armv7hl-redhat-linux-gnueabi" };
1123 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1124 static const char *const X86_64Triples[] = {
1125 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1126 "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1127 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux"
1129 static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1130 static const char *const X86Triples[] = {
1131 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1132 "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1133 "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1134 "i686-montavista-linux"
1137 static const char *const MIPSLibDirs[] = { "/lib" };
1138 static const char *const MIPSTriples[] = { "mips-linux-gnu",
1139 "mips-mti-linux-gnu" };
1140 static const char *const MIPSELLibDirs[] = { "/lib" };
1141 static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1142 "mipsel-linux-android" };
1144 static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1145 static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
1146 "mips-mti-linux-gnu" };
1147 static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1148 static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
1149 "mips-mti-linux-gnu" };
1151 static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1152 static const char *const PPCTriples[] = {
1153 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1154 "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1156 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1157 static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1158 "powerpc64-unknown-linux-gnu",
1159 "powerpc64-suse-linux",
1160 "ppc64-redhat-linux" };
1161 static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
1162 static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
1163 "powerpc64le-unknown-linux-gnu",
1164 "powerpc64le-suse-linux",
1165 "ppc64le-redhat-linux" };
1167 static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1168 static const char *const SystemZTriples[] = {
1169 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1170 "s390x-suse-linux", "s390x-redhat-linux"
1173 switch (TargetTriple.getArch()) {
1174 case llvm::Triple::aarch64:
1175 LibDirs.append(AArch64LibDirs,
1176 AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1177 TripleAliases.append(AArch64Triples,
1178 AArch64Triples + llvm::array_lengthof(AArch64Triples));
1179 BiarchLibDirs.append(AArch64LibDirs,
1180 AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1181 BiarchTripleAliases.append(
1182 AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1184 case llvm::Triple::arm:
1185 case llvm::Triple::thumb:
1186 LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1187 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1188 TripleAliases.append(ARMHFTriples,
1189 ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1191 TripleAliases.append(ARMTriples,
1192 ARMTriples + llvm::array_lengthof(ARMTriples));
1195 case llvm::Triple::x86_64:
1196 LibDirs.append(X86_64LibDirs,
1197 X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1198 TripleAliases.append(X86_64Triples,
1199 X86_64Triples + llvm::array_lengthof(X86_64Triples));
1200 BiarchLibDirs.append(X86LibDirs,
1201 X86LibDirs + llvm::array_lengthof(X86LibDirs));
1202 BiarchTripleAliases.append(X86Triples,
1203 X86Triples + llvm::array_lengthof(X86Triples));
1205 case llvm::Triple::x86:
1206 LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1207 TripleAliases.append(X86Triples,
1208 X86Triples + llvm::array_lengthof(X86Triples));
1209 BiarchLibDirs.append(X86_64LibDirs,
1210 X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1211 BiarchTripleAliases.append(
1212 X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1214 case llvm::Triple::mips:
1215 LibDirs.append(MIPSLibDirs,
1216 MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1217 TripleAliases.append(MIPSTriples,
1218 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1219 BiarchLibDirs.append(MIPS64LibDirs,
1220 MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1221 BiarchTripleAliases.append(
1222 MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1224 case llvm::Triple::mipsel:
1225 LibDirs.append(MIPSELLibDirs,
1226 MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1227 TripleAliases.append(MIPSELTriples,
1228 MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1229 TripleAliases.append(MIPSTriples,
1230 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1231 BiarchLibDirs.append(
1233 MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1234 BiarchTripleAliases.append(
1236 MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1238 case llvm::Triple::mips64:
1239 LibDirs.append(MIPS64LibDirs,
1240 MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1241 TripleAliases.append(MIPS64Triples,
1242 MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1243 BiarchLibDirs.append(MIPSLibDirs,
1244 MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1245 BiarchTripleAliases.append(MIPSTriples,
1246 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1248 case llvm::Triple::mips64el:
1249 LibDirs.append(MIPS64ELLibDirs,
1250 MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1251 TripleAliases.append(
1253 MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1254 BiarchLibDirs.append(MIPSELLibDirs,
1255 MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1256 BiarchTripleAliases.append(
1257 MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1258 BiarchTripleAliases.append(
1259 MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1261 case llvm::Triple::ppc:
1262 LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1263 TripleAliases.append(PPCTriples,
1264 PPCTriples + llvm::array_lengthof(PPCTriples));
1265 BiarchLibDirs.append(PPC64LibDirs,
1266 PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1267 BiarchTripleAliases.append(
1268 PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1270 case llvm::Triple::ppc64:
1271 LibDirs.append(PPC64LibDirs,
1272 PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1273 TripleAliases.append(PPC64Triples,
1274 PPC64Triples + llvm::array_lengthof(PPC64Triples));
1275 BiarchLibDirs.append(PPCLibDirs,
1276 PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1277 BiarchTripleAliases.append(PPCTriples,
1278 PPCTriples + llvm::array_lengthof(PPCTriples));
1280 case llvm::Triple::ppc64le:
1281 LibDirs.append(PPC64LELibDirs,
1282 PPC64LELibDirs + llvm::array_lengthof(PPC64LELibDirs));
1283 TripleAliases.append(PPC64LETriples,
1284 PPC64LETriples + llvm::array_lengthof(PPC64LETriples));
1286 case llvm::Triple::systemz:
1287 LibDirs.append(SystemZLibDirs,
1288 SystemZLibDirs + llvm::array_lengthof(SystemZLibDirs));
1289 TripleAliases.append(SystemZTriples,
1290 SystemZTriples + llvm::array_lengthof(SystemZTriples));
1294 // By default, just rely on the standard lib directories and the original
1299 // Always append the drivers target triple to the end, in case it doesn't
1300 // match any of our aliases.
1301 TripleAliases.push_back(TargetTriple.str());
1303 // Also include the multiarch variant if it's different.
1304 if (TargetTriple.str() != BiarchTriple.str())
1305 BiarchTripleAliases.push_back(BiarchTriple.str());
1308 static bool isSoftFloatABI(const ArgList &Args) {
1309 Arg *A = Args.getLastArg(options::OPT_msoft_float,
1310 options::OPT_mhard_float,
1311 options::OPT_mfloat_abi_EQ);
1312 if (!A) return false;
1314 return A->getOption().matches(options::OPT_msoft_float) ||
1315 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1316 A->getValue() == StringRef("soft"));
1319 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1320 return Arch == llvm::Triple::mips ||
1321 Arch == llvm::Triple::mipsel ||
1322 Arch == llvm::Triple::mips64 ||
1323 Arch == llvm::Triple::mips64el;
1326 static bool isMips16(const ArgList &Args) {
1327 Arg *A = Args.getLastArg(options::OPT_mips16,
1328 options::OPT_mno_mips16);
1329 return A && A->getOption().matches(options::OPT_mips16);
1332 static bool isMips32r2(const ArgList &Args) {
1333 Arg *A = Args.getLastArg(options::OPT_march_EQ,
1334 options::OPT_mcpu_EQ);
1336 return A && A->getValue() == StringRef("mips32r2");
1339 static bool isMips64r2(const ArgList &Args) {
1340 Arg *A = Args.getLastArg(options::OPT_march_EQ,
1341 options::OPT_mcpu_EQ);
1343 return A && A->getValue() == StringRef("mips64r2");
1346 static bool isMicroMips(const ArgList &Args) {
1347 Arg *A = Args.getLastArg(options::OPT_mmicromips,
1348 options::OPT_mno_micromips);
1349 return A && A->getOption().matches(options::OPT_mmicromips);
1352 static bool isMipsFP64(const ArgList &Args) {
1353 Arg *A = Args.getLastArg(options::OPT_mfp64, options::OPT_mfp32);
1354 return A && A->getOption().matches(options::OPT_mfp64);
1357 static bool isMipsNan2008(const ArgList &Args) {
1358 Arg *A = Args.getLastArg(options::OPT_mnan_EQ);
1359 return A && A->getValue() == StringRef("2008");
1362 // FIXME: There is the same routine in the Tools.cpp.
1363 static bool hasMipsN32ABIArg(const ArgList &Args) {
1364 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1365 return A && (A->getValue() == StringRef("n32"));
1368 static bool hasCrtBeginObj(Twine Path) {
1369 return llvm::sys::fs::exists(Path + "/crtbegin.o");
1372 static bool findTargetBiarchSuffix(std::string &Suffix, StringRef Path,
1373 llvm::Triple::ArchType TargetArch,
1374 const ArgList &Args) {
1375 // FIXME: This routine was only intended to model bi-arch toolchains which
1376 // use -m32 and -m64 to swap between variants of a target. It shouldn't be
1377 // doing ABI-based builtin location for MIPS.
1378 if (hasMipsN32ABIArg(Args))
1380 else if (TargetArch == llvm::Triple::x86_64 ||
1381 TargetArch == llvm::Triple::ppc64 ||
1382 TargetArch == llvm::Triple::systemz ||
1383 TargetArch == llvm::Triple::mips64 ||
1384 TargetArch == llvm::Triple::mips64el)
1389 return hasCrtBeginObj(Path + Suffix);
1392 void Generic_GCC::GCCInstallationDetector::findMIPSABIDirSuffix(
1393 std::string &Suffix, llvm::Triple::ArchType TargetArch, StringRef Path,
1394 const llvm::opt::ArgList &Args) {
1395 if (!isMipsArch(TargetArch))
1398 // Some MIPS toolchains put libraries and object files compiled
1399 // using different options in to the sub-directoris which names
1400 // reflects the flags used for compilation. For example sysroot
1401 // directory might looks like the following examples:
1404 // /lib <= crt*.o files compiled with '-mips32'
1407 // /lib <= crt*.o files compiled with '-mips16'
1410 // /lib <= crt*.o files compiled with '-mips16 -EL'
1415 // /lib <= crt*.o files compiled with '-mips32r2'
1418 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1421 // /lib <= crt*.o files compiled with '-mips32'
1423 // Unfortunately different toolchains use different and partially
1424 // overlapped naming schemes. So we have to make a trick for detection
1425 // of using toolchain. We lookup a path which unique for each toolchains.
1427 bool IsMentorToolChain = hasCrtBeginObj(Path + "/mips16/soft-float");
1428 bool IsFSFToolChain = hasCrtBeginObj(Path + "/mips32/mips16/sof");
1430 if (IsMentorToolChain && IsFSFToolChain)
1431 D.Diag(diag::err_drv_unknown_toolchain);
1433 if (IsMentorToolChain) {
1435 Suffix += "/mips16";
1436 else if (isMicroMips(Args))
1437 Suffix += "/micromips";
1439 if (isSoftFloatABI(Args))
1440 Suffix += "/soft-float";
1442 if (TargetArch == llvm::Triple::mipsel ||
1443 TargetArch == llvm::Triple::mips64el)
1445 } else if (IsFSFToolChain) {
1446 if (TargetArch == llvm::Triple::mips ||
1447 TargetArch == llvm::Triple::mipsel) {
1448 if (isMicroMips(Args))
1449 Suffix += "/micromips";
1450 else if (isMips32r2(Args))
1453 Suffix += "/mips32";
1456 Suffix += "/mips16";
1458 if (isMips64r2(Args))
1459 Suffix += hasMipsN32ABIArg(Args) ? "/mips64r2" : "/mips64r2/64";
1461 Suffix += hasMipsN32ABIArg(Args) ? "/mips64" : "/mips64/64";
1464 if (TargetArch == llvm::Triple::mipsel ||
1465 TargetArch == llvm::Triple::mips64el)
1468 if (isSoftFloatABI(Args))
1471 if (isMipsFP64(Args))
1474 if (isMipsNan2008(Args))
1475 Suffix += "/nan2008";
1479 if (!hasCrtBeginObj(Path + Suffix))
1483 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1484 llvm::Triple::ArchType TargetArch, const ArgList &Args,
1485 const std::string &LibDir, StringRef CandidateTriple,
1486 bool NeedsBiarchSuffix) {
1487 // There are various different suffixes involving the triple we
1488 // check for. We also record what is necessary to walk from each back
1489 // up to the lib directory.
1490 const std::string LibSuffixes[] = {
1491 "/gcc/" + CandidateTriple.str(),
1492 // Debian puts cross-compilers in gcc-cross
1493 "/gcc-cross/" + CandidateTriple.str(),
1494 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1496 // The Freescale PPC SDK has the gcc libraries in
1497 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1498 "/" + CandidateTriple.str(),
1500 // Ubuntu has a strange mis-matched pair of triples that this happens to
1502 // FIXME: It may be worthwhile to generalize this and look for a second
1504 "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1506 const std::string InstallSuffixes[] = {
1507 "/../../..", // gcc/
1508 "/../../..", // gcc-cross/
1509 "/../../../..", // <triple>/gcc/
1510 "/../..", // <triple>/
1511 "/../../../.." // i386-linux-gnu/gcc/<triple>/
1513 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1514 const unsigned NumLibSuffixes =
1515 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1516 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1517 StringRef LibSuffix = LibSuffixes[i];
1518 llvm::error_code EC;
1519 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1520 !EC && LI != LE; LI = LI.increment(EC)) {
1521 StringRef VersionText = llvm::sys::path::filename(LI->path());
1522 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1523 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1524 if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1525 continue; // Saw this path before; no need to look at it again.
1526 if (CandidateVersion.isOlderThan(4, 1, 1))
1528 if (CandidateVersion <= Version)
1531 std::string MIPSABIDirSuffix;
1532 findMIPSABIDirSuffix(MIPSABIDirSuffix, TargetArch, LI->path(), Args);
1534 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1535 // in what would normally be GCCInstallPath and put the 64-bit
1536 // libs in a subdirectory named 64. The simple logic we follow is that
1537 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1538 // we use that. If not, and if not a biarch triple alias, we look for
1539 // crtbegin.o without the subdirectory.
1541 std::string BiarchSuffix;
1542 if (findTargetBiarchSuffix(BiarchSuffix,
1543 LI->path() + MIPSABIDirSuffix,
1544 TargetArch, Args)) {
1545 GCCBiarchSuffix = BiarchSuffix;
1546 } else if (NeedsBiarchSuffix ||
1547 !hasCrtBeginObj(LI->path() + MIPSABIDirSuffix)) {
1550 GCCBiarchSuffix.clear();
1553 Version = CandidateVersion;
1554 GCCTriple.setTriple(CandidateTriple);
1555 // FIXME: We hack together the directory name here instead of
1556 // using LI to ensure stable path separators across Windows and
1558 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1559 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1560 GCCMIPSABIDirSuffix = MIPSABIDirSuffix;
1566 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1567 const ArgList &Args)
1568 : ToolChain(D, Triple, Args), GCCInstallation(getDriver(), Triple, Args) {
1569 getProgramPaths().push_back(getDriver().getInstalledDir());
1570 if (getDriver().getInstalledDir() != getDriver().Dir)
1571 getProgramPaths().push_back(getDriver().Dir);
1574 Generic_GCC::~Generic_GCC() {
1577 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
1579 case Action::PreprocessJobClass:
1581 Preprocess.reset(new tools::gcc::Preprocess(*this));
1582 return Preprocess.get();
1583 case Action::PrecompileJobClass:
1585 Precompile.reset(new tools::gcc::Precompile(*this));
1586 return Precompile.get();
1587 case Action::CompileJobClass:
1589 Compile.reset(new tools::gcc::Compile(*this));
1590 return Compile.get();
1592 return ToolChain::getTool(AC);
1596 Tool *Generic_GCC::buildAssembler() const {
1597 return new tools::gcc::Assemble(*this);
1600 Tool *Generic_GCC::buildLinker() const {
1601 return new tools::gcc::Link(*this);
1604 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
1605 // Print the information about how we detected the GCC installation.
1606 GCCInstallation.print(OS);
1609 bool Generic_GCC::IsUnwindTablesDefault() const {
1610 return getArch() == llvm::Triple::x86_64;
1613 bool Generic_GCC::isPICDefault() const {
1617 bool Generic_GCC::isPIEDefault() const {
1621 bool Generic_GCC::isPICDefaultForced() const {
1625 /// Hexagon Toolchain
1627 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) {
1629 // Locate the rest of the toolchain ...
1630 if (strlen(GCC_INSTALL_PREFIX))
1631 return std::string(GCC_INSTALL_PREFIX);
1633 std::string InstallRelDir = InstalledDir + "/../../gnu";
1634 if (llvm::sys::fs::exists(InstallRelDir))
1635 return InstallRelDir;
1637 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
1638 if (llvm::sys::fs::exists(PrefixRelDir))
1639 return PrefixRelDir;
1641 return InstallRelDir;
1644 static void GetHexagonLibraryPaths(
1645 const ArgList &Args,
1646 const std::string Ver,
1647 const std::string MarchString,
1648 const std::string &InstalledDir,
1649 ToolChain::path_list *LibPaths)
1651 bool buildingLib = Args.hasArg(options::OPT_shared);
1653 //----------------------------------------------------------------------------
1655 //----------------------------------------------------------------------------
1657 it = Args.filtered_begin(options::OPT_L),
1658 ie = Args.filtered_end();
1661 for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
1662 LibPaths->push_back((*it)->getValue(i));
1665 //----------------------------------------------------------------------------
1666 // Other standard paths
1667 //----------------------------------------------------------------------------
1668 const std::string MarchSuffix = "/" + MarchString;
1669 const std::string G0Suffix = "/G0";
1670 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
1671 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/";
1673 // lib/gcc/hexagon/...
1674 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
1676 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
1677 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
1679 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
1680 LibPaths->push_back(LibGCCHexagonDir + Ver);
1683 LibPaths->push_back(RootDir + "lib/gcc");
1686 std::string HexagonLibDir = RootDir + "hexagon/lib";
1688 LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
1689 LibPaths->push_back(HexagonLibDir + G0Suffix);
1691 LibPaths->push_back(HexagonLibDir + MarchSuffix);
1692 LibPaths->push_back(HexagonLibDir);
1695 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
1696 const ArgList &Args)
1697 : Linux(D, Triple, Args) {
1698 const std::string InstalledDir(getDriver().getInstalledDir());
1699 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir);
1701 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
1703 const std::string BinDir(GnuDir + "/bin");
1704 if (llvm::sys::fs::exists(BinDir))
1705 getProgramPaths().push_back(BinDir);
1707 // Determine version of GCC libraries and headers to use.
1708 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
1709 llvm::error_code ec;
1710 GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
1711 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
1712 !ec && di != de; di = di.increment(ec)) {
1713 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
1714 if (MaxVersion < cv)
1717 GCCLibAndIncVersion = MaxVersion;
1719 ToolChain::path_list *LibPaths= &getFilePaths();
1721 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
1722 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
1723 // support 'linux' we'll need to fix this up
1726 GetHexagonLibraryPaths(
1728 GetGCCLibAndIncVersion(),
1734 Hexagon_TC::~Hexagon_TC() {
1737 Tool *Hexagon_TC::buildAssembler() const {
1738 return new tools::hexagon::Assemble(*this);
1741 Tool *Hexagon_TC::buildLinker() const {
1742 return new tools::hexagon::Link(*this);
1745 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1746 ArgStringList &CC1Args) const {
1747 const Driver &D = getDriver();
1749 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
1750 DriverArgs.hasArg(options::OPT_nostdlibinc))
1753 std::string Ver(GetGCCLibAndIncVersion());
1754 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir);
1755 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
1756 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
1757 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
1758 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
1761 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1762 ArgStringList &CC1Args) const {
1764 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1765 DriverArgs.hasArg(options::OPT_nostdincxx))
1768 const Driver &D = getDriver();
1769 std::string Ver(GetGCCLibAndIncVersion());
1770 SmallString<128> IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir));
1772 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
1773 llvm::sys::path::append(IncludeDir, Ver);
1774 addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
1777 ToolChain::CXXStdlibType
1778 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
1779 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1781 return ToolChain::CST_Libstdcxx;
1783 StringRef Value = A->getValue();
1784 if (Value != "libstdc++") {
1785 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1786 << A->getAsString(Args);
1789 return ToolChain::CST_Libstdcxx;
1792 static int getHexagonVersion(const ArgList &Args) {
1793 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
1794 // Select the default CPU (v4) if none was given.
1798 // FIXME: produce errors if we cannot parse the version.
1799 StringRef WhichHexagon = A->getValue();
1800 if (WhichHexagon.startswith("hexagonv")) {
1802 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
1805 if (WhichHexagon.startswith("v")) {
1807 if (!WhichHexagon.substr(1).getAsInteger(10, Val))
1811 // FIXME: should probably be an error.
1815 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
1817 int V = getHexagonVersion(Args);
1818 // FIXME: We don't support versions < 4. We should error on them.
1821 llvm_unreachable("Unexpected version");
1836 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1837 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1838 /// Currently does not support anything else but compilation.
1840 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
1841 const ArgList &Args)
1842 : ToolChain(D, Triple, Args) {
1843 // Path mangling to find libexec
1844 std::string Path(getDriver().Dir);
1846 Path += "/../libexec";
1847 getProgramPaths().push_back(Path);
1850 TCEToolChain::~TCEToolChain() {
1853 bool TCEToolChain::IsMathErrnoDefault() const {
1857 bool TCEToolChain::isPICDefault() const {
1861 bool TCEToolChain::isPIEDefault() const {
1865 bool TCEToolChain::isPICDefaultForced() const {
1869 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1871 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1872 : Generic_ELF(D, Triple, Args) {
1873 getFilePaths().push_back(getDriver().Dir + "/../lib");
1874 getFilePaths().push_back("/usr/lib");
1877 Tool *OpenBSD::buildAssembler() const {
1878 return new tools::openbsd::Assemble(*this);
1881 Tool *OpenBSD::buildLinker() const {
1882 return new tools::openbsd::Link(*this);
1885 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1887 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1888 : Generic_ELF(D, Triple, Args) {
1889 getFilePaths().push_back(getDriver().Dir + "/../lib");
1890 getFilePaths().push_back("/usr/lib");
1893 Tool *Bitrig::buildAssembler() const {
1894 return new tools::bitrig::Assemble(*this);
1897 Tool *Bitrig::buildLinker() const {
1898 return new tools::bitrig::Link(*this);
1901 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1902 ArgStringList &CC1Args) const {
1903 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1904 DriverArgs.hasArg(options::OPT_nostdincxx))
1907 switch (GetCXXStdlibType(DriverArgs)) {
1908 case ToolChain::CST_Libcxx:
1909 addSystemInclude(DriverArgs, CC1Args,
1910 getDriver().SysRoot + "/usr/include/c++/");
1912 case ToolChain::CST_Libstdcxx:
1913 addSystemInclude(DriverArgs, CC1Args,
1914 getDriver().SysRoot + "/usr/include/c++/stdc++");
1915 addSystemInclude(DriverArgs, CC1Args,
1916 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1918 StringRef Triple = getTriple().str();
1919 if (Triple.startswith("amd64"))
1920 addSystemInclude(DriverArgs, CC1Args,
1921 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1924 addSystemInclude(DriverArgs, CC1Args,
1925 getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1931 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1932 ArgStringList &CmdArgs) const {
1933 switch (GetCXXStdlibType(Args)) {
1934 case ToolChain::CST_Libcxx:
1935 CmdArgs.push_back("-lc++");
1936 CmdArgs.push_back("-lcxxrt");
1937 // Include supc++ to provide Unwind until provided by libcxx.
1938 CmdArgs.push_back("-lgcc");
1940 case ToolChain::CST_Libstdcxx:
1941 CmdArgs.push_back("-lstdc++");
1946 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1948 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1949 : Generic_ELF(D, Triple, Args) {
1951 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1952 // back to '/usr/lib' if it doesn't exist.
1953 if ((Triple.getArch() == llvm::Triple::x86 ||
1954 Triple.getArch() == llvm::Triple::ppc) &&
1955 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1956 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1958 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1961 ToolChain::CXXStdlibType
1962 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
1963 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
1964 StringRef Value = A->getValue();
1965 if (Value == "libstdc++")
1966 return ToolChain::CST_Libstdcxx;
1967 if (Value == "libc++")
1968 return ToolChain::CST_Libcxx;
1970 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1971 << A->getAsString(Args);
1973 if (getTriple().getOSMajorVersion() >= 10)
1974 return ToolChain::CST_Libcxx;
1975 return ToolChain::CST_Libstdcxx;
1978 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1979 ArgStringList &CC1Args) const {
1980 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1981 DriverArgs.hasArg(options::OPT_nostdincxx))
1984 switch (GetCXXStdlibType(DriverArgs)) {
1985 case ToolChain::CST_Libcxx:
1986 addSystemInclude(DriverArgs, CC1Args,
1987 getDriver().SysRoot + "/usr/include/c++/v1");
1989 case ToolChain::CST_Libstdcxx:
1990 addSystemInclude(DriverArgs, CC1Args,
1991 getDriver().SysRoot + "/usr/include/c++/4.2");
1992 addSystemInclude(DriverArgs, CC1Args,
1993 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
1998 Tool *FreeBSD::buildAssembler() const {
1999 return new tools::freebsd::Assemble(*this);
2002 Tool *FreeBSD::buildLinker() const {
2003 return new tools::freebsd::Link(*this);
2006 bool FreeBSD::UseSjLjExceptions() const {
2007 // FreeBSD uses SjLj exceptions on ARM oabi.
2008 switch (getTriple().getEnvironment()) {
2009 case llvm::Triple::GNUEABI:
2010 case llvm::Triple::EABI:
2014 return (getTriple().getArch() == llvm::Triple::arm ||
2015 getTriple().getArch() == llvm::Triple::thumb);
2019 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2021 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2022 : Generic_ELF(D, Triple, Args) {
2024 if (getDriver().UseStdLib) {
2025 // When targeting a 32-bit platform, try the special directory used on
2026 // 64-bit hosts, and only fall back to the main library directory if that
2028 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2029 // what all logic is needed to emulate the '=' prefix here.
2030 if (Triple.getArch() == llvm::Triple::x86)
2031 getFilePaths().push_back("=/usr/lib/i386");
2033 getFilePaths().push_back("=/usr/lib");
2037 Tool *NetBSD::buildAssembler() const {
2038 return new tools::netbsd::Assemble(*this);
2041 Tool *NetBSD::buildLinker() const {
2042 return new tools::netbsd::Link(*this);
2045 ToolChain::CXXStdlibType
2046 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2047 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2048 StringRef Value = A->getValue();
2049 if (Value == "libstdc++")
2050 return ToolChain::CST_Libstdcxx;
2051 if (Value == "libc++")
2052 return ToolChain::CST_Libcxx;
2054 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2055 << A->getAsString(Args);
2058 unsigned Major, Minor, Micro;
2059 getTriple().getOSVersion(Major, Minor, Micro);
2060 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
2061 if (getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64)
2062 return ToolChain::CST_Libcxx;
2064 return ToolChain::CST_Libstdcxx;
2067 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2068 ArgStringList &CC1Args) const {
2069 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2070 DriverArgs.hasArg(options::OPT_nostdincxx))
2073 switch (GetCXXStdlibType(DriverArgs)) {
2074 case ToolChain::CST_Libcxx:
2075 addSystemInclude(DriverArgs, CC1Args,
2076 getDriver().SysRoot + "/usr/include/c++/");
2078 case ToolChain::CST_Libstdcxx:
2079 addSystemInclude(DriverArgs, CC1Args,
2080 getDriver().SysRoot + "/usr/include/g++");
2081 addSystemInclude(DriverArgs, CC1Args,
2082 getDriver().SysRoot + "/usr/include/g++/backward");
2087 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2089 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2090 : Generic_ELF(D, Triple, Args) {
2091 getFilePaths().push_back(getDriver().Dir + "/../lib");
2092 getFilePaths().push_back("/usr/lib");
2095 Tool *Minix::buildAssembler() const {
2096 return new tools::minix::Assemble(*this);
2099 Tool *Minix::buildLinker() const {
2100 return new tools::minix::Link(*this);
2103 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
2105 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
2106 const ArgList &Args)
2107 : Generic_GCC(D, Triple, Args) {
2109 getProgramPaths().push_back(getDriver().getInstalledDir());
2110 if (getDriver().getInstalledDir() != getDriver().Dir)
2111 getProgramPaths().push_back(getDriver().Dir);
2113 getFilePaths().push_back(getDriver().Dir + "/../lib");
2114 getFilePaths().push_back("/usr/lib");
2115 getFilePaths().push_back("/usr/sfw/lib");
2116 getFilePaths().push_back("/opt/gcc4/lib");
2117 getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
2121 Tool *AuroraUX::buildAssembler() const {
2122 return new tools::auroraux::Assemble(*this);
2125 Tool *AuroraUX::buildLinker() const {
2126 return new tools::auroraux::Link(*this);
2129 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2131 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2132 const ArgList &Args)
2133 : Generic_GCC(D, Triple, Args) {
2135 getProgramPaths().push_back(getDriver().getInstalledDir());
2136 if (getDriver().getInstalledDir() != getDriver().Dir)
2137 getProgramPaths().push_back(getDriver().Dir);
2139 getFilePaths().push_back(getDriver().Dir + "/../lib");
2140 getFilePaths().push_back("/usr/lib");
2143 Tool *Solaris::buildAssembler() const {
2144 return new tools::solaris::Assemble(*this);
2147 Tool *Solaris::buildLinker() const {
2148 return new tools::solaris::Link(*this);
2151 /// Distribution (very bare-bones at the moment).
2181 static bool IsRedhat(enum Distro Distro) {
2182 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
2185 static bool IsOpenSUSE(enum Distro Distro) {
2186 return Distro == OpenSUSE;
2189 static bool IsDebian(enum Distro Distro) {
2190 return Distro >= DebianLenny && Distro <= DebianJessie;
2193 static bool IsUbuntu(enum Distro Distro) {
2194 return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
2197 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2198 OwningPtr<llvm::MemoryBuffer> File;
2199 if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
2200 StringRef Data = File.get()->getBuffer();
2201 SmallVector<StringRef, 8> Lines;
2202 Data.split(Lines, "\n");
2203 Distro Version = UnknownDistro;
2204 for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2205 if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2206 Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2207 .Case("hardy", UbuntuHardy)
2208 .Case("intrepid", UbuntuIntrepid)
2209 .Case("jaunty", UbuntuJaunty)
2210 .Case("karmic", UbuntuKarmic)
2211 .Case("lucid", UbuntuLucid)
2212 .Case("maverick", UbuntuMaverick)
2213 .Case("natty", UbuntuNatty)
2214 .Case("oneiric", UbuntuOneiric)
2215 .Case("precise", UbuntuPrecise)
2216 .Case("quantal", UbuntuQuantal)
2217 .Case("raring", UbuntuRaring)
2218 .Case("saucy", UbuntuSaucy)
2219 .Case("trusty", UbuntuTrusty)
2220 .Default(UnknownDistro);
2224 if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
2225 StringRef Data = File.get()->getBuffer();
2226 if (Data.startswith("Fedora release"))
2228 else if (Data.startswith("Red Hat Enterprise Linux") &&
2229 Data.find("release 6") != StringRef::npos)
2231 else if ((Data.startswith("Red Hat Enterprise Linux") ||
2232 Data.startswith("CentOS")) &&
2233 Data.find("release 5") != StringRef::npos)
2235 else if ((Data.startswith("Red Hat Enterprise Linux") ||
2236 Data.startswith("CentOS")) &&
2237 Data.find("release 4") != StringRef::npos)
2239 return UnknownDistro;
2242 if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
2243 StringRef Data = File.get()->getBuffer();
2246 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2247 return DebianSqueeze;
2248 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
2249 return DebianWheezy;
2250 else if (Data.startswith("jessie/sid") || Data[0] == '8')
2251 return DebianJessie;
2252 return UnknownDistro;
2255 if (llvm::sys::fs::exists("/etc/SuSE-release"))
2258 if (llvm::sys::fs::exists("/etc/exherbo-release"))
2261 if (llvm::sys::fs::exists("/etc/arch-release"))
2264 return UnknownDistro;
2267 /// \brief Get our best guess at the multiarch triple for a target.
2269 /// Debian-based systems are starting to use a multiarch setup where they use
2270 /// a target-triple directory in the library and header search paths.
2271 /// Unfortunately, this triple does not align with the vanilla target triple,
2272 /// so we provide a rough mapping here.
2273 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2274 StringRef SysRoot) {
2275 // For most architectures, just use whatever we have rather than trying to be
2277 switch (TargetTriple.getArch()) {
2279 return TargetTriple.str();
2281 // We use the existence of '/lib/<triple>' as a directory to detect some
2282 // common linux triples that don't quite match the Clang triple for both
2283 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2284 // regardless of what the actual target triple is.
2285 case llvm::Triple::arm:
2286 case llvm::Triple::thumb:
2287 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2288 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2289 return "arm-linux-gnueabihf";
2291 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2292 return "arm-linux-gnueabi";
2294 return TargetTriple.str();
2295 case llvm::Triple::x86:
2296 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2297 return "i386-linux-gnu";
2298 return TargetTriple.str();
2299 case llvm::Triple::x86_64:
2300 if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2301 return "x86_64-linux-gnu";
2302 return TargetTriple.str();
2303 case llvm::Triple::aarch64:
2304 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2305 return "aarch64-linux-gnu";
2306 return TargetTriple.str();
2307 case llvm::Triple::mips:
2308 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2309 return "mips-linux-gnu";
2310 return TargetTriple.str();
2311 case llvm::Triple::mipsel:
2312 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2313 return "mipsel-linux-gnu";
2314 return TargetTriple.str();
2315 case llvm::Triple::ppc:
2316 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2317 return "powerpc-linux-gnuspe";
2318 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2319 return "powerpc-linux-gnu";
2320 return TargetTriple.str();
2321 case llvm::Triple::ppc64:
2322 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2323 return "powerpc64-linux-gnu";
2324 case llvm::Triple::ppc64le:
2325 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
2326 return "powerpc64le-linux-gnu";
2327 return TargetTriple.str();
2331 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2332 if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2335 static StringRef getMultilibDir(const llvm::Triple &Triple,
2336 const ArgList &Args) {
2337 if (isMipsArch(Triple.getArch())) {
2338 // lib32 directory has a special meaning on MIPS targets.
2339 // It contains N32 ABI binaries. Use this folder if produce
2340 // code for N32 ABI only.
2341 if (hasMipsN32ABIArg(Args))
2343 return Triple.isArch32Bit() ? "lib" : "lib64";
2346 // It happens that only x86 and PPC use the 'lib32' variant of multilib, and
2347 // using that variant while targeting other architectures causes problems
2348 // because the libraries are laid out in shared system roots that can't cope
2349 // with a 'lib32' multilib search path being considered. So we only enable
2350 // them when we know we may need it.
2352 // FIXME: This is a bit of a hack. We should really unify this code for
2353 // reasoning about multilib spellings with the lib dir spellings in the
2354 // GCCInstallationDetector, but that is a more significant refactoring.
2355 if (Triple.getArch() == llvm::Triple::x86 ||
2356 Triple.getArch() == llvm::Triple::ppc)
2359 return Triple.isArch32Bit() ? "lib" : "lib64";
2362 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2363 : Generic_ELF(D, Triple, Args) {
2364 llvm::Triple::ArchType Arch = Triple.getArch();
2365 std::string SysRoot = computeSysRoot();
2367 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2368 // least) put various tools in a triple-prefixed directory off of the parent
2369 // of the GCC installation. We use the GCC triple here to ensure that we end
2370 // up with tools that support the same amount of cross compiling as the
2371 // detected GCC installation. For example, if we find a GCC installation
2372 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2373 // used to target i386.
2374 // FIXME: This seems unlikely to be Linux-specific.
2375 ToolChain::path_list &PPaths = getProgramPaths();
2376 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2377 GCCInstallation.getTriple().str() + "/bin").str());
2379 Linker = GetProgramPath("ld");
2381 Distro Distro = DetectDistro(Arch);
2383 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2384 ExtraOpts.push_back("-z");
2385 ExtraOpts.push_back("relro");
2388 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2389 ExtraOpts.push_back("-X");
2391 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2392 const bool IsMips = isMipsArch(Arch);
2394 if (IsMips && !SysRoot.empty())
2395 ExtraOpts.push_back("--sysroot=" + SysRoot);
2397 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2398 // and the MIPS ABI require .dynsym to be sorted in different ways.
2399 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2400 // ABI requires a mapping between the GOT and the symbol table.
2401 // Android loader does not support .gnu.hash.
2402 if (!IsMips && !IsAndroid) {
2403 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2404 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2405 ExtraOpts.push_back("--hash-style=gnu");
2407 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2408 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2409 ExtraOpts.push_back("--hash-style=both");
2412 if (IsRedhat(Distro))
2413 ExtraOpts.push_back("--no-add-needed");
2415 if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2416 Distro == DebianJessie || IsOpenSUSE(Distro) ||
2417 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2418 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2419 ExtraOpts.push_back("--build-id");
2421 if (IsOpenSUSE(Distro))
2422 ExtraOpts.push_back("--enable-new-dtags");
2424 // The selection of paths to try here is designed to match the patterns which
2425 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2426 // This was determined by running GCC in a fake filesystem, creating all
2427 // possible permutations of these directories, and seeing which ones it added
2428 // to the link paths.
2429 path_list &Paths = getFilePaths();
2431 const std::string Multilib = getMultilibDir(Triple, Args);
2432 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2434 // Add the multilib suffixed paths where they are available.
2435 if (GCCInstallation.isValid()) {
2436 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2437 const std::string &LibPath = GCCInstallation.getParentLibPath();
2439 // Sourcery CodeBench MIPS toolchain holds some libraries under
2440 // a biarch-like suffix of the GCC installation.
2442 // FIXME: It would be cleaner to model this as a variant of bi-arch. IE,
2443 // instead of a '64' biarch suffix it would be 'el' or something.
2444 if (IsAndroid && IsMips && isMips32r2(Args)) {
2445 assert(GCCInstallation.getBiarchSuffix().empty() &&
2446 "Unexpected bi-arch suffix");
2447 addPathIfExists(GCCInstallation.getInstallPath() + "/mips-r2", Paths);
2449 addPathIfExists((GCCInstallation.getInstallPath() +
2450 GCCInstallation.getMIPSABIDirSuffix() +
2451 GCCInstallation.getBiarchSuffix()),
2455 // GCC cross compiling toolchains will install target libraries which ship
2456 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
2457 // any part of the GCC installation in
2458 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
2459 // debatable, but is the reality today. We need to search this tree even
2460 // when we have a sysroot somewhere else. It is the responsibility of
2461 // whomever is doing the cross build targetting a sysroot using a GCC
2462 // installation that is *not* within the system root to ensure two things:
2464 // 1) Any DSOs that are linked in from this tree or from the install path
2465 // above must be preasant on the system root and found via an
2466 // appropriate rpath.
2467 // 2) There must not be libraries installed into
2468 // <prefix>/<triple>/<libdir> unless they should be preferred over
2469 // those within the system root.
2471 // Note that this matches the GCC behavior. See the below comment for where
2472 // Clang diverges from GCC's behavior.
2473 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib +
2474 GCCInstallation.getMIPSABIDirSuffix(),
2477 // If the GCC installation we found is inside of the sysroot, we want to
2478 // prefer libraries installed in the parent prefix of the GCC installation.
2479 // It is important to *not* use these paths when the GCC installation is
2480 // outside of the system root as that can pick up unintended libraries.
2481 // This usually happens when there is an external cross compiler on the
2482 // host system, and a more minimal sysroot available that is the target of
2483 // the cross. Note that GCC does include some of these directories in some
2484 // configurations but this seems somewhere between questionable and simply
2486 if (StringRef(LibPath).startswith(SysRoot)) {
2487 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2488 addPathIfExists(LibPath + "/../" + Multilib, Paths);
2491 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2492 addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2493 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2494 addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2496 // Try walking via the GCC triple path in case of biarch or multiarch GCC
2497 // installations with strange symlinks.
2498 if (GCCInstallation.isValid()) {
2499 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2500 "/../../" + Multilib, Paths);
2502 // Add the non-multilib suffixed paths (if potentially different).
2503 const std::string &LibPath = GCCInstallation.getParentLibPath();
2504 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2505 if (!GCCInstallation.getBiarchSuffix().empty())
2506 addPathIfExists(GCCInstallation.getInstallPath() +
2507 GCCInstallation.getMIPSABIDirSuffix(), Paths);
2509 // See comments above on the multilib variant for details of why this is
2510 // included even from outside the sysroot.
2511 addPathIfExists(LibPath + "/../" + GCCTriple.str() +
2512 "/lib" + GCCInstallation.getMIPSABIDirSuffix(), Paths);
2514 // See comments above on the multilib variant for details of why this is
2515 // only included from within the sysroot.
2516 if (StringRef(LibPath).startswith(SysRoot))
2517 addPathIfExists(LibPath, Paths);
2519 addPathIfExists(SysRoot + "/lib", Paths);
2520 addPathIfExists(SysRoot + "/usr/lib", Paths);
2523 bool FreeBSD::HasNativeLLVMSupport() const {
2527 bool Linux::HasNativeLLVMSupport() const {
2531 Tool *Linux::buildLinker() const {
2532 return new tools::gnutools::Link(*this);
2535 Tool *Linux::buildAssembler() const {
2536 return new tools::gnutools::Assemble(*this);
2539 void Linux::addClangTargetOptions(const ArgList &DriverArgs,
2540 ArgStringList &CC1Args) const {
2541 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2542 bool UseInitArrayDefault =
2543 !V.isOlderThan(4, 7, 0) ||
2544 getTriple().getArch() == llvm::Triple::aarch64 ||
2545 getTriple().getEnvironment() == llvm::Triple::Android;
2546 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2547 options::OPT_fno_use_init_array,
2548 UseInitArrayDefault))
2549 CC1Args.push_back("-fuse-init-array");
2552 std::string Linux::computeSysRoot() const {
2553 if (!getDriver().SysRoot.empty())
2554 return getDriver().SysRoot;
2556 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
2557 return std::string();
2559 // Standalone MIPS toolchains use different names for sysroot folder
2560 // and put it into different places. Here we try to check some known
2563 const StringRef InstallDir = GCCInstallation.getInstallPath();
2564 const StringRef TripleStr = GCCInstallation.getTriple().str();
2565 const StringRef MIPSABIDirSuffix = GCCInstallation.getMIPSABIDirSuffix();
2567 std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
2568 MIPSABIDirSuffix).str();
2570 if (llvm::sys::fs::exists(Path))
2573 Path = (InstallDir + "/../../../../sysroot" + MIPSABIDirSuffix).str();
2575 if (llvm::sys::fs::exists(Path))
2578 return std::string();
2581 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2582 ArgStringList &CC1Args) const {
2583 const Driver &D = getDriver();
2584 std::string SysRoot = computeSysRoot();
2586 if (DriverArgs.hasArg(options::OPT_nostdinc))
2589 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2590 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
2592 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2593 SmallString<128> P(D.ResourceDir);
2594 llvm::sys::path::append(P, "include");
2595 addSystemInclude(DriverArgs, CC1Args, P.str());
2598 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2601 // Check for configure-time C include directories.
2602 StringRef CIncludeDirs(C_INCLUDE_DIRS);
2603 if (CIncludeDirs != "") {
2604 SmallVector<StringRef, 5> dirs;
2605 CIncludeDirs.split(dirs, ":");
2606 for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2608 StringRef Prefix = llvm::sys::path::is_absolute(*I) ? SysRoot : "";
2609 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2614 // Lacking those, try to detect the correct set of system includes for the
2617 // Sourcery CodeBench and modern FSF Mips toolchains put extern C
2618 // system includes under three additional directories.
2619 if (GCCInstallation.isValid() && isMipsArch(getTriple().getArch())) {
2620 addExternCSystemIncludeIfExists(
2621 DriverArgs, CC1Args, GCCInstallation.getInstallPath() + "/include");
2623 addExternCSystemIncludeIfExists(
2624 DriverArgs, CC1Args,
2625 GCCInstallation.getInstallPath() + "/../../../../" +
2626 GCCInstallation.getTriple().str() + "/libc/usr/include");
2628 addExternCSystemIncludeIfExists(
2629 DriverArgs, CC1Args,
2630 GCCInstallation.getInstallPath() + "/../../../../sysroot/usr/include");
2633 // Implement generic Debian multiarch support.
2634 const StringRef X86_64MultiarchIncludeDirs[] = {
2635 "/usr/include/x86_64-linux-gnu",
2637 // FIXME: These are older forms of multiarch. It's not clear that they're
2638 // in use in any released version of Debian, so we should consider
2640 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
2642 const StringRef X86MultiarchIncludeDirs[] = {
2643 "/usr/include/i386-linux-gnu",
2645 // FIXME: These are older forms of multiarch. It's not clear that they're
2646 // in use in any released version of Debian, so we should consider
2648 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
2649 "/usr/include/i486-linux-gnu"
2651 const StringRef AArch64MultiarchIncludeDirs[] = {
2652 "/usr/include/aarch64-linux-gnu"
2654 const StringRef ARMMultiarchIncludeDirs[] = {
2655 "/usr/include/arm-linux-gnueabi"
2657 const StringRef ARMHFMultiarchIncludeDirs[] = {
2658 "/usr/include/arm-linux-gnueabihf"
2660 const StringRef MIPSMultiarchIncludeDirs[] = {
2661 "/usr/include/mips-linux-gnu"
2663 const StringRef MIPSELMultiarchIncludeDirs[] = {
2664 "/usr/include/mipsel-linux-gnu"
2666 const StringRef PPCMultiarchIncludeDirs[] = {
2667 "/usr/include/powerpc-linux-gnu"
2669 const StringRef PPC64MultiarchIncludeDirs[] = {
2670 "/usr/include/powerpc64-linux-gnu"
2672 ArrayRef<StringRef> MultiarchIncludeDirs;
2673 if (getTriple().getArch() == llvm::Triple::x86_64) {
2674 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2675 } else if (getTriple().getArch() == llvm::Triple::x86) {
2676 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2677 } else if (getTriple().getArch() == llvm::Triple::aarch64) {
2678 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
2679 } else if (getTriple().getArch() == llvm::Triple::arm) {
2680 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2681 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2683 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2684 } else if (getTriple().getArch() == llvm::Triple::mips) {
2685 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2686 } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2687 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2688 } else if (getTriple().getArch() == llvm::Triple::ppc) {
2689 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2690 } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2691 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2693 for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2694 E = MultiarchIncludeDirs.end();
2696 if (llvm::sys::fs::exists(SysRoot + *I)) {
2697 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + *I);
2702 if (getTriple().getOS() == llvm::Triple::RTEMS)
2705 // Add an include of '/include' directly. This isn't provided by default by
2706 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2707 // add even when Clang is acting as-if it were a system compiler.
2708 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
2710 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
2713 /// \brief Helper to add the three variant paths for a libstdc++ installation.
2714 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2715 const ArgList &DriverArgs,
2716 ArgStringList &CC1Args) {
2717 if (!llvm::sys::fs::exists(Base))
2719 addSystemInclude(DriverArgs, CC1Args, Base);
2720 addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2721 addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2725 /// \brief Helper to add an extra variant path for an (Ubuntu) multilib
2726 /// libstdc++ installation.
2727 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
2728 Twine TargetArchDir,
2730 Twine MIPSABIDirSuffix,
2731 const ArgList &DriverArgs,
2732 ArgStringList &CC1Args) {
2733 if (!addLibStdCXXIncludePaths(Base + Suffix,
2734 TargetArchDir + MIPSABIDirSuffix + BiarchSuffix,
2735 DriverArgs, CC1Args))
2738 addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix
2739 + MIPSABIDirSuffix + BiarchSuffix);
2743 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2744 ArgStringList &CC1Args) const {
2745 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2746 DriverArgs.hasArg(options::OPT_nostdincxx))
2749 // Check if libc++ has been enabled and provide its include paths if so.
2750 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2751 // libc++ is always installed at a fixed path on Linux currently.
2752 addSystemInclude(DriverArgs, CC1Args,
2753 getDriver().SysRoot + "/usr/include/c++/v1");
2757 // We need a detected GCC installation on Linux to provide libstdc++'s
2758 // headers. We handled the libc++ case above.
2759 if (!GCCInstallation.isValid())
2762 // By default, look for the C++ headers in an include directory adjacent to
2763 // the lib directory of the GCC installation. Note that this is expect to be
2764 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2765 StringRef LibDir = GCCInstallation.getParentLibPath();
2766 StringRef InstallDir = GCCInstallation.getInstallPath();
2767 StringRef TripleStr = GCCInstallation.getTriple().str();
2768 StringRef MIPSABIDirSuffix = GCCInstallation.getMIPSABIDirSuffix();
2769 StringRef BiarchSuffix = GCCInstallation.getBiarchSuffix();
2770 const GCCVersion &Version = GCCInstallation.getVersion();
2772 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
2773 "/c++/" + Version.Text, TripleStr, BiarchSuffix,
2774 MIPSABIDirSuffix, DriverArgs, CC1Args))
2777 const std::string IncludePathCandidates[] = {
2778 // Gentoo is weird and places its headers inside the GCC install, so if the
2779 // first attempt to find the headers fails, try these patterns.
2780 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
2782 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
2783 // Android standalone toolchain has C++ headers in yet another place.
2784 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
2785 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2786 // without a subdirectory corresponding to the gcc version.
2787 LibDir.str() + "/../include/c++",
2790 for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2791 if (addLibStdCXXIncludePaths(IncludePathCandidates[i],
2792 TripleStr + MIPSABIDirSuffix + BiarchSuffix,
2793 DriverArgs, CC1Args))
2798 bool Linux::isPIEDefault() const {
2799 return getSanitizerArgs().hasZeroBaseShadow();
2802 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2804 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2805 : Generic_ELF(D, Triple, Args) {
2807 // Path mangling to find libexec
2808 getProgramPaths().push_back(getDriver().getInstalledDir());
2809 if (getDriver().getInstalledDir() != getDriver().Dir)
2810 getProgramPaths().push_back(getDriver().Dir);
2812 getFilePaths().push_back(getDriver().Dir + "/../lib");
2813 getFilePaths().push_back("/usr/lib");
2814 if (llvm::sys::fs::exists("/usr/lib/gcc47"))
2815 getFilePaths().push_back("/usr/lib/gcc47");
2817 getFilePaths().push_back("/usr/lib/gcc44");
2820 Tool *DragonFly::buildAssembler() const {
2821 return new tools::dragonfly::Assemble(*this);
2824 Tool *DragonFly::buildLinker() const {
2825 return new tools::dragonfly::Link(*this);
2829 /// XCore tool chain
2830 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
2831 const ArgList &Args) : ToolChain(D, Triple, Args) {
2832 // ProgramPaths are found via 'PATH' environment variable.
2835 Tool *XCore::buildAssembler() const {
2836 return new tools::XCore::Assemble(*this);
2839 Tool *XCore::buildLinker() const {
2840 return new tools::XCore::Link(*this);
2843 bool XCore::isPICDefault() const {
2847 bool XCore::isPIEDefault() const {
2851 bool XCore::isPICDefaultForced() const {
2855 bool XCore::SupportsProfiling() const {
2859 bool XCore::hasBlocksRuntime() const {
2864 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2865 ArgStringList &CC1Args) const {
2866 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2867 DriverArgs.hasArg(options::OPT_nostdlibinc))
2869 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
2870 SmallVector<StringRef, 4> Dirs;
2871 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
2872 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
2873 ArrayRef<StringRef> DirVec(Dirs);
2874 addSystemIncludes(DriverArgs, CC1Args, DirVec);
2878 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2879 llvm::opt::ArgStringList &CC1Args) const {
2880 CC1Args.push_back("-nostdsysteminc");
2883 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2884 ArgStringList &CC1Args) const {
2885 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2886 DriverArgs.hasArg(options::OPT_nostdlibinc))
2888 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
2889 SmallVector<StringRef, 4> Dirs;
2890 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
2891 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
2892 ArrayRef<StringRef> DirVec(Dirs);
2893 addSystemIncludes(DriverArgs, CC1Args, DirVec);
2897 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
2898 ArgStringList &CmdArgs) const {
2899 // We don't output any lib args. This is handled by xcc.