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"
12 #include "clang/Driver/Arg.h"
13 #include "clang/Driver/ArgList.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/OptTable.h"
18 #include "clang/Driver/Option.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Basic/ObjCRuntime.h"
21 #include "clang/Basic/Version.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/system_error.h"
34 #include "SanitizerArgs.h"
36 #include <cstdlib> // ::getenv
38 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
40 using namespace clang::driver;
41 using namespace clang::driver::toolchains;
42 using namespace clang;
44 /// Darwin - Darwin tool chain for i386 and x86_64.
46 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
47 : ToolChain(D, Triple), TargetInitialized(false)
49 // Compute the initial Darwin version from the triple
50 unsigned Major, Minor, Micro;
51 if (!Triple.getMacOSXVersion(Major, Minor, Micro))
52 getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
54 llvm::raw_string_ostream(MacosxVersionMin)
55 << Major << '.' << Minor << '.' << Micro;
57 // FIXME: DarwinVersion is only used to find GCC's libexec directory.
58 // It should be removed when we stop supporting that.
59 DarwinVersion[0] = Minor + 4;
60 DarwinVersion[1] = Micro;
63 // Compute the initial iOS version from the triple
64 Triple.getiOSVersion(Major, Minor, Micro);
65 llvm::raw_string_ostream(iOSVersionMin)
66 << Major << '.' << Minor << '.' << Micro;
69 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
70 types::ID Ty = types::lookupTypeForExtension(Ext);
72 // Darwin always preprocesses assembly files (unless -x is used explicitly).
73 if (Ty == types::TY_PP_Asm)
79 bool Darwin::HasNativeLLVMSupport() const {
83 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
84 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
85 if (isTargetIPhoneOS())
86 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
88 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
89 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
92 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
93 bool Darwin::hasBlocksRuntime() const {
94 if (isTargetIPhoneOS())
95 return !isIPhoneOSVersionLT(3, 2);
97 return !isMacosxVersionLT(10, 6);
100 static const char *GetArmArchForMArch(StringRef Value) {
101 return llvm::StringSwitch<const char*>(Value)
102 .Case("armv6k", "armv6")
103 .Case("armv5tej", "armv5")
104 .Case("xscale", "xscale")
105 .Case("armv4t", "armv4t")
106 .Case("armv7", "armv7")
107 .Cases("armv7a", "armv7-a", "armv7")
108 .Cases("armv7r", "armv7-r", "armv7")
109 .Cases("armv7m", "armv7-m", "armv7")
110 .Cases("armv7f", "armv7-f", "armv7f")
111 .Cases("armv7k", "armv7-k", "armv7k")
112 .Cases("armv7s", "armv7-s", "armv7s")
116 static const char *GetArmArchForMCpu(StringRef Value) {
117 return llvm::StringSwitch<const char *>(Value)
118 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
119 .Cases("arm10e", "arm10tdmi", "armv5")
120 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
121 .Case("xscale", "xscale")
122 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s",
123 "arm1176jzf-s", "cortex-m0", "armv6")
124 .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "cortex-a15",
126 .Case("cortex-a9-mp", "armv7f")
127 .Case("swift", "armv7s")
131 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
132 switch (getTriple().getArch()) {
134 return getArchName();
136 case llvm::Triple::thumb:
137 case llvm::Triple::arm: {
138 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
139 if (const char *Arch = GetArmArchForMArch(A->getValue()))
142 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
143 if (const char *Arch = GetArmArchForMCpu(A->getValue()))
152 // Free tool implementations.
153 for (llvm::DenseMap<unsigned, Tool*>::iterator
154 it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
158 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
159 types::ID InputType) const {
160 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
162 // If the target isn't initialized (e.g., an unknown Darwin platform, return
163 // the default triple).
164 if (!isTargetInitialized())
165 return Triple.getTriple();
168 Str += isTargetIPhoneOS() ? "ios" : "macosx";
169 Str += getTargetVersion().getAsString();
170 Triple.setOSName(Str);
172 return Triple.getTriple();
175 void Generic_ELF::anchor() {}
177 Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
178 const ActionList &Inputs) const {
179 Action::ActionClass Key = JA.getKind();
181 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
182 // FIXME: This seems like a hacky way to choose clang frontend.
183 Key = Action::AnalyzeJobClass;
186 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
187 options::OPT_no_integrated_as,
188 IsIntegratedAssemblerDefault());
190 Tool *&T = Tools[Key];
193 case Action::InputClass:
194 case Action::BindArchClass:
195 llvm_unreachable("Invalid tool kind.");
196 case Action::PreprocessJobClass:
197 T = new tools::darwin::Preprocess(*this); break;
198 case Action::AnalyzeJobClass:
199 case Action::MigrateJobClass:
200 T = new tools::Clang(*this); break;
201 case Action::PrecompileJobClass:
202 case Action::CompileJobClass:
203 T = new tools::darwin::Compile(*this); break;
204 case Action::AssembleJobClass: {
206 T = new tools::ClangAs(*this);
208 T = new tools::darwin::Assemble(*this);
211 case Action::LinkJobClass:
212 T = new tools::darwin::Link(*this); break;
213 case Action::LipoJobClass:
214 T = new tools::darwin::Lipo(*this); break;
215 case Action::DsymutilJobClass:
216 T = new tools::darwin::Dsymutil(*this); break;
217 case Action::VerifyJobClass:
218 T = new tools::darwin::VerifyDebug(*this); break;
226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
229 getProgramPaths().push_back(getDriver().getInstalledDir());
230 if (getDriver().getInstalledDir() != getDriver().Dir)
231 getProgramPaths().push_back(getDriver().Dir);
233 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
234 getProgramPaths().push_back(getDriver().getInstalledDir());
235 if (getDriver().getInstalledDir() != getDriver().Dir)
236 getProgramPaths().push_back(getDriver().Dir);
239 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
240 ArgStringList &CmdArgs) const {
242 CmdArgs.push_back("-force_load");
243 llvm::sys::Path P(getDriver().ClangExecutable);
244 P.eraseComponent(); // 'clang'
245 P.eraseComponent(); // 'bin'
246 P.appendComponent("lib");
247 P.appendComponent("arc");
248 P.appendComponent("libarclite_");
249 std::string s = P.str();
250 // Mash in the platform.
251 if (isTargetIOSSimulator())
252 s += "iphonesimulator";
253 else if (isTargetIPhoneOS())
259 CmdArgs.push_back(Args.MakeArgString(s));
262 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
263 ArgStringList &CmdArgs,
264 const char *DarwinStaticLib) const {
265 llvm::sys::Path P(getDriver().ResourceDir);
266 P.appendComponent("lib");
267 P.appendComponent("darwin");
268 P.appendComponent(DarwinStaticLib);
270 // For now, allow missing resource libraries to support developers who may
271 // not have compiler-rt checked out or integrated into their build.
273 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
274 CmdArgs.push_back(Args.MakeArgString(P.str()));
277 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
278 ArgStringList &CmdArgs) const {
279 // Darwin only supports the compiler-rt based runtime libraries.
280 switch (GetRuntimeLibType(Args)) {
281 case ToolChain::RLT_CompilerRT:
284 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
285 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
289 // Darwin doesn't support real static executables, don't link any runtime
290 // libraries with -static.
291 if (Args.hasArg(options::OPT_static) ||
292 Args.hasArg(options::OPT_fapple_kext) ||
293 Args.hasArg(options::OPT_mkernel))
296 // Reject -static-libgcc for now, we can deal with this when and if someone
297 // cares. This is useful in situations where someone wants to statically link
298 // something like libstdc++, and needs its runtime support routines.
299 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
300 getDriver().Diag(diag::err_drv_unsupported_opt)
301 << A->getAsString(Args);
305 // If we are building profile support, link that library in.
306 if (Args.hasArg(options::OPT_fprofile_arcs) ||
307 Args.hasArg(options::OPT_fprofile_generate) ||
308 Args.hasArg(options::OPT_fcreate_profile) ||
309 Args.hasArg(options::OPT_coverage)) {
310 // Select the appropriate runtime library for the target.
311 if (isTargetIPhoneOS()) {
312 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
314 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
318 SanitizerArgs Sanitize(getDriver(), Args);
320 // Add ASAN runtime library, if required. Dynamic libraries and bundles
321 // should not be linked with the runtime library.
322 if (Sanitize.needsAsanRt()) {
323 if (Args.hasArg(options::OPT_dynamiclib) ||
324 Args.hasArg(options::OPT_bundle)) return;
325 if (isTargetIPhoneOS()) {
326 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
327 << "-fsanitize=address";
329 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
331 // The ASAN runtime library requires C++ and CoreFoundation.
332 AddCXXStdlibLibArgs(Args, CmdArgs);
333 CmdArgs.push_back("-framework");
334 CmdArgs.push_back("CoreFoundation");
338 // Otherwise link libSystem, then the dynamic runtime library, and finally any
339 // target specific static runtime library.
340 CmdArgs.push_back("-lSystem");
342 // Select the dynamic runtime library and the target specific static library.
343 if (isTargetIPhoneOS()) {
344 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
345 // it never went into the SDK.
346 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
347 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
348 CmdArgs.push_back("-lgcc_s.1");
350 // We currently always need a static runtime library for iOS.
351 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
353 // The dynamic runtime library was merged with libSystem for 10.6 and
354 // beyond; only 10.4 and 10.5 need an additional runtime library.
355 if (isMacosxVersionLT(10, 5))
356 CmdArgs.push_back("-lgcc_s.10.4");
357 else if (isMacosxVersionLT(10, 6))
358 CmdArgs.push_back("-lgcc_s.10.5");
360 // For OS X, we thought we would only need a static runtime library when
361 // targeting 10.4, to provide versions of the static functions which were
362 // omitted from 10.4.dylib.
364 // Unfortunately, that turned out to not be true, because Darwin system
365 // headers can still use eprintf on i386, and it is not exported from
366 // libSystem. Therefore, we still must provide a runtime library just for
367 // the tiny tiny handful of projects that *might* use that symbol.
368 if (isMacosxVersionLT(10, 5)) {
369 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
371 if (getTriple().getArch() == llvm::Triple::x86)
372 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
373 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
378 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
379 const OptTable &Opts = getDriver().getOpts();
381 // Support allowing the SDKROOT environment variable used by xcrun and other
382 // Xcode tools to define the default sysroot, by making it the default for
384 if (!Args.hasArg(options::OPT_isysroot)) {
385 if (char *env = ::getenv("SDKROOT")) {
386 // We only use this value as the default if it is an absolute path and
388 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env)) {
389 Args.append(Args.MakeSeparateArg(
390 0, Opts.getOption(options::OPT_isysroot), env));
395 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
396 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
397 Arg *iOSSimVersion = Args.getLastArg(
398 options::OPT_mios_simulator_version_min_EQ);
400 if (OSXVersion && (iOSVersion || iOSSimVersion)) {
401 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
402 << OSXVersion->getAsString(Args)
403 << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
404 iOSVersion = iOSSimVersion = 0;
405 } else if (iOSVersion && iOSSimVersion) {
406 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
407 << iOSVersion->getAsString(Args)
408 << iOSSimVersion->getAsString(Args);
410 } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
411 // If no deployment target was specified on the command line, check for
412 // environment defines.
415 StringRef iOSSimTarget;
416 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
418 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
420 if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
423 // If no '-miphoneos-version-min' specified on the command line and
424 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
425 // based on -isysroot.
426 if (iOSTarget.empty()) {
427 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
428 StringRef first, second;
429 StringRef isysroot = A->getValue();
430 llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
432 iOSTarget = second.substr(0,3);
436 // If no OSX or iOS target has been specified and we're compiling for armv7,
437 // go ahead as assume we're targeting iOS.
438 if (OSXTarget.empty() && iOSTarget.empty() &&
439 (getDarwinArchName(Args) == "armv7" ||
440 getDarwinArchName(Args) == "armv7s"))
441 iOSTarget = iOSVersionMin;
443 // Handle conflicting deployment targets
445 // FIXME: Don't hardcode default here.
447 // Do not allow conflicts with the iOS simulator target.
448 if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
449 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
450 << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
451 << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
452 "IPHONEOS_DEPLOYMENT_TARGET");
455 // Allow conflicts among OSX and iOS for historical reasons, but choose the
457 if (!OSXTarget.empty() && !iOSTarget.empty()) {
458 if (getTriple().getArch() == llvm::Triple::arm ||
459 getTriple().getArch() == llvm::Triple::thumb)
465 if (!OSXTarget.empty()) {
466 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
467 OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
468 Args.append(OSXVersion);
469 } else if (!iOSTarget.empty()) {
470 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
471 iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
472 Args.append(iOSVersion);
473 } else if (!iOSSimTarget.empty()) {
474 const Option O = Opts.getOption(
475 options::OPT_mios_simulator_version_min_EQ);
476 iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
477 Args.append(iOSSimVersion);
479 // Otherwise, assume we are targeting OS X.
480 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
481 OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
482 Args.append(OSXVersion);
486 // Reject invalid architecture combinations.
487 if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
488 getTriple().getArch() != llvm::Triple::x86_64)) {
489 getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
490 << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
493 // Set the tool chain target information.
494 unsigned Major, Minor, Micro;
497 assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
498 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
499 Micro, HadExtra) || HadExtra ||
500 Major != 10 || Minor >= 100 || Micro >= 100)
501 getDriver().Diag(diag::err_drv_invalid_version_number)
502 << OSXVersion->getAsString(Args);
504 const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
505 assert(Version && "Unknown target platform!");
506 if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
507 Micro, HadExtra) || HadExtra ||
508 Major >= 10 || Minor >= 100 || Micro >= 100)
509 getDriver().Diag(diag::err_drv_invalid_version_number)
510 << Version->getAsString(Args);
513 bool IsIOSSim = bool(iOSSimVersion);
515 // In GCC, the simulator historically was treated as being OS X in some
516 // contexts, like determining the link logic, despite generally being called
517 // with an iOS deployment target. For compatibility, we detect the
518 // simulator as iOS + x86, and treat it differently in a few contexts.
519 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
520 getTriple().getArch() == llvm::Triple::x86_64))
523 setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
526 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
527 ArgStringList &CmdArgs) const {
528 CXXStdlibType Type = GetCXXStdlibType(Args);
531 case ToolChain::CST_Libcxx:
532 CmdArgs.push_back("-lc++");
535 case ToolChain::CST_Libstdcxx: {
536 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
537 // it was previously found in the gcc lib dir. However, for all the Darwin
538 // platforms we care about it was -lstdc++.6, so we search for that
539 // explicitly if we can't see an obvious -lstdc++ candidate.
541 // Check in the sysroot first.
543 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
544 llvm::sys::Path P(A->getValue());
545 P.appendComponent("usr");
546 P.appendComponent("lib");
547 P.appendComponent("libstdc++.dylib");
549 if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
551 P.appendComponent("libstdc++.6.dylib");
552 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
553 CmdArgs.push_back(Args.MakeArgString(P.str()));
559 // Otherwise, look in the root.
560 // FIXME: This should be removed someday when we don't have to care about
561 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
562 if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
563 (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
564 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
568 // Otherwise, let the linker search.
569 CmdArgs.push_back("-lstdc++");
575 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
576 ArgStringList &CmdArgs) const {
578 // For Darwin platforms, use the compiler-rt-based support library
579 // instead of the gcc-provided one (which is also incidentally
580 // only present in the gcc lib dir, which makes it hard to find).
582 llvm::sys::Path P(getDriver().ResourceDir);
583 P.appendComponent("lib");
584 P.appendComponent("darwin");
586 // Use the newer cc_kext for iOS ARM after 6.0.
587 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
588 !isIPhoneOSVersionLT(6, 0)) {
589 P.appendComponent("libclang_rt.cc_kext.a");
591 P.appendComponent("libclang_rt.cc_kext_ios5.a");
594 // For now, allow missing resource libraries to support developers who may
595 // not have compiler-rt checked out or integrated into their build.
597 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
598 CmdArgs.push_back(Args.MakeArgString(P.str()));
601 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
602 const char *BoundArch) const {
603 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
604 const OptTable &Opts = getDriver().getOpts();
606 // FIXME: We really want to get out of the tool chain level argument
607 // translation business, as it makes the driver functionality much
608 // more opaque. For now, we follow gcc closely solely for the
609 // purpose of easily achieving feature parity & testability. Once we
610 // have something that works, we should reevaluate each translation
611 // and try to push it down into tool specific logic.
613 for (ArgList::const_iterator it = Args.begin(),
614 ie = Args.end(); it != ie; ++it) {
617 if (A->getOption().matches(options::OPT_Xarch__)) {
618 // Skip this argument unless the architecture matches either the toolchain
619 // triple arch, or the arch being bound.
620 llvm::Triple::ArchType XarchArch =
621 tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
622 if (!(XarchArch == getArch() ||
623 (BoundArch && XarchArch ==
624 tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
627 Arg *OriginalArg = A;
628 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
629 unsigned Prev = Index;
630 Arg *XarchArg = Opts.ParseOneArg(Args, Index);
632 // If the argument parsing failed or more than one argument was
633 // consumed, the -Xarch_ argument's parameter tried to consume
634 // extra arguments. Emit an error and ignore.
636 // We also want to disallow any options which would alter the
637 // driver behavior; that isn't going to work in our model. We
638 // use isDriverOption() as an approximation, although things
639 // like -O4 are going to slip through.
640 if (!XarchArg || Index > Prev + 1) {
641 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
642 << A->getAsString(Args);
644 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
645 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
646 << A->getAsString(Args);
650 XarchArg->setBaseArg(A);
653 DAL->AddSynthesizedArg(A);
655 // Linker input arguments require custom handling. The problem is that we
656 // have already constructed the phase actions, so we can not treat them as
657 // "input arguments".
658 if (A->getOption().hasFlag(options::LinkerInput)) {
659 // Convert the argument into individual Zlinker_input_args.
660 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
661 DAL->AddSeparateArg(OriginalArg,
662 Opts.getOption(options::OPT_Zlinker_input),
670 // Sob. These is strictly gcc compatible for the time being. Apple
671 // gcc translates options twice, which means that self-expanding
672 // options add duplicates.
673 switch ((options::ID) A->getOption().getID()) {
678 case options::OPT_mkernel:
679 case options::OPT_fapple_kext:
681 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
684 case options::OPT_dependency_file:
685 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
689 case options::OPT_gfull:
690 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
692 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
695 case options::OPT_gused:
696 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
698 Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
701 case options::OPT_shared:
702 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
705 case options::OPT_fconstant_cfstrings:
706 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
709 case options::OPT_fno_constant_cfstrings:
710 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
713 case options::OPT_Wnonportable_cfstrings:
715 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
718 case options::OPT_Wno_nonportable_cfstrings:
720 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
723 case options::OPT_fpascal_strings:
724 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
727 case options::OPT_fno_pascal_strings:
728 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
733 if (getTriple().getArch() == llvm::Triple::x86 ||
734 getTriple().getArch() == llvm::Triple::x86_64)
735 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
736 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
738 // Add the arch options based on the particular spelling of -arch, to match
739 // how the driver driver works.
741 StringRef Name = BoundArch;
742 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
743 const Option MArch = Opts.getOption(options::OPT_march_EQ);
745 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
746 // which defines the list of which architectures we accept.
749 else if (Name == "ppc601")
750 DAL->AddJoinedArg(0, MCpu, "601");
751 else if (Name == "ppc603")
752 DAL->AddJoinedArg(0, MCpu, "603");
753 else if (Name == "ppc604")
754 DAL->AddJoinedArg(0, MCpu, "604");
755 else if (Name == "ppc604e")
756 DAL->AddJoinedArg(0, MCpu, "604e");
757 else if (Name == "ppc750")
758 DAL->AddJoinedArg(0, MCpu, "750");
759 else if (Name == "ppc7400")
760 DAL->AddJoinedArg(0, MCpu, "7400");
761 else if (Name == "ppc7450")
762 DAL->AddJoinedArg(0, MCpu, "7450");
763 else if (Name == "ppc970")
764 DAL->AddJoinedArg(0, MCpu, "970");
766 else if (Name == "ppc64")
767 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
769 else if (Name == "i386")
771 else if (Name == "i486")
772 DAL->AddJoinedArg(0, MArch, "i486");
773 else if (Name == "i586")
774 DAL->AddJoinedArg(0, MArch, "i586");
775 else if (Name == "i686")
776 DAL->AddJoinedArg(0, MArch, "i686");
777 else if (Name == "pentium")
778 DAL->AddJoinedArg(0, MArch, "pentium");
779 else if (Name == "pentium2")
780 DAL->AddJoinedArg(0, MArch, "pentium2");
781 else if (Name == "pentpro")
782 DAL->AddJoinedArg(0, MArch, "pentiumpro");
783 else if (Name == "pentIIm3")
784 DAL->AddJoinedArg(0, MArch, "pentium2");
786 else if (Name == "x86_64")
787 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
789 else if (Name == "arm")
790 DAL->AddJoinedArg(0, MArch, "armv4t");
791 else if (Name == "armv4t")
792 DAL->AddJoinedArg(0, MArch, "armv4t");
793 else if (Name == "armv5")
794 DAL->AddJoinedArg(0, MArch, "armv5tej");
795 else if (Name == "xscale")
796 DAL->AddJoinedArg(0, MArch, "xscale");
797 else if (Name == "armv6")
798 DAL->AddJoinedArg(0, MArch, "armv6k");
799 else if (Name == "armv7")
800 DAL->AddJoinedArg(0, MArch, "armv7a");
801 else if (Name == "armv7f")
802 DAL->AddJoinedArg(0, MArch, "armv7f");
803 else if (Name == "armv7k")
804 DAL->AddJoinedArg(0, MArch, "armv7k");
805 else if (Name == "armv7s")
806 DAL->AddJoinedArg(0, MArch, "armv7s");
809 llvm_unreachable("invalid Darwin arch");
812 // Add an explicit version min argument for the deployment target. We do this
813 // after argument translation because -Xarch_ arguments may add a version min
816 AddDeploymentTarget(*DAL);
818 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
819 // FIXME: It would be far better to avoid inserting those -static arguments,
820 // but we can't check the deployment target in the translation code until
822 if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
823 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
826 if (A->getOption().getID() != options::OPT_mkernel &&
827 A->getOption().getID() != options::OPT_fapple_kext)
829 assert(it != ie && "unexpected argument translation");
831 assert(A->getOption().getID() == options::OPT_static &&
832 "missing expected -static argument");
833 it = DAL->getArgs().erase(it);
837 // Validate the C++ standard library choice.
838 CXXStdlibType Type = GetCXXStdlibType(*DAL);
839 if (Type == ToolChain::CST_Libcxx) {
840 // Check whether the target provides libc++.
843 // Complain about targetting iOS < 5.0 in any way.
844 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
847 if (where != StringRef()) {
848 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
856 bool Darwin::IsUnwindTablesDefault() const {
857 return getArch() == llvm::Triple::x86_64;
860 bool Darwin::UseDwarfDebugFlags() const {
861 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
866 bool Darwin::UseSjLjExceptions() const {
867 // Darwin uses SjLj exceptions on ARM.
868 return (getTriple().getArch() == llvm::Triple::arm ||
869 getTriple().getArch() == llvm::Triple::thumb);
872 bool Darwin::isPICDefault() const {
876 bool Darwin::isPICDefaultForced() const {
877 return getArch() == llvm::Triple::x86_64;
880 bool Darwin::SupportsProfiling() const {
881 // Profiling instrumentation is only supported on x86.
882 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
885 bool Darwin::SupportsObjCGC() const {
886 // Garbage collection is supported everywhere except on iPhone OS.
887 return !isTargetIPhoneOS();
890 void Darwin::CheckObjCARC() const {
891 if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
893 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
897 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
898 types::ID InputType) const {
899 return ComputeLLVMTriple(Args, InputType);
902 /// Generic_GCC - A tool chain using the 'gcc' command to perform
903 /// all subcommands; this relies on gcc translating the majority of
904 /// command line options.
906 /// \brief Parse a GCCVersion object out of a string of text.
908 /// This is the primary means of forming GCCVersion objects.
910 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
911 const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
912 std::pair<StringRef, StringRef> First = VersionText.split('.');
913 std::pair<StringRef, StringRef> Second = First.second.split('.');
915 GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
916 if (First.first.getAsInteger(10, GoodVersion.Major) ||
917 GoodVersion.Major < 0)
919 if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
920 GoodVersion.Minor < 0)
923 // First look for a number prefix and parse that if present. Otherwise just
924 // stash the entire patch string in the suffix, and leave the number
925 // unspecified. This covers versions strings such as:
931 // And retains any patch number it finds.
932 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
933 if (!PatchText.empty()) {
934 if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
935 // Try to parse the number and any suffix.
936 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
937 GoodVersion.Patch < 0)
939 GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
946 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
947 bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
948 if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
949 if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
951 // Note that we rank versions with *no* patch specified is better than ones
952 // hard-coding a patch version. Thus if the RHS has no patch, it always
953 // wins, and the LHS only wins if it has no patch and the RHS does have
955 if (RHS.Patch == -1) return true; if (Patch == -1) return false;
956 if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
957 if (PatchSuffix == RHS.PatchSuffix) return false;
959 // Finally, between completely tied version numbers, the version with the
960 // suffix loses as we prefer full releases.
961 if (RHS.PatchSuffix.empty()) return true;
965 static StringRef getGCCToolchainDir(const ArgList &Args) {
966 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
968 return A->getValue();
969 return GCC_INSTALL_PREFIX;
972 /// \brief Construct a GCCInstallationDetector from the driver.
974 /// This performs all of the autodetection and sets up the various paths.
975 /// Once constructed, a GCCInstallationDetector is essentially immutable.
977 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
978 /// should instead pull the target out of the driver. This is currently
979 /// necessary because the driver doesn't store the final version of the target
981 Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
983 const llvm::Triple &TargetTriple,
986 llvm::Triple MultiarchTriple
987 = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
988 : TargetTriple.get32BitArchVariant();
989 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
990 // The library directories which may contain GCC installations.
991 SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
992 // The compatible GCC triples for this particular architecture.
993 SmallVector<StringRef, 10> CandidateTripleAliases;
994 SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
995 CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
996 CandidateTripleAliases,
997 CandidateMultiarchLibDirs,
998 CandidateMultiarchTripleAliases);
1000 // Compute the set of prefixes for our search.
1001 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1002 D.PrefixDirs.end());
1004 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1005 if (GCCToolchainDir != "") {
1006 if (GCCToolchainDir.back() == '/')
1007 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1009 Prefixes.push_back(GCCToolchainDir);
1011 Prefixes.push_back(D.SysRoot);
1012 Prefixes.push_back(D.SysRoot + "/usr");
1013 Prefixes.push_back(D.InstalledDir + "/..");
1016 // Loop over the various components which exist and select the best GCC
1017 // installation available. GCC installs are ranked by version number.
1018 Version = GCCVersion::Parse("0.0.0");
1019 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1020 if (!llvm::sys::fs::exists(Prefixes[i]))
1022 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1023 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1024 if (!llvm::sys::fs::exists(LibDir))
1026 for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1027 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1028 CandidateTripleAliases[k]);
1030 for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1031 const std::string LibDir
1032 = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1033 if (!llvm::sys::fs::exists(LibDir))
1035 for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1037 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1038 CandidateMultiarchTripleAliases[k],
1039 /*NeedsMultiarchSuffix=*/true);
1044 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1045 const llvm::Triple &TargetTriple,
1046 const llvm::Triple &MultiarchTriple,
1047 SmallVectorImpl<StringRef> &LibDirs,
1048 SmallVectorImpl<StringRef> &TripleAliases,
1049 SmallVectorImpl<StringRef> &MultiarchLibDirs,
1050 SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1051 // Declare a bunch of static data sets that we'll select between below. These
1052 // are specifically designed to always refer to string literals to avoid any
1053 // lifetime or initialization issues.
1054 static const char *const ARMLibDirs[] = { "/lib" };
1055 static const char *const ARMTriples[] = {
1056 "arm-linux-gnueabi",
1057 "arm-linux-androideabi"
1059 static const char *const ARMHFTriples[] = {
1060 "arm-linux-gnueabihf",
1063 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1064 static const char *const X86_64Triples[] = {
1066 "x86_64-unknown-linux-gnu",
1067 "x86_64-pc-linux-gnu",
1068 "x86_64-redhat-linux6E",
1069 "x86_64-redhat-linux",
1070 "x86_64-suse-linux",
1071 "x86_64-manbo-linux-gnu",
1073 "x86_64-slackware-linux"
1075 static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1076 static const char *const X86Triples[] = {
1078 "i686-pc-linux-gnu",
1081 "i686-redhat-linux",
1082 "i586-redhat-linux",
1083 "i386-redhat-linux",
1085 "i486-slackware-linux",
1086 "i686-montavista-linux"
1089 static const char *const MIPSLibDirs[] = { "/lib" };
1090 static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1091 static const char *const MIPSELLibDirs[] = { "/lib" };
1092 static const char *const MIPSELTriples[] = {
1094 "mipsel-linux-android"
1097 static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1098 static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1099 static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1100 static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1102 static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1103 static const char *const PPCTriples[] = {
1104 "powerpc-linux-gnu",
1105 "powerpc-unknown-linux-gnu",
1106 "powerpc-suse-linux",
1107 "powerpc-montavista-linuxspe"
1109 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1110 static const char *const PPC64Triples[] = {
1111 "powerpc64-linux-gnu",
1112 "powerpc64-unknown-linux-gnu",
1113 "powerpc64-suse-linux",
1114 "ppc64-redhat-linux"
1117 switch (TargetTriple.getArch()) {
1118 case llvm::Triple::arm:
1119 case llvm::Triple::thumb:
1120 LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1121 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1122 TripleAliases.append(
1123 ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1125 TripleAliases.append(
1126 ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1129 case llvm::Triple::x86_64:
1131 X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1132 TripleAliases.append(
1133 X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1134 MultiarchLibDirs.append(
1135 X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1136 MultiarchTripleAliases.append(
1137 X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1139 case llvm::Triple::x86:
1140 LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1141 TripleAliases.append(
1142 X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1143 MultiarchLibDirs.append(
1144 X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1145 MultiarchTripleAliases.append(
1146 X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1148 case llvm::Triple::mips:
1150 MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1151 TripleAliases.append(
1152 MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1153 MultiarchLibDirs.append(
1154 MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1155 MultiarchTripleAliases.append(
1156 MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1158 case llvm::Triple::mipsel:
1160 MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1161 TripleAliases.append(
1162 MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1163 MultiarchLibDirs.append(
1164 MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1165 MultiarchTripleAliases.append(
1166 MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1168 case llvm::Triple::mips64:
1170 MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1171 TripleAliases.append(
1172 MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1173 MultiarchLibDirs.append(
1174 MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1175 MultiarchTripleAliases.append(
1176 MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1178 case llvm::Triple::mips64el:
1180 MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1181 TripleAliases.append(
1182 MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1183 MultiarchLibDirs.append(
1184 MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1185 MultiarchTripleAliases.append(
1186 MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1188 case llvm::Triple::ppc:
1189 LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1190 TripleAliases.append(
1191 PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1192 MultiarchLibDirs.append(
1193 PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1194 MultiarchTripleAliases.append(
1195 PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1197 case llvm::Triple::ppc64:
1199 PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1200 TripleAliases.append(
1201 PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1202 MultiarchLibDirs.append(
1203 PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1204 MultiarchTripleAliases.append(
1205 PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1209 // By default, just rely on the standard lib directories and the original
1214 // Always append the drivers target triple to the end, in case it doesn't
1215 // match any of our aliases.
1216 TripleAliases.push_back(TargetTriple.str());
1218 // Also include the multiarch variant if it's different.
1219 if (TargetTriple.str() != MultiarchTriple.str())
1220 MultiarchTripleAliases.push_back(MultiarchTriple.str());
1223 // FIXME: There is the same routine in the Tools.cpp.
1224 static bool hasMipsN32ABIArg(const ArgList &Args) {
1225 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1226 return A && (A->getValue() == StringRef("n32"));
1229 static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
1230 const ArgList &Args) {
1231 if (TargetArch == llvm::Triple::x86_64 ||
1232 TargetArch == llvm::Triple::ppc64)
1235 if (TargetArch == llvm::Triple::mips64 ||
1236 TargetArch == llvm::Triple::mips64el) {
1237 if (hasMipsN32ABIArg(Args))
1246 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1247 llvm::Triple::ArchType TargetArch, const ArgList &Args,
1248 const std::string &LibDir,
1249 StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1250 // There are various different suffixes involving the triple we
1251 // check for. We also record what is necessary to walk from each back
1252 // up to the lib directory.
1253 const std::string LibSuffixes[] = {
1254 "/gcc/" + CandidateTriple.str(),
1255 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1257 // The Freescale PPC SDK has the gcc libraries in
1258 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1259 "/" + CandidateTriple.str(),
1261 // Ubuntu has a strange mis-matched pair of triples that this happens to
1263 // FIXME: It may be worthwhile to generalize this and look for a second
1265 "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1267 const std::string InstallSuffixes[] = {
1273 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1274 const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1275 (TargetArch != llvm::Triple::x86));
1276 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1277 StringRef LibSuffix = LibSuffixes[i];
1278 llvm::error_code EC;
1279 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1280 !EC && LI != LE; LI = LI.increment(EC)) {
1281 StringRef VersionText = llvm::sys::path::filename(LI->path());
1282 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1283 static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1284 if (CandidateVersion < MinVersion)
1286 if (CandidateVersion <= Version)
1289 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1290 // in what would normally be GCCInstallPath and put the 64-bit
1291 // libs in a subdirectory named 64. The simple logic we follow is that
1292 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1293 // we use that. If not, and if not a multiarch triple, we look for
1294 // crtbegin.o without the subdirectory.
1295 StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
1296 if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1297 GCCMultiarchSuffix = MultiarchSuffix.str();
1299 if (NeedsMultiarchSuffix ||
1300 !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1302 GCCMultiarchSuffix.clear();
1305 Version = CandidateVersion;
1306 GCCTriple.setTriple(CandidateTriple);
1307 // FIXME: We hack together the directory name here instead of
1308 // using LI to ensure stable path separators across Windows and
1310 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1311 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1317 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1318 const ArgList &Args)
1319 : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
1320 getProgramPaths().push_back(getDriver().getInstalledDir());
1321 if (getDriver().getInstalledDir() != getDriver().Dir)
1322 getProgramPaths().push_back(getDriver().Dir);
1325 Generic_GCC::~Generic_GCC() {
1326 // Free tool implementations.
1327 for (llvm::DenseMap<unsigned, Tool*>::iterator
1328 it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1332 Tool &Generic_GCC::SelectTool(const Compilation &C,
1333 const JobAction &JA,
1334 const ActionList &Inputs) const {
1335 Action::ActionClass Key;
1336 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1337 Key = Action::AnalyzeJobClass;
1341 Tool *&T = Tools[Key];
1344 case Action::InputClass:
1345 case Action::BindArchClass:
1346 llvm_unreachable("Invalid tool kind.");
1347 case Action::PreprocessJobClass:
1348 T = new tools::gcc::Preprocess(*this); break;
1349 case Action::PrecompileJobClass:
1350 T = new tools::gcc::Precompile(*this); break;
1351 case Action::AnalyzeJobClass:
1352 case Action::MigrateJobClass:
1353 T = new tools::Clang(*this); break;
1354 case Action::CompileJobClass:
1355 T = new tools::gcc::Compile(*this); break;
1356 case Action::AssembleJobClass:
1357 T = new tools::gcc::Assemble(*this); break;
1358 case Action::LinkJobClass:
1359 T = new tools::gcc::Link(*this); break;
1361 // This is a bit ungeneric, but the only platform using a driver
1362 // driver is Darwin.
1363 case Action::LipoJobClass:
1364 T = new tools::darwin::Lipo(*this); break;
1365 case Action::DsymutilJobClass:
1366 T = new tools::darwin::Dsymutil(*this); break;
1367 case Action::VerifyJobClass:
1368 T = new tools::darwin::VerifyDebug(*this); break;
1375 bool Generic_GCC::IsUnwindTablesDefault() const {
1376 return getArch() == llvm::Triple::x86_64;
1379 bool Generic_GCC::isPICDefault() const {
1383 bool Generic_GCC::isPICDefaultForced() const {
1387 /// Hexagon Toolchain
1389 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
1390 : ToolChain(D, Triple) {
1391 getProgramPaths().push_back(getDriver().getInstalledDir());
1392 if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
1393 getProgramPaths().push_back(getDriver().Dir);
1396 Hexagon_TC::~Hexagon_TC() {
1397 // Free tool implementations.
1398 for (llvm::DenseMap<unsigned, Tool*>::iterator
1399 it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1403 Tool &Hexagon_TC::SelectTool(const Compilation &C,
1404 const JobAction &JA,
1405 const ActionList &Inputs) const {
1406 Action::ActionClass Key;
1407 // if (JA.getKind () == Action::CompileJobClass)
1408 // Key = JA.getKind ();
1411 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1412 Key = Action::AnalyzeJobClass;
1415 // if ((JA.getKind () == Action::CompileJobClass)
1416 // && (JA.getType () != types::TY_LTO_BC)) {
1417 // Key = JA.getKind ();
1420 Tool *&T = Tools[Key];
1423 case Action::InputClass:
1424 case Action::BindArchClass:
1425 assert(0 && "Invalid tool kind.");
1426 case Action::AnalyzeJobClass:
1427 T = new tools::Clang(*this); break;
1428 case Action::AssembleJobClass:
1429 T = new tools::hexagon::Assemble(*this); break;
1430 case Action::LinkJobClass:
1431 T = new tools::hexagon::Link(*this); break;
1433 assert(false && "Unsupported action for Hexagon target.");
1440 bool Hexagon_TC::isPICDefault() const {
1444 bool Hexagon_TC::isPICDefaultForced() const {
1448 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1449 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1450 /// Currently does not support anything else but compilation.
1452 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
1453 : ToolChain(D, Triple) {
1454 // Path mangling to find libexec
1455 std::string Path(getDriver().Dir);
1457 Path += "/../libexec";
1458 getProgramPaths().push_back(Path);
1461 TCEToolChain::~TCEToolChain() {
1462 for (llvm::DenseMap<unsigned, Tool*>::iterator
1463 it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1467 bool TCEToolChain::IsMathErrnoDefault() const {
1471 bool TCEToolChain::isPICDefault() const {
1475 bool TCEToolChain::isPICDefaultForced() const {
1479 Tool &TCEToolChain::SelectTool(const Compilation &C,
1480 const JobAction &JA,
1481 const ActionList &Inputs) const {
1482 Action::ActionClass Key;
1483 Key = Action::AnalyzeJobClass;
1485 Tool *&T = Tools[Key];
1488 case Action::PreprocessJobClass:
1489 T = new tools::gcc::Preprocess(*this); break;
1490 case Action::AnalyzeJobClass:
1491 T = new tools::Clang(*this); break;
1493 llvm_unreachable("Unsupported action for TCE target.");
1499 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1501 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1502 : Generic_ELF(D, Triple, Args) {
1503 getFilePaths().push_back(getDriver().Dir + "/../lib");
1504 getFilePaths().push_back("/usr/lib");
1507 Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1508 const ActionList &Inputs) const {
1509 Action::ActionClass Key;
1510 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1511 Key = Action::AnalyzeJobClass;
1515 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1516 options::OPT_no_integrated_as,
1517 IsIntegratedAssemblerDefault());
1519 Tool *&T = Tools[Key];
1522 case Action::AssembleJobClass: {
1523 if (UseIntegratedAs)
1524 T = new tools::ClangAs(*this);
1526 T = new tools::openbsd::Assemble(*this);
1529 case Action::LinkJobClass:
1530 T = new tools::openbsd::Link(*this); break;
1532 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1539 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1541 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1542 : Generic_ELF(D, Triple, Args) {
1543 getFilePaths().push_back(getDriver().Dir + "/../lib");
1544 getFilePaths().push_back("/usr/lib");
1547 Tool &Bitrig::SelectTool(const Compilation &C, const JobAction &JA,
1548 const ActionList &Inputs) const {
1549 Action::ActionClass Key;
1550 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1551 Key = Action::AnalyzeJobClass;
1555 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1556 options::OPT_no_integrated_as,
1557 IsIntegratedAssemblerDefault());
1559 Tool *&T = Tools[Key];
1562 case Action::AssembleJobClass: {
1563 if (UseIntegratedAs)
1564 T = new tools::ClangAs(*this);
1566 T = new tools::bitrig::Assemble(*this);
1569 case Action::LinkJobClass:
1570 T = new tools::bitrig::Link(*this); break;
1572 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1579 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1580 ArgStringList &CC1Args) const {
1581 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1582 DriverArgs.hasArg(options::OPT_nostdincxx))
1585 switch (GetCXXStdlibType(DriverArgs)) {
1586 case ToolChain::CST_Libcxx:
1587 addSystemInclude(DriverArgs, CC1Args,
1588 getDriver().SysRoot + "/usr/include/c++/");
1590 case ToolChain::CST_Libstdcxx:
1591 addSystemInclude(DriverArgs, CC1Args,
1592 getDriver().SysRoot + "/usr/include/c++/stdc++");
1593 addSystemInclude(DriverArgs, CC1Args,
1594 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1596 StringRef Triple = getTriple().str();
1597 if (Triple.startswith("amd64"))
1598 addSystemInclude(DriverArgs, CC1Args,
1599 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1602 addSystemInclude(DriverArgs, CC1Args,
1603 getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1609 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1610 ArgStringList &CmdArgs) const {
1611 switch (GetCXXStdlibType(Args)) {
1612 case ToolChain::CST_Libcxx:
1613 CmdArgs.push_back("-lc++");
1614 CmdArgs.push_back("-lcxxrt");
1615 // Include supc++ to provide Unwind until provided by libcxx.
1616 CmdArgs.push_back("-lgcc");
1618 case ToolChain::CST_Libstdcxx:
1619 CmdArgs.push_back("-lstdc++");
1624 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1626 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1627 : Generic_ELF(D, Triple, Args) {
1629 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1630 // back to '/usr/lib' if it doesn't exist.
1631 if ((Triple.getArch() == llvm::Triple::x86 ||
1632 Triple.getArch() == llvm::Triple::ppc) &&
1633 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1634 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1636 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1639 Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1640 const ActionList &Inputs) const {
1641 Action::ActionClass Key;
1642 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1643 Key = Action::AnalyzeJobClass;
1647 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1648 options::OPT_no_integrated_as,
1649 IsIntegratedAssemblerDefault());
1651 Tool *&T = Tools[Key];
1654 case Action::AssembleJobClass:
1655 if (UseIntegratedAs)
1656 T = new tools::ClangAs(*this);
1658 T = new tools::freebsd::Assemble(*this);
1660 case Action::LinkJobClass:
1661 T = new tools::freebsd::Link(*this); break;
1663 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1670 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1672 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1673 : Generic_ELF(D, Triple, Args) {
1675 if (getDriver().UseStdLib) {
1676 // When targeting a 32-bit platform, try the special directory used on
1677 // 64-bit hosts, and only fall back to the main library directory if that
1679 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1680 // what all logic is needed to emulate the '=' prefix here.
1681 if (Triple.getArch() == llvm::Triple::x86)
1682 getFilePaths().push_back("=/usr/lib/i386");
1684 getFilePaths().push_back("=/usr/lib");
1688 Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1689 const ActionList &Inputs) const {
1690 Action::ActionClass Key;
1691 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1692 Key = Action::AnalyzeJobClass;
1696 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1697 options::OPT_no_integrated_as,
1698 IsIntegratedAssemblerDefault());
1700 Tool *&T = Tools[Key];
1703 case Action::AssembleJobClass:
1704 if (UseIntegratedAs)
1705 T = new tools::ClangAs(*this);
1707 T = new tools::netbsd::Assemble(*this);
1709 case Action::LinkJobClass:
1710 T = new tools::netbsd::Link(*this);
1713 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1720 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1722 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1723 : Generic_ELF(D, Triple, Args) {
1724 getFilePaths().push_back(getDriver().Dir + "/../lib");
1725 getFilePaths().push_back("/usr/lib");
1728 Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1729 const ActionList &Inputs) const {
1730 Action::ActionClass Key;
1731 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1732 Key = Action::AnalyzeJobClass;
1736 Tool *&T = Tools[Key];
1739 case Action::AssembleJobClass:
1740 T = new tools::minix::Assemble(*this); break;
1741 case Action::LinkJobClass:
1742 T = new tools::minix::Link(*this); break;
1744 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1751 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1753 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1754 const ArgList &Args)
1755 : Generic_GCC(D, Triple, Args) {
1757 getProgramPaths().push_back(getDriver().getInstalledDir());
1758 if (getDriver().getInstalledDir() != getDriver().Dir)
1759 getProgramPaths().push_back(getDriver().Dir);
1761 getFilePaths().push_back(getDriver().Dir + "/../lib");
1762 getFilePaths().push_back("/usr/lib");
1763 getFilePaths().push_back("/usr/sfw/lib");
1764 getFilePaths().push_back("/opt/gcc4/lib");
1765 getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1769 Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1770 const ActionList &Inputs) const {
1771 Action::ActionClass Key;
1772 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1773 Key = Action::AnalyzeJobClass;
1777 Tool *&T = Tools[Key];
1780 case Action::AssembleJobClass:
1781 T = new tools::auroraux::Assemble(*this); break;
1782 case Action::LinkJobClass:
1783 T = new tools::auroraux::Link(*this); break;
1785 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1792 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1794 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1795 const ArgList &Args)
1796 : Generic_GCC(D, Triple, Args) {
1798 getProgramPaths().push_back(getDriver().getInstalledDir());
1799 if (getDriver().getInstalledDir() != getDriver().Dir)
1800 getProgramPaths().push_back(getDriver().Dir);
1802 getFilePaths().push_back(getDriver().Dir + "/../lib");
1803 getFilePaths().push_back("/usr/lib");
1806 Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
1807 const ActionList &Inputs) const {
1808 Action::ActionClass Key;
1809 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1810 Key = Action::AnalyzeJobClass;
1814 Tool *&T = Tools[Key];
1817 case Action::AssembleJobClass:
1818 T = new tools::solaris::Assemble(*this); break;
1819 case Action::LinkJobClass:
1820 T = new tools::solaris::Link(*this); break;
1822 T = &Generic_GCC::SelectTool(C, JA, Inputs);
1829 /// Linux toolchain (very bare-bones at the moment).
1863 static bool IsRedhat(enum LinuxDistro Distro) {
1864 return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1865 (Distro >= RHEL4 && Distro <= RHEL6);
1868 static bool IsOpenSuse(enum LinuxDistro Distro) {
1869 return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
1872 static bool IsDebian(enum LinuxDistro Distro) {
1873 return Distro >= DebianLenny && Distro <= DebianWheezy;
1876 static bool IsUbuntu(enum LinuxDistro Distro) {
1877 return Distro >= UbuntuHardy && Distro <= UbuntuRaring;
1880 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1881 OwningPtr<llvm::MemoryBuffer> File;
1882 if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1883 StringRef Data = File.get()->getBuffer();
1884 SmallVector<StringRef, 8> Lines;
1885 Data.split(Lines, "\n");
1886 LinuxDistro Version = UnknownDistro;
1887 for (unsigned i = 0, s = Lines.size(); i != s; ++i)
1888 if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
1889 Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
1890 .Case("hardy", UbuntuHardy)
1891 .Case("intrepid", UbuntuIntrepid)
1892 .Case("jaunty", UbuntuJaunty)
1893 .Case("karmic", UbuntuKarmic)
1894 .Case("lucid", UbuntuLucid)
1895 .Case("maverick", UbuntuMaverick)
1896 .Case("natty", UbuntuNatty)
1897 .Case("oneiric", UbuntuOneiric)
1898 .Case("precise", UbuntuPrecise)
1899 .Case("quantal", UbuntuQuantal)
1900 .Case("raring", UbuntuRaring)
1901 .Default(UnknownDistro);
1905 if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1906 StringRef Data = File.get()->getBuffer();
1907 if (Data.startswith("Fedora release 16"))
1909 else if (Data.startswith("Fedora release 15"))
1911 else if (Data.startswith("Fedora release 14"))
1913 else if (Data.startswith("Fedora release 13"))
1915 else if (Data.startswith("Fedora release") &&
1916 Data.find("Rawhide") != StringRef::npos)
1917 return FedoraRawhide;
1918 else if (Data.startswith("Red Hat Enterprise Linux") &&
1919 Data.find("release 6") != StringRef::npos)
1921 else if ((Data.startswith("Red Hat Enterprise Linux") ||
1922 Data.startswith("CentOS")) &&
1923 Data.find("release 5") != StringRef::npos)
1925 else if ((Data.startswith("Red Hat Enterprise Linux") ||
1926 Data.startswith("CentOS")) &&
1927 Data.find("release 4") != StringRef::npos)
1929 return UnknownDistro;
1932 if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1933 StringRef Data = File.get()->getBuffer();
1936 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
1937 return DebianSqueeze;
1938 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
1939 return DebianWheezy;
1940 return UnknownDistro;
1943 if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
1944 return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
1945 .StartsWith("openSUSE 11.3", OpenSuse11_3)
1946 .StartsWith("openSUSE 11.4", OpenSuse11_4)
1947 .StartsWith("openSUSE 12.1", OpenSuse12_1)
1948 .StartsWith("openSUSE 12.2", OpenSuse12_2)
1949 .Default(UnknownDistro);
1952 if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1955 if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1958 return UnknownDistro;
1961 /// \brief Get our best guess at the multiarch triple for a target.
1963 /// Debian-based systems are starting to use a multiarch setup where they use
1964 /// a target-triple directory in the library and header search paths.
1965 /// Unfortunately, this triple does not align with the vanilla target triple,
1966 /// so we provide a rough mapping here.
1967 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
1968 StringRef SysRoot) {
1969 // For most architectures, just use whatever we have rather than trying to be
1971 switch (TargetTriple.getArch()) {
1973 return TargetTriple.str();
1975 // We use the existence of '/lib/<triple>' as a directory to detect some
1976 // common linux triples that don't quite match the Clang triple for both
1977 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
1978 // regardless of what the actual target triple is.
1979 case llvm::Triple::arm:
1980 case llvm::Triple::thumb:
1981 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1982 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
1983 return "arm-linux-gnueabihf";
1985 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
1986 return "arm-linux-gnueabi";
1988 return TargetTriple.str();
1989 case llvm::Triple::x86:
1990 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
1991 return "i386-linux-gnu";
1992 return TargetTriple.str();
1993 case llvm::Triple::x86_64:
1994 if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
1995 return "x86_64-linux-gnu";
1996 return TargetTriple.str();
1997 case llvm::Triple::mips:
1998 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
1999 return "mips-linux-gnu";
2000 return TargetTriple.str();
2001 case llvm::Triple::mipsel:
2002 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2003 return "mipsel-linux-gnu";
2004 return TargetTriple.str();
2005 case llvm::Triple::ppc:
2006 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2007 return "powerpc-linux-gnu";
2008 return TargetTriple.str();
2009 case llvm::Triple::ppc64:
2010 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2011 return "powerpc64-linux-gnu";
2012 return TargetTriple.str();
2016 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2017 if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2020 static bool isMipsArch(llvm::Triple::ArchType Arch) {
2021 return Arch == llvm::Triple::mips ||
2022 Arch == llvm::Triple::mipsel ||
2023 Arch == llvm::Triple::mips64 ||
2024 Arch == llvm::Triple::mips64el;
2027 static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2028 const ArgList &Args) {
2029 if (Arch != llvm::Triple::mips &&
2030 Arch != llvm::Triple::mipsel)
2033 Arg *A = Args.getLastArg(options::OPT_march_EQ,
2034 options::OPT_mcpu_EQ,
2035 options::OPT_mips_CPUs_Group);
2040 if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2041 return A->getOption().matches(options::OPT_mips32r2);
2043 return A->getValue() == StringRef("mips32r2");
2046 static StringRef getMultilibDir(const llvm::Triple &Triple,
2047 const ArgList &Args) {
2048 if (!isMipsArch(Triple.getArch()))
2049 return Triple.isArch32Bit() ? "lib32" : "lib64";
2051 // lib32 directory has a special meaning on MIPS targets.
2052 // It contains N32 ABI binaries. Use this folder if produce
2053 // code for N32 ABI only.
2054 if (hasMipsN32ABIArg(Args))
2057 return Triple.isArch32Bit() ? "lib" : "lib64";
2060 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2061 : Generic_ELF(D, Triple, Args) {
2062 llvm::Triple::ArchType Arch = Triple.getArch();
2063 const std::string &SysRoot = getDriver().SysRoot;
2065 // OpenSuse stores the linker with the compiler, add that to the search
2067 ToolChain::path_list &PPaths = getProgramPaths();
2068 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2069 GCCInstallation.getTriple().str() + "/bin").str());
2071 Linker = GetProgramPath("ld");
2073 LinuxDistro Distro = DetectLinuxDistro(Arch);
2075 if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2076 ExtraOpts.push_back("-z");
2077 ExtraOpts.push_back("relro");
2080 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2081 ExtraOpts.push_back("-X");
2083 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2085 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2086 // and the MIPS ABI require .dynsym to be sorted in different ways.
2087 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2088 // ABI requires a mapping between the GOT and the symbol table.
2089 // Android loader does not support .gnu.hash.
2090 if (!isMipsArch(Arch) && !IsAndroid) {
2091 if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2092 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2093 ExtraOpts.push_back("--hash-style=gnu");
2095 if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2096 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2097 ExtraOpts.push_back("--hash-style=both");
2100 if (IsRedhat(Distro))
2101 ExtraOpts.push_back("--no-add-needed");
2103 if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2104 IsOpenSuse(Distro) ||
2105 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2106 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2107 ExtraOpts.push_back("--build-id");
2109 if (IsOpenSuse(Distro))
2110 ExtraOpts.push_back("--enable-new-dtags");
2112 // The selection of paths to try here is designed to match the patterns which
2113 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2114 // This was determined by running GCC in a fake filesystem, creating all
2115 // possible permutations of these directories, and seeing which ones it added
2116 // to the link paths.
2117 path_list &Paths = getFilePaths();
2119 const std::string Multilib = getMultilibDir(Triple, Args);
2120 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2122 // Add the multilib suffixed paths where they are available.
2123 if (GCCInstallation.isValid()) {
2124 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2125 const std::string &LibPath = GCCInstallation.getParentLibPath();
2127 if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2128 addPathIfExists(GCCInstallation.getInstallPath() +
2129 GCCInstallation.getMultiarchSuffix() +
2133 addPathIfExists((GCCInstallation.getInstallPath() +
2134 GCCInstallation.getMultiarchSuffix()),
2137 // If the GCC installation we found is inside of the sysroot, we want to
2138 // prefer libraries installed in the parent prefix of the GCC installation.
2139 // It is important to *not* use these paths when the GCC installation is
2140 // outside of the system root as that can pick up unintended libraries.
2141 // This usually happens when there is an external cross compiler on the
2142 // host system, and a more minimal sysroot available that is the target of
2144 if (StringRef(LibPath).startswith(SysRoot)) {
2145 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2147 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2148 addPathIfExists(LibPath + "/../" + Multilib, Paths);
2150 // On Android, libraries in the parent prefix of the GCC installation are
2151 // preferred to the ones under sysroot.
2153 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2156 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2157 addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2158 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2159 addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2161 // Try walking via the GCC triple path in case of multiarch GCC
2162 // installations with strange symlinks.
2163 if (GCCInstallation.isValid())
2164 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2165 "/../../" + Multilib, Paths);
2167 // Add the non-multilib suffixed paths (if potentially different).
2168 if (GCCInstallation.isValid()) {
2169 const std::string &LibPath = GCCInstallation.getParentLibPath();
2170 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2171 if (!GCCInstallation.getMultiarchSuffix().empty())
2172 addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2174 if (StringRef(LibPath).startswith(SysRoot)) {
2175 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2176 addPathIfExists(LibPath, Paths);
2179 addPathIfExists(SysRoot + "/lib", Paths);
2180 addPathIfExists(SysRoot + "/usr/lib", Paths);
2183 bool Linux::HasNativeLLVMSupport() const {
2187 Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
2188 const ActionList &Inputs) const {
2189 Action::ActionClass Key;
2190 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2191 Key = Action::AnalyzeJobClass;
2195 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2196 options::OPT_no_integrated_as,
2197 IsIntegratedAssemblerDefault());
2199 Tool *&T = Tools[Key];
2202 case Action::AssembleJobClass:
2203 if (UseIntegratedAs)
2204 T = new tools::ClangAs(*this);
2206 T = new tools::linuxtools::Assemble(*this);
2208 case Action::LinkJobClass:
2209 T = new tools::linuxtools::Link(*this); break;
2211 T = &Generic_GCC::SelectTool(C, JA, Inputs);
2218 void Linux::addClangTargetOptions(ArgStringList &CC1Args) const {
2219 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2220 if (V >= Generic_GCC::GCCVersion::Parse("4.7.0"))
2221 CC1Args.push_back("-fuse-init-array");
2224 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2225 ArgStringList &CC1Args) const {
2226 const Driver &D = getDriver();
2228 if (DriverArgs.hasArg(options::OPT_nostdinc))
2231 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2232 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2234 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2235 llvm::sys::Path P(D.ResourceDir);
2236 P.appendComponent("include");
2237 addSystemInclude(DriverArgs, CC1Args, P.str());
2240 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2243 // Check for configure-time C include directories.
2244 StringRef CIncludeDirs(C_INCLUDE_DIRS);
2245 if (CIncludeDirs != "") {
2246 SmallVector<StringRef, 5> dirs;
2247 CIncludeDirs.split(dirs, ":");
2248 for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2250 StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2251 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2256 // Lacking those, try to detect the correct set of system includes for the
2259 // Implement generic Debian multiarch support.
2260 const StringRef X86_64MultiarchIncludeDirs[] = {
2261 "/usr/include/x86_64-linux-gnu",
2263 // FIXME: These are older forms of multiarch. It's not clear that they're
2264 // in use in any released version of Debian, so we should consider
2266 "/usr/include/i686-linux-gnu/64",
2267 "/usr/include/i486-linux-gnu/64"
2269 const StringRef X86MultiarchIncludeDirs[] = {
2270 "/usr/include/i386-linux-gnu",
2272 // FIXME: These are older forms of multiarch. It's not clear that they're
2273 // in use in any released version of Debian, so we should consider
2275 "/usr/include/x86_64-linux-gnu/32",
2276 "/usr/include/i686-linux-gnu",
2277 "/usr/include/i486-linux-gnu"
2279 const StringRef ARMMultiarchIncludeDirs[] = {
2280 "/usr/include/arm-linux-gnueabi"
2282 const StringRef ARMHFMultiarchIncludeDirs[] = {
2283 "/usr/include/arm-linux-gnueabihf"
2285 const StringRef MIPSMultiarchIncludeDirs[] = {
2286 "/usr/include/mips-linux-gnu"
2288 const StringRef MIPSELMultiarchIncludeDirs[] = {
2289 "/usr/include/mipsel-linux-gnu"
2291 const StringRef PPCMultiarchIncludeDirs[] = {
2292 "/usr/include/powerpc-linux-gnu"
2294 const StringRef PPC64MultiarchIncludeDirs[] = {
2295 "/usr/include/powerpc64-linux-gnu"
2297 ArrayRef<StringRef> MultiarchIncludeDirs;
2298 if (getTriple().getArch() == llvm::Triple::x86_64) {
2299 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2300 } else if (getTriple().getArch() == llvm::Triple::x86) {
2301 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2302 } else if (getTriple().getArch() == llvm::Triple::arm) {
2303 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2304 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2306 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2307 } else if (getTriple().getArch() == llvm::Triple::mips) {
2308 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2309 } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2310 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2311 } else if (getTriple().getArch() == llvm::Triple::ppc) {
2312 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2313 } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2314 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2316 for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2317 E = MultiarchIncludeDirs.end();
2319 if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2320 addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2325 if (getTriple().getOS() == llvm::Triple::RTEMS)
2328 // Add an include of '/include' directly. This isn't provided by default by
2329 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2330 // add even when Clang is acting as-if it were a system compiler.
2331 addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2333 addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2336 /// \brief Helper to add the thre variant paths for a libstdc++ installation.
2337 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2338 const ArgList &DriverArgs,
2339 ArgStringList &CC1Args) {
2340 if (!llvm::sys::fs::exists(Base))
2342 addSystemInclude(DriverArgs, CC1Args, Base);
2343 addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2344 addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2348 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2349 ArgStringList &CC1Args) const {
2350 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2351 DriverArgs.hasArg(options::OPT_nostdincxx))
2354 // Check if libc++ has been enabled and provide its include paths if so.
2355 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2356 // libc++ is always installed at a fixed path on Linux currently.
2357 addSystemInclude(DriverArgs, CC1Args,
2358 getDriver().SysRoot + "/usr/include/c++/v1");
2362 // We need a detected GCC installation on Linux to provide libstdc++'s
2363 // headers. We handled the libc++ case above.
2364 if (!GCCInstallation.isValid())
2367 // By default, look for the C++ headers in an include directory adjacent to
2368 // the lib directory of the GCC installation. Note that this is expect to be
2369 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2370 StringRef LibDir = GCCInstallation.getParentLibPath();
2371 StringRef InstallDir = GCCInstallation.getInstallPath();
2372 StringRef Version = GCCInstallation.getVersion().Text;
2373 StringRef TripleStr = GCCInstallation.getTriple().str();
2375 const std::string IncludePathCandidates[] = {
2376 LibDir.str() + "/../include/c++/" + Version.str(),
2377 // Gentoo is weird and places its headers inside the GCC install, so if the
2378 // first attempt to find the headers fails, try this pattern.
2379 InstallDir.str() + "/include/g++-v4",
2380 // Android standalone toolchain has C++ headers in yet another place.
2381 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2382 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2383 // without a subdirectory corresponding to the gcc version.
2384 LibDir.str() + "/../include/c++",
2387 for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2388 if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2389 GCCInstallation.getMultiarchSuffix()),
2390 DriverArgs, CC1Args))
2395 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2397 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2398 : Generic_ELF(D, Triple, Args) {
2400 // Path mangling to find libexec
2401 getProgramPaths().push_back(getDriver().getInstalledDir());
2402 if (getDriver().getInstalledDir() != getDriver().Dir)
2403 getProgramPaths().push_back(getDriver().Dir);
2405 getFilePaths().push_back(getDriver().Dir + "/../lib");
2406 getFilePaths().push_back("/usr/lib");
2407 getFilePaths().push_back("/usr/lib/gcc41");
2410 Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
2411 const ActionList &Inputs) const {
2412 Action::ActionClass Key;
2413 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2414 Key = Action::AnalyzeJobClass;
2418 Tool *&T = Tools[Key];
2421 case Action::AssembleJobClass:
2422 T = new tools::dragonfly::Assemble(*this); break;
2423 case Action::LinkJobClass:
2424 T = new tools::dragonfly::Link(*this); break;
2426 T = &Generic_GCC::SelectTool(C, JA, Inputs);