clang API Documentation

ToolChains.cpp
Go to the documentation of this file.
00001 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "ToolChains.h"
00011 #include "clang/Basic/ObjCRuntime.h"
00012 #include "clang/Basic/Version.h"
00013 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
00014 #include "clang/Driver/Compilation.h"
00015 #include "clang/Driver/Driver.h"
00016 #include "clang/Driver/DriverDiagnostic.h"
00017 #include "clang/Driver/Options.h"
00018 #include "clang/Driver/SanitizerArgs.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/ADT/StringSwitch.h"
00023 #include "llvm/Option/Arg.h"
00024 #include "llvm/Option/ArgList.h"
00025 #include "llvm/Option/OptTable.h"
00026 #include "llvm/Option/Option.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/FileSystem.h"
00029 #include "llvm/Support/MemoryBuffer.h"
00030 #include "llvm/Support/Path.h"
00031 #include "llvm/Support/Program.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include <cstdlib> // ::getenv
00034 #include <system_error>
00035 
00036 using namespace clang::driver;
00037 using namespace clang::driver::toolchains;
00038 using namespace clang;
00039 using namespace llvm::opt;
00040 
00041 MachO::MachO(const Driver &D, const llvm::Triple &Triple,
00042                        const ArgList &Args)
00043   : ToolChain(D, Triple, Args) {
00044   getProgramPaths().push_back(getDriver().getInstalledDir());
00045   if (getDriver().getInstalledDir() != getDriver().Dir)
00046     getProgramPaths().push_back(getDriver().Dir);
00047 
00048   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
00049   getProgramPaths().push_back(getDriver().getInstalledDir());
00050   if (getDriver().getInstalledDir() != getDriver().Dir)
00051     getProgramPaths().push_back(getDriver().Dir);
00052 }
00053 
00054 /// Darwin - Darwin tool chain for i386 and x86_64.
00055 Darwin::Darwin(const Driver & D, const llvm::Triple & Triple,
00056                const ArgList & Args)
00057   : MachO(D, Triple, Args), TargetInitialized(false) {
00058   // Compute the initial Darwin version from the triple
00059   unsigned Major, Minor, Micro;
00060   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
00061     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
00062       Triple.getOSName();
00063   llvm::raw_string_ostream(MacosxVersionMin)
00064     << Major << '.' << Minor << '.' << Micro;
00065 
00066   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
00067   // It should be removed when we stop supporting that.
00068   DarwinVersion[0] = Minor + 4;
00069   DarwinVersion[1] = Micro;
00070   DarwinVersion[2] = 0;
00071 
00072   // Compute the initial iOS version from the triple
00073   Triple.getiOSVersion(Major, Minor, Micro);
00074   llvm::raw_string_ostream(iOSVersionMin)
00075     << Major << '.' << Minor << '.' << Micro;
00076 }
00077 
00078 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
00079   types::ID Ty = types::lookupTypeForExtension(Ext);
00080 
00081   // Darwin always preprocesses assembly files (unless -x is used explicitly).
00082   if (Ty == types::TY_PP_Asm)
00083     return types::TY_Asm;
00084 
00085   return Ty;
00086 }
00087 
00088 bool MachO::HasNativeLLVMSupport() const {
00089   return true;
00090 }
00091 
00092 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
00093 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
00094   if (isTargetIOSBased())
00095     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
00096   if (isNonFragile)
00097     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
00098   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
00099 }
00100 
00101 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
00102 bool Darwin::hasBlocksRuntime() const {
00103   if (isTargetIOSBased())
00104     return !isIPhoneOSVersionLT(3, 2);
00105   else {
00106     assert(isTargetMacOS() && "unexpected darwin target");
00107     return !isMacosxVersionLT(10, 6);
00108   }
00109 }
00110 
00111 static const char *GetArmArchForMArch(StringRef Value) {
00112   return llvm::StringSwitch<const char*>(Value)
00113     .Case("armv6k", "armv6")
00114     .Case("armv6m", "armv6m")
00115     .Case("armv5tej", "armv5")
00116     .Case("xscale", "xscale")
00117     .Case("armv4t", "armv4t")
00118     .Case("armv7", "armv7")
00119     .Cases("armv7a", "armv7-a", "armv7")
00120     .Cases("armv7r", "armv7-r", "armv7")
00121     .Cases("armv7em", "armv7e-m", "armv7em")
00122     .Cases("armv7k", "armv7-k", "armv7k")
00123     .Cases("armv7m", "armv7-m", "armv7m")
00124     .Cases("armv7s", "armv7-s", "armv7s")
00125     .Default(nullptr);
00126 }
00127 
00128 static const char *GetArmArchForMCpu(StringRef Value) {
00129   return llvm::StringSwitch<const char *>(Value)
00130     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
00131     .Cases("arm10e", "arm10tdmi", "armv5")
00132     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
00133     .Case("xscale", "xscale")
00134     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
00135     .Case("cortex-m0", "armv6m")
00136     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
00137     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7")
00138     .Cases("cortex-r4", "cortex-r5", "armv7r")
00139     .Case("cortex-m3", "armv7m")
00140     .Cases("cortex-m4", "cortex-m7", "armv7em")
00141     .Case("swift", "armv7s")
00142     .Default(nullptr);
00143 }
00144 
00145 static bool isSoftFloatABI(const ArgList &Args) {
00146   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
00147                            options::OPT_mfloat_abi_EQ);
00148   if (!A)
00149     return false;
00150 
00151   return A->getOption().matches(options::OPT_msoft_float) ||
00152          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
00153           A->getValue() == StringRef("soft"));
00154 }
00155 
00156 StringRef MachO::getMachOArchName(const ArgList &Args) const {
00157   switch (getTriple().getArch()) {
00158   default:
00159     return getDefaultUniversalArchName();
00160 
00161   case llvm::Triple::aarch64:
00162     return "arm64";
00163 
00164   case llvm::Triple::thumb:
00165   case llvm::Triple::arm: {
00166     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
00167       if (const char *Arch = GetArmArchForMArch(A->getValue()))
00168         return Arch;
00169 
00170     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
00171       if (const char *Arch = GetArmArchForMCpu(A->getValue()))
00172         return Arch;
00173 
00174     return "arm";
00175   }
00176   }
00177 }
00178 
00179 Darwin::~Darwin() {
00180 }
00181 
00182 MachO::~MachO() {
00183 }
00184 
00185 
00186 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
00187                                                     types::ID InputType) const {
00188   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
00189 
00190   return Triple.getTriple();
00191 }
00192 
00193 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
00194                                                 types::ID InputType) const {
00195   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
00196 
00197   // If the target isn't initialized (e.g., an unknown Darwin platform, return
00198   // the default triple).
00199   if (!isTargetInitialized())
00200     return Triple.getTriple();
00201 
00202   SmallString<16> Str;
00203   Str += isTargetIOSBased() ? "ios" : "macosx";
00204   Str += getTargetVersion().getAsString();
00205   Triple.setOSName(Str);
00206 
00207   return Triple.getTriple();
00208 }
00209 
00210 void Generic_ELF::anchor() {}
00211 
00212 Tool *MachO::getTool(Action::ActionClass AC) const {
00213   switch (AC) {
00214   case Action::LipoJobClass:
00215     if (!Lipo)
00216       Lipo.reset(new tools::darwin::Lipo(*this));
00217     return Lipo.get();
00218   case Action::DsymutilJobClass:
00219     if (!Dsymutil)
00220       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
00221     return Dsymutil.get();
00222   case Action::VerifyDebugInfoJobClass:
00223     if (!VerifyDebug)
00224       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
00225     return VerifyDebug.get();
00226   default:
00227     return ToolChain::getTool(AC);
00228   }
00229 }
00230 
00231 Tool *MachO::buildLinker() const {
00232   return new tools::darwin::Link(*this);
00233 }
00234 
00235 Tool *MachO::buildAssembler() const {
00236   return new tools::darwin::Assemble(*this);
00237 }
00238 
00239 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
00240                          const ArgList &Args)
00241   : Darwin(D, Triple, Args) {
00242 }
00243 
00244 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
00245   // For iOS, 64-bit, promote certain warnings to errors.
00246   if (!isTargetMacOS() && getTriple().isArch64Bit()) {
00247     // Always enable -Wdeprecated-objc-isa-usage and promote it
00248     // to an error.
00249     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
00250     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
00251 
00252     // Also error about implicit function declarations, as that
00253     // can impact calling conventions.
00254     CC1Args.push_back("-Werror=implicit-function-declaration");
00255   }
00256 }
00257 
00258 /// \brief Determine whether Objective-C automated reference counting is
00259 /// enabled.
00260 static bool isObjCAutoRefCount(const ArgList &Args) {
00261   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
00262 }
00263 
00264 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
00265                                  ArgStringList &CmdArgs) const {
00266   // Avoid linking compatibility stubs on i386 mac.
00267   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
00268     return;
00269 
00270   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
00271 
00272   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
00273       runtime.hasSubscripting())
00274     return;
00275 
00276   CmdArgs.push_back("-force_load");
00277   SmallString<128> P(getDriver().ClangExecutable);
00278   llvm::sys::path::remove_filename(P); // 'clang'
00279   llvm::sys::path::remove_filename(P); // 'bin'
00280   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
00281   // Mash in the platform.
00282   if (isTargetIOSSimulator())
00283     P += "iphonesimulator";
00284   else if (isTargetIPhoneOS())
00285     P += "iphoneos";
00286   else
00287     P += "macosx";
00288   P += ".a";
00289 
00290   CmdArgs.push_back(Args.MakeArgString(P));
00291 }
00292 
00293 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
00294                               StringRef DarwinLibName, bool AlwaysLink,
00295                               bool IsEmbedded, bool AddRPath) const {
00296   SmallString<128> Dir(getDriver().ResourceDir);
00297   llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
00298 
00299   SmallString<128> P(Dir);
00300   llvm::sys::path::append(P, DarwinLibName);
00301 
00302   // For now, allow missing resource libraries to support developers who may
00303   // not have compiler-rt checked out or integrated into their build (unless
00304   // we explicitly force linking with this library).
00305   if (AlwaysLink || llvm::sys::fs::exists(P.str()))
00306     CmdArgs.push_back(Args.MakeArgString(P.str()));
00307 
00308   // Adding the rpaths might negatively interact when other rpaths are involved,
00309   // so we should make sure we add the rpaths last, after all user-specified
00310   // rpaths. This is currently true from this place, but we need to be
00311   // careful if this function is ever called before user's rpaths are emitted.
00312   if (AddRPath) {
00313     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
00314 
00315     // Add @executable_path to rpath to support having the dylib copied with
00316     // the executable.
00317     CmdArgs.push_back("-rpath");
00318     CmdArgs.push_back("@executable_path");
00319 
00320     // Add the path to the resource dir to rpath to support using the dylib
00321     // from the default location without copying.
00322     CmdArgs.push_back("-rpath");
00323     CmdArgs.push_back(Args.MakeArgString(Dir.str()));
00324   }
00325 }
00326 
00327 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
00328                                         ArgStringList &CmdArgs) const {
00329   // Darwin only supports the compiler-rt based runtime libraries.
00330   switch (GetRuntimeLibType(Args)) {
00331   case ToolChain::RLT_CompilerRT:
00332     break;
00333   default:
00334     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
00335       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
00336     return;
00337   }
00338 
00339   // Darwin doesn't support real static executables, don't link any runtime
00340   // libraries with -static.
00341   if (Args.hasArg(options::OPT_static) ||
00342       Args.hasArg(options::OPT_fapple_kext) ||
00343       Args.hasArg(options::OPT_mkernel))
00344     return;
00345 
00346   // Reject -static-libgcc for now, we can deal with this when and if someone
00347   // cares. This is useful in situations where someone wants to statically link
00348   // something like libstdc++, and needs its runtime support routines.
00349   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
00350     getDriver().Diag(diag::err_drv_unsupported_opt)
00351       << A->getAsString(Args);
00352     return;
00353   }
00354 
00355   // If we are building profile support, link that library in.
00356   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
00357                    false) ||
00358       Args.hasArg(options::OPT_fprofile_generate) ||
00359       Args.hasArg(options::OPT_fprofile_instr_generate) ||
00360       Args.hasArg(options::OPT_fcreate_profile) ||
00361       Args.hasArg(options::OPT_coverage)) {
00362     // Select the appropriate runtime library for the target.
00363     if (isTargetIOSBased())
00364       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
00365     else
00366       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
00367   }
00368 
00369   const SanitizerArgs &Sanitize = getSanitizerArgs();
00370 
00371   // Add Ubsan runtime library, if required.
00372   if (Sanitize.needsUbsanRt()) {
00373     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
00374     if (isTargetIOSBased()) {
00375       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
00376         << "-fsanitize=undefined";
00377     } else {
00378       assert(isTargetMacOS() && "unexpected non OS X target");
00379       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
00380 
00381       // The Ubsan runtime library requires C++.
00382       AddCXXStdlibLibArgs(Args, CmdArgs);
00383     }
00384   }
00385 
00386   // Add ASAN runtime library, if required. Dynamic libraries and bundles
00387   // should not be linked with the runtime library.
00388   if (Sanitize.needsAsanRt()) {
00389     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
00390     if (isTargetIPhoneOS()) {
00391       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
00392         << "-fsanitize=address";
00393     } else {
00394       if (!Args.hasArg(options::OPT_dynamiclib) &&
00395           !Args.hasArg(options::OPT_bundle)) {
00396         // The ASAN runtime library requires C++.
00397         AddCXXStdlibLibArgs(Args, CmdArgs);
00398       }
00399       if (isTargetMacOS()) {
00400         AddLinkRuntimeLib(Args, CmdArgs,
00401                           "libclang_rt.asan_osx_dynamic.dylib",
00402                           /*AlwaysLink*/ true, /*IsEmbedded*/ false,
00403                           /*AddRPath*/ true);
00404       } else {
00405         if (isTargetIOSSimulator()) {
00406           AddLinkRuntimeLib(Args, CmdArgs,
00407                             "libclang_rt.asan_iossim_dynamic.dylib",
00408                             /*AlwaysLink*/ true, /*IsEmbedded*/ false,
00409                             /*AddRPath*/ true);
00410         }
00411       }
00412     }
00413   }
00414 
00415   // Otherwise link libSystem, then the dynamic runtime library, and finally any
00416   // target specific static runtime library.
00417   CmdArgs.push_back("-lSystem");
00418 
00419   // Select the dynamic runtime library and the target specific static library.
00420   if (isTargetIOSBased()) {
00421     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
00422     // it never went into the SDK.
00423     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
00424     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
00425         getTriple().getArch() != llvm::Triple::aarch64)
00426       CmdArgs.push_back("-lgcc_s.1");
00427 
00428     // We currently always need a static runtime library for iOS.
00429     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
00430   } else {
00431     assert(isTargetMacOS() && "unexpected non MacOS platform");
00432     // The dynamic runtime library was merged with libSystem for 10.6 and
00433     // beyond; only 10.4 and 10.5 need an additional runtime library.
00434     if (isMacosxVersionLT(10, 5))
00435       CmdArgs.push_back("-lgcc_s.10.4");
00436     else if (isMacosxVersionLT(10, 6))
00437       CmdArgs.push_back("-lgcc_s.10.5");
00438 
00439     // For OS X, we thought we would only need a static runtime library when
00440     // targeting 10.4, to provide versions of the static functions which were
00441     // omitted from 10.4.dylib.
00442     //
00443     // Unfortunately, that turned out to not be true, because Darwin system
00444     // headers can still use eprintf on i386, and it is not exported from
00445     // libSystem. Therefore, we still must provide a runtime library just for
00446     // the tiny tiny handful of projects that *might* use that symbol.
00447     if (isMacosxVersionLT(10, 5)) {
00448       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
00449     } else {
00450       if (getTriple().getArch() == llvm::Triple::x86)
00451         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
00452       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
00453     }
00454   }
00455 }
00456 
00457 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
00458   const OptTable &Opts = getDriver().getOpts();
00459 
00460   // Support allowing the SDKROOT environment variable used by xcrun and other
00461   // Xcode tools to define the default sysroot, by making it the default for
00462   // isysroot.
00463   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
00464     // Warn if the path does not exist.
00465     if (!llvm::sys::fs::exists(A->getValue()))
00466       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
00467   } else {
00468     if (char *env = ::getenv("SDKROOT")) {
00469       // We only use this value as the default if it is an absolute path,
00470       // exists, and it is not the root path.
00471       if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
00472           StringRef(env) != "/") {
00473         Args.append(Args.MakeSeparateArg(
00474                       nullptr, Opts.getOption(options::OPT_isysroot), env));
00475       }
00476     }
00477   }
00478 
00479   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
00480   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
00481 
00482   if (OSXVersion && iOSVersion) {
00483     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
00484           << OSXVersion->getAsString(Args)
00485           << iOSVersion->getAsString(Args);
00486     iOSVersion = nullptr;
00487   } else if (!OSXVersion && !iOSVersion) {
00488     // If no deployment target was specified on the command line, check for
00489     // environment defines.
00490     StringRef OSXTarget;
00491     StringRef iOSTarget;
00492     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
00493       OSXTarget = env;
00494     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
00495       iOSTarget = env;
00496 
00497     // If no '-miphoneos-version-min' specified on the command line and
00498     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
00499     // based on -isysroot.
00500     if (iOSTarget.empty()) {
00501       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
00502         StringRef first, second;
00503         StringRef isysroot = A->getValue();
00504         std::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
00505         if (second != "")
00506           iOSTarget = second.substr(0,3);
00507       }
00508     }
00509 
00510     // If no OSX or iOS target has been specified and we're compiling for armv7,
00511     // go ahead as assume we're targeting iOS.
00512     StringRef MachOArchName = getMachOArchName(Args);
00513     if (OSXTarget.empty() && iOSTarget.empty() &&
00514         (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
00515          MachOArchName == "arm64"))
00516         iOSTarget = iOSVersionMin;
00517 
00518     // Allow conflicts among OSX and iOS for historical reasons, but choose the
00519     // default platform.
00520     if (!OSXTarget.empty() && !iOSTarget.empty()) {
00521       if (getTriple().getArch() == llvm::Triple::arm ||
00522           getTriple().getArch() == llvm::Triple::aarch64 ||
00523           getTriple().getArch() == llvm::Triple::thumb)
00524         OSXTarget = "";
00525       else
00526         iOSTarget = "";
00527     }
00528 
00529     if (!OSXTarget.empty()) {
00530       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
00531       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
00532       Args.append(OSXVersion);
00533     } else if (!iOSTarget.empty()) {
00534       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
00535       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
00536       Args.append(iOSVersion);
00537     } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
00538                MachOArchName != "armv7em") {
00539       // Otherwise, assume we are targeting OS X.
00540       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
00541       OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin);
00542       Args.append(OSXVersion);
00543     }
00544   }
00545 
00546   DarwinPlatformKind Platform;
00547   if (OSXVersion)
00548     Platform = MacOS;
00549   else if (iOSVersion)
00550     Platform = IPhoneOS;
00551   else
00552     llvm_unreachable("Unable to infer Darwin variant");
00553 
00554   // Set the tool chain target information.
00555   unsigned Major, Minor, Micro;
00556   bool HadExtra;
00557   if (Platform == MacOS) {
00558     assert(!iOSVersion && "Unknown target platform!");
00559     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
00560                                    Micro, HadExtra) || HadExtra ||
00561         Major != 10 || Minor >= 100 || Micro >= 100)
00562       getDriver().Diag(diag::err_drv_invalid_version_number)
00563         << OSXVersion->getAsString(Args);
00564   } else if (Platform == IPhoneOS) {
00565     assert(iOSVersion && "Unknown target platform!");
00566     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor,
00567                                    Micro, HadExtra) || HadExtra ||
00568         Major >= 10 || Minor >= 100 || Micro >= 100)
00569       getDriver().Diag(diag::err_drv_invalid_version_number)
00570         << iOSVersion->getAsString(Args);
00571   } else
00572     llvm_unreachable("unknown kind of Darwin platform");
00573 
00574   // Recognize iOS targets with an x86 architecture as the iOS simulator.
00575   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
00576                      getTriple().getArch() == llvm::Triple::x86_64))
00577     Platform = IPhoneOSSimulator;
00578 
00579   setTarget(Platform, Major, Minor, Micro);
00580 }
00581 
00582 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
00583                                       ArgStringList &CmdArgs) const {
00584   CXXStdlibType Type = GetCXXStdlibType(Args);
00585 
00586   switch (Type) {
00587   case ToolChain::CST_Libcxx:
00588     CmdArgs.push_back("-lc++");
00589     break;
00590 
00591   case ToolChain::CST_Libstdcxx: {
00592     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
00593     // it was previously found in the gcc lib dir. However, for all the Darwin
00594     // platforms we care about it was -lstdc++.6, so we search for that
00595     // explicitly if we can't see an obvious -lstdc++ candidate.
00596 
00597     // Check in the sysroot first.
00598     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
00599       SmallString<128> P(A->getValue());
00600       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
00601 
00602       if (!llvm::sys::fs::exists(P.str())) {
00603         llvm::sys::path::remove_filename(P);
00604         llvm::sys::path::append(P, "libstdc++.6.dylib");
00605         if (llvm::sys::fs::exists(P.str())) {
00606           CmdArgs.push_back(Args.MakeArgString(P.str()));
00607           return;
00608         }
00609       }
00610     }
00611 
00612     // Otherwise, look in the root.
00613     // FIXME: This should be removed someday when we don't have to care about
00614     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
00615     if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
00616         llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
00617       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
00618       return;
00619     }
00620 
00621     // Otherwise, let the linker search.
00622     CmdArgs.push_back("-lstdc++");
00623     break;
00624   }
00625   }
00626 }
00627 
00628 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
00629                                    ArgStringList &CmdArgs) const {
00630 
00631   // For Darwin platforms, use the compiler-rt-based support library
00632   // instead of the gcc-provided one (which is also incidentally
00633   // only present in the gcc lib dir, which makes it hard to find).
00634 
00635   SmallString<128> P(getDriver().ResourceDir);
00636   llvm::sys::path::append(P, "lib", "darwin");
00637 
00638   // Use the newer cc_kext for iOS ARM after 6.0.
00639   if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
00640       getTriple().getArch() == llvm::Triple::aarch64 ||
00641       !isIPhoneOSVersionLT(6, 0)) {
00642     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
00643   } else {
00644     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
00645   }
00646 
00647   // For now, allow missing resource libraries to support developers who may
00648   // not have compiler-rt checked out or integrated into their build.
00649   if (llvm::sys::fs::exists(P.str()))
00650     CmdArgs.push_back(Args.MakeArgString(P.str()));
00651 }
00652 
00653 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
00654                                      const char *BoundArch) const {
00655   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
00656   const OptTable &Opts = getDriver().getOpts();
00657 
00658   // FIXME: We really want to get out of the tool chain level argument
00659   // translation business, as it makes the driver functionality much
00660   // more opaque. For now, we follow gcc closely solely for the
00661   // purpose of easily achieving feature parity & testability. Once we
00662   // have something that works, we should reevaluate each translation
00663   // and try to push it down into tool specific logic.
00664 
00665   for (Arg *A : Args) {
00666     if (A->getOption().matches(options::OPT_Xarch__)) {
00667       // Skip this argument unless the architecture matches either the toolchain
00668       // triple arch, or the arch being bound.
00669       llvm::Triple::ArchType XarchArch =
00670         tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
00671       if (!(XarchArch == getArch()  ||
00672             (BoundArch && XarchArch ==
00673              tools::darwin::getArchTypeForMachOArchName(BoundArch))))
00674         continue;
00675 
00676       Arg *OriginalArg = A;
00677       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
00678       unsigned Prev = Index;
00679       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
00680 
00681       // If the argument parsing failed or more than one argument was
00682       // consumed, the -Xarch_ argument's parameter tried to consume
00683       // extra arguments. Emit an error and ignore.
00684       //
00685       // We also want to disallow any options which would alter the
00686       // driver behavior; that isn't going to work in our model. We
00687       // use isDriverOption() as an approximation, although things
00688       // like -O4 are going to slip through.
00689       if (!XarchArg || Index > Prev + 1) {
00690         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
00691           << A->getAsString(Args);
00692         continue;
00693       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
00694         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
00695           << A->getAsString(Args);
00696         continue;
00697       }
00698 
00699       XarchArg->setBaseArg(A);
00700 
00701       A = XarchArg.release();
00702       DAL->AddSynthesizedArg(A);
00703 
00704       // Linker input arguments require custom handling. The problem is that we
00705       // have already constructed the phase actions, so we can not treat them as
00706       // "input arguments".
00707       if (A->getOption().hasFlag(options::LinkerInput)) {
00708         // Convert the argument into individual Zlinker_input_args.
00709         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
00710           DAL->AddSeparateArg(OriginalArg,
00711                               Opts.getOption(options::OPT_Zlinker_input),
00712                               A->getValue(i));
00713 
00714         }
00715         continue;
00716       }
00717     }
00718 
00719     // Sob. These is strictly gcc compatible for the time being. Apple
00720     // gcc translates options twice, which means that self-expanding
00721     // options add duplicates.
00722     switch ((options::ID) A->getOption().getID()) {
00723     default:
00724       DAL->append(A);
00725       break;
00726 
00727     case options::OPT_mkernel:
00728     case options::OPT_fapple_kext:
00729       DAL->append(A);
00730       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
00731       break;
00732 
00733     case options::OPT_dependency_file:
00734       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
00735                           A->getValue());
00736       break;
00737 
00738     case options::OPT_gfull:
00739       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
00740       DAL->AddFlagArg(A,
00741                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
00742       break;
00743 
00744     case options::OPT_gused:
00745       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
00746       DAL->AddFlagArg(A,
00747              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
00748       break;
00749 
00750     case options::OPT_shared:
00751       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
00752       break;
00753 
00754     case options::OPT_fconstant_cfstrings:
00755       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
00756       break;
00757 
00758     case options::OPT_fno_constant_cfstrings:
00759       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
00760       break;
00761 
00762     case options::OPT_Wnonportable_cfstrings:
00763       DAL->AddFlagArg(A,
00764                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
00765       break;
00766 
00767     case options::OPT_Wno_nonportable_cfstrings:
00768       DAL->AddFlagArg(A,
00769                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
00770       break;
00771 
00772     case options::OPT_fpascal_strings:
00773       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
00774       break;
00775 
00776     case options::OPT_fno_pascal_strings:
00777       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
00778       break;
00779     }
00780   }
00781 
00782   if (getTriple().getArch() == llvm::Triple::x86 ||
00783       getTriple().getArch() == llvm::Triple::x86_64)
00784     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
00785       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
00786                         "core2");
00787 
00788   // Add the arch options based on the particular spelling of -arch, to match
00789   // how the driver driver works.
00790   if (BoundArch) {
00791     StringRef Name = BoundArch;
00792     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
00793     const Option MArch = Opts.getOption(options::OPT_march_EQ);
00794 
00795     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
00796     // which defines the list of which architectures we accept.
00797     if (Name == "ppc")
00798       ;
00799     else if (Name == "ppc601")
00800       DAL->AddJoinedArg(nullptr, MCpu, "601");
00801     else if (Name == "ppc603")
00802       DAL->AddJoinedArg(nullptr, MCpu, "603");
00803     else if (Name == "ppc604")
00804       DAL->AddJoinedArg(nullptr, MCpu, "604");
00805     else if (Name == "ppc604e")
00806       DAL->AddJoinedArg(nullptr, MCpu, "604e");
00807     else if (Name == "ppc750")
00808       DAL->AddJoinedArg(nullptr, MCpu, "750");
00809     else if (Name == "ppc7400")
00810       DAL->AddJoinedArg(nullptr, MCpu, "7400");
00811     else if (Name == "ppc7450")
00812       DAL->AddJoinedArg(nullptr, MCpu, "7450");
00813     else if (Name == "ppc970")
00814       DAL->AddJoinedArg(nullptr, MCpu, "970");
00815 
00816     else if (Name == "ppc64" || Name == "ppc64le")
00817       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
00818 
00819     else if (Name == "i386")
00820       ;
00821     else if (Name == "i486")
00822       DAL->AddJoinedArg(nullptr, MArch, "i486");
00823     else if (Name == "i586")
00824       DAL->AddJoinedArg(nullptr, MArch, "i586");
00825     else if (Name == "i686")
00826       DAL->AddJoinedArg(nullptr, MArch, "i686");
00827     else if (Name == "pentium")
00828       DAL->AddJoinedArg(nullptr, MArch, "pentium");
00829     else if (Name == "pentium2")
00830       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
00831     else if (Name == "pentpro")
00832       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
00833     else if (Name == "pentIIm3")
00834       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
00835 
00836     else if (Name == "x86_64")
00837       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
00838     else if (Name == "x86_64h") {
00839       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
00840       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
00841     }
00842 
00843     else if (Name == "arm")
00844       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
00845     else if (Name == "armv4t")
00846       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
00847     else if (Name == "armv5")
00848       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
00849     else if (Name == "xscale")
00850       DAL->AddJoinedArg(nullptr, MArch, "xscale");
00851     else if (Name == "armv6")
00852       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
00853     else if (Name == "armv6m")
00854       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
00855     else if (Name == "armv7")
00856       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
00857     else if (Name == "armv7em")
00858       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
00859     else if (Name == "armv7k")
00860       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
00861     else if (Name == "armv7m")
00862       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
00863     else if (Name == "armv7s")
00864       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
00865   }
00866 
00867   return DAL;
00868 }
00869 
00870 void MachO::AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args,
00871                                   llvm::opt::ArgStringList &CmdArgs) const {
00872   // Embedded targets are simple at the moment, not supporting sanitizers and
00873   // with different libraries for each member of the product { static, PIC } x
00874   // { hard-float, soft-float }
00875   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
00876   CompilerRT +=
00877       tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
00878           ? "hard"
00879           : "soft";
00880   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
00881 
00882   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
00883 }
00884 
00885 
00886 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
00887                                       const char *BoundArch) const {
00888   // First get the generic Apple args, before moving onto Darwin-specific ones.
00889   DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
00890   const OptTable &Opts = getDriver().getOpts();
00891 
00892   // If no architecture is bound, none of the translations here are relevant.
00893   if (!BoundArch)
00894     return DAL;
00895 
00896   // Add an explicit version min argument for the deployment target. We do this
00897   // after argument translation because -Xarch_ arguments may add a version min
00898   // argument.
00899   AddDeploymentTarget(*DAL);
00900 
00901   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
00902   // FIXME: It would be far better to avoid inserting those -static arguments,
00903   // but we can't check the deployment target in the translation code until
00904   // it is set here.
00905   if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0) &&
00906       getTriple().getArch() != llvm::Triple::aarch64) {
00907     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
00908       Arg *A = *it;
00909       ++it;
00910       if (A->getOption().getID() != options::OPT_mkernel &&
00911           A->getOption().getID() != options::OPT_fapple_kext)
00912         continue;
00913       assert(it != ie && "unexpected argument translation");
00914       A = *it;
00915       assert(A->getOption().getID() == options::OPT_static &&
00916              "missing expected -static argument");
00917       it = DAL->getArgs().erase(it);
00918     }
00919   }
00920 
00921   // Default to use libc++ on OS X 10.9+ and iOS 7+.
00922   if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
00923        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
00924       !Args.getLastArg(options::OPT_stdlib_EQ))
00925     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
00926                       "libc++");
00927 
00928   // Validate the C++ standard library choice.
00929   CXXStdlibType Type = GetCXXStdlibType(*DAL);
00930   if (Type == ToolChain::CST_Libcxx) {
00931     // Check whether the target provides libc++.
00932     StringRef where;
00933 
00934     // Complain about targeting iOS < 5.0 in any way.
00935     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
00936       where = "iOS 5.0";
00937 
00938     if (where != StringRef()) {
00939       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
00940         << where;
00941     }
00942   }
00943 
00944   return DAL;
00945 }
00946 
00947 bool MachO::IsUnwindTablesDefault() const {
00948   return getArch() == llvm::Triple::x86_64;
00949 }
00950 
00951 bool MachO::UseDwarfDebugFlags() const {
00952   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
00953     return S[0] != '\0';
00954   return false;
00955 }
00956 
00957 bool Darwin::UseSjLjExceptions() const {
00958   // Darwin uses SjLj exceptions on ARM.
00959   return (getTriple().getArch() == llvm::Triple::arm ||
00960           getTriple().getArch() == llvm::Triple::thumb);
00961 }
00962 
00963 bool MachO::isPICDefault() const {
00964   return true;
00965 }
00966 
00967 bool MachO::isPIEDefault() const {
00968   return false;
00969 }
00970 
00971 bool MachO::isPICDefaultForced() const {
00972   return (getArch() == llvm::Triple::x86_64 ||
00973           getArch() == llvm::Triple::aarch64);
00974 }
00975 
00976 bool MachO::SupportsProfiling() const {
00977   // Profiling instrumentation is only supported on x86.
00978   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
00979 }
00980 
00981 void Darwin::addMinVersionArgs(const llvm::opt::ArgList &Args,
00982                                llvm::opt::ArgStringList &CmdArgs) const {
00983   VersionTuple TargetVersion = getTargetVersion();
00984 
00985   if (isTargetIOSSimulator())
00986     CmdArgs.push_back("-ios_simulator_version_min");
00987   else if (isTargetIOSBased())
00988     CmdArgs.push_back("-iphoneos_version_min");
00989   else {
00990     assert(isTargetMacOS() && "unexpected target");
00991     CmdArgs.push_back("-macosx_version_min");
00992   }
00993 
00994   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
00995 }
00996 
00997 void Darwin::addStartObjectFileArgs(const llvm::opt::ArgList &Args,
00998                                     llvm::opt::ArgStringList &CmdArgs) const {
00999   // Derived from startfile spec.
01000   if (Args.hasArg(options::OPT_dynamiclib)) {
01001     // Derived from darwin_dylib1 spec.
01002     if (isTargetIOSSimulator()) {
01003       ; // iOS simulator does not need dylib1.o.
01004     } else if (isTargetIPhoneOS()) {
01005       if (isIPhoneOSVersionLT(3, 1))
01006         CmdArgs.push_back("-ldylib1.o");
01007     } else {
01008       if (isMacosxVersionLT(10, 5))
01009         CmdArgs.push_back("-ldylib1.o");
01010       else if (isMacosxVersionLT(10, 6))
01011         CmdArgs.push_back("-ldylib1.10.5.o");
01012     }
01013   } else {
01014     if (Args.hasArg(options::OPT_bundle)) {
01015       if (!Args.hasArg(options::OPT_static)) {
01016         // Derived from darwin_bundle1 spec.
01017         if (isTargetIOSSimulator()) {
01018           ; // iOS simulator does not need bundle1.o.
01019         } else if (isTargetIPhoneOS()) {
01020           if (isIPhoneOSVersionLT(3, 1))
01021             CmdArgs.push_back("-lbundle1.o");
01022         } else {
01023           if (isMacosxVersionLT(10, 6))
01024             CmdArgs.push_back("-lbundle1.o");
01025         }
01026       }
01027     } else {
01028       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
01029         if (Args.hasArg(options::OPT_static) ||
01030             Args.hasArg(options::OPT_object) ||
01031             Args.hasArg(options::OPT_preload)) {
01032           CmdArgs.push_back("-lgcrt0.o");
01033         } else {
01034           CmdArgs.push_back("-lgcrt1.o");
01035 
01036           // darwin_crt2 spec is empty.
01037         }
01038         // By default on OS X 10.8 and later, we don't link with a crt1.o
01039         // file and the linker knows to use _main as the entry point.  But,
01040         // when compiling with -pg, we need to link with the gcrt1.o file,
01041         // so pass the -no_new_main option to tell the linker to use the
01042         // "start" symbol as the entry point.
01043         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
01044           CmdArgs.push_back("-no_new_main");
01045       } else {
01046         if (Args.hasArg(options::OPT_static) ||
01047             Args.hasArg(options::OPT_object) ||
01048             Args.hasArg(options::OPT_preload)) {
01049           CmdArgs.push_back("-lcrt0.o");
01050         } else {
01051           // Derived from darwin_crt1 spec.
01052           if (isTargetIOSSimulator()) {
01053             ; // iOS simulator does not need crt1.o.
01054           } else if (isTargetIPhoneOS()) {
01055             if (getArch() == llvm::Triple::aarch64)
01056               ; // iOS does not need any crt1 files for arm64
01057             else if (isIPhoneOSVersionLT(3, 1))
01058               CmdArgs.push_back("-lcrt1.o");
01059             else if (isIPhoneOSVersionLT(6, 0))
01060               CmdArgs.push_back("-lcrt1.3.1.o");
01061           } else {
01062             if (isMacosxVersionLT(10, 5))
01063               CmdArgs.push_back("-lcrt1.o");
01064             else if (isMacosxVersionLT(10, 6))
01065               CmdArgs.push_back("-lcrt1.10.5.o");
01066             else if (isMacosxVersionLT(10, 8))
01067               CmdArgs.push_back("-lcrt1.10.6.o");
01068 
01069             // darwin_crt2 spec is empty.
01070           }
01071         }
01072       }
01073     }
01074   }
01075 
01076   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
01077       isMacosxVersionLT(10, 5)) {
01078     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
01079     CmdArgs.push_back(Str);
01080   }
01081 }
01082 
01083 bool Darwin::SupportsObjCGC() const {
01084   return isTargetMacOS();
01085 }
01086 
01087 void Darwin::CheckObjCARC() const {
01088   if (isTargetIOSBased()|| (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
01089     return;
01090   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
01091 }
01092 
01093 /// Generic_GCC - A tool chain using the 'gcc' command to perform
01094 /// all subcommands; this relies on gcc translating the majority of
01095 /// command line options.
01096 
01097 /// \brief Parse a GCCVersion object out of a string of text.
01098 ///
01099 /// This is the primary means of forming GCCVersion objects.
01100 /*static*/
01101 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
01102   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
01103   std::pair<StringRef, StringRef> First = VersionText.split('.');
01104   std::pair<StringRef, StringRef> Second = First.second.split('.');
01105 
01106   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
01107   if (First.first.getAsInteger(10, GoodVersion.Major) ||
01108       GoodVersion.Major < 0)
01109     return BadVersion;
01110   GoodVersion.MajorStr = First.first.str();
01111   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
01112       GoodVersion.Minor < 0)
01113     return BadVersion;
01114   GoodVersion.MinorStr = Second.first.str();
01115 
01116   // First look for a number prefix and parse that if present. Otherwise just
01117   // stash the entire patch string in the suffix, and leave the number
01118   // unspecified. This covers versions strings such as:
01119   //   4.4
01120   //   4.4.0
01121   //   4.4.x
01122   //   4.4.2-rc4
01123   //   4.4.x-patched
01124   // And retains any patch number it finds.
01125   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
01126   if (!PatchText.empty()) {
01127     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
01128       // Try to parse the number and any suffix.
01129       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
01130           GoodVersion.Patch < 0)
01131         return BadVersion;
01132       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
01133     }
01134   }
01135 
01136   return GoodVersion;
01137 }
01138 
01139 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
01140 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
01141                                           int RHSPatch,
01142                                           StringRef RHSPatchSuffix) const {
01143   if (Major != RHSMajor)
01144     return Major < RHSMajor;
01145   if (Minor != RHSMinor)
01146     return Minor < RHSMinor;
01147   if (Patch != RHSPatch) {
01148     // Note that versions without a specified patch sort higher than those with
01149     // a patch.
01150     if (RHSPatch == -1)
01151       return true;
01152     if (Patch == -1)
01153       return false;
01154 
01155     // Otherwise just sort on the patch itself.
01156     return Patch < RHSPatch;
01157   }
01158   if (PatchSuffix != RHSPatchSuffix) {
01159     // Sort empty suffixes higher.
01160     if (RHSPatchSuffix.empty())
01161       return true;
01162     if (PatchSuffix.empty())
01163       return false;
01164 
01165     // Provide a lexicographic sort to make this a total ordering.
01166     return PatchSuffix < RHSPatchSuffix;
01167   }
01168 
01169   // The versions are equal.
01170   return false;
01171 }
01172 
01173 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
01174   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
01175   if (A)
01176     return A->getValue();
01177   return GCC_INSTALL_PREFIX;
01178 }
01179 
01180 /// \brief Initialize a GCCInstallationDetector from the driver.
01181 ///
01182 /// This performs all of the autodetection and sets up the various paths.
01183 /// Once constructed, a GCCInstallationDetector is essentially immutable.
01184 ///
01185 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
01186 /// should instead pull the target out of the driver. This is currently
01187 /// necessary because the driver doesn't store the final version of the target
01188 /// triple.
01189 void
01190 Generic_GCC::GCCInstallationDetector::init(
01191     const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
01192   llvm::Triple BiarchVariantTriple =
01193       TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
01194                                  : TargetTriple.get32BitArchVariant();
01195   // The library directories which may contain GCC installations.
01196   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
01197   // The compatible GCC triples for this particular architecture.
01198   SmallVector<StringRef, 16> CandidateTripleAliases;
01199   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
01200   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
01201                            CandidateTripleAliases, CandidateBiarchLibDirs,
01202                            CandidateBiarchTripleAliases);
01203 
01204   // Compute the set of prefixes for our search.
01205   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
01206                                        D.PrefixDirs.end());
01207 
01208   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
01209   if (GCCToolchainDir != "") {
01210     if (GCCToolchainDir.back() == '/')
01211       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
01212 
01213     Prefixes.push_back(GCCToolchainDir);
01214   } else {
01215     // If we have a SysRoot, try that first.
01216     if (!D.SysRoot.empty()) {
01217       Prefixes.push_back(D.SysRoot);
01218       Prefixes.push_back(D.SysRoot + "/usr");
01219     }
01220 
01221     // Then look for gcc installed alongside clang.
01222     Prefixes.push_back(D.InstalledDir + "/..");
01223 
01224     // And finally in /usr.
01225     if (D.SysRoot.empty())
01226       Prefixes.push_back("/usr");
01227   }
01228 
01229   // Loop over the various components which exist and select the best GCC
01230   // installation available. GCC installs are ranked by version number.
01231   Version = GCCVersion::Parse("0.0.0");
01232   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
01233     if (!llvm::sys::fs::exists(Prefixes[i]))
01234       continue;
01235     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
01236       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
01237       if (!llvm::sys::fs::exists(LibDir))
01238         continue;
01239       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
01240         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
01241                                CandidateTripleAliases[k]);
01242     }
01243     for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
01244       const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
01245       if (!llvm::sys::fs::exists(LibDir))
01246         continue;
01247       for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
01248            ++k)
01249         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
01250                                CandidateBiarchTripleAliases[k],
01251                                /*NeedsBiarchSuffix=*/ true);
01252     }
01253   }
01254 }
01255 
01256 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
01257   for (const auto &InstallPath : CandidateGCCInstallPaths)
01258     OS << "Found candidate GCC installation: " << InstallPath << "\n";
01259 
01260   if (!GCCInstallPath.empty())
01261     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
01262 
01263   for (const auto &Multilib : Multilibs)
01264     OS << "Candidate multilib: " << Multilib << "\n";
01265 
01266   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
01267     OS << "Selected multilib: " << SelectedMultilib << "\n";
01268 }
01269 
01270 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
01271   if (BiarchSibling.hasValue()) {
01272     M = BiarchSibling.getValue();
01273     return true;
01274   }
01275   return false;
01276 }
01277 
01278 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
01279     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
01280     SmallVectorImpl<StringRef> &LibDirs,
01281     SmallVectorImpl<StringRef> &TripleAliases,
01282     SmallVectorImpl<StringRef> &BiarchLibDirs,
01283     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
01284   // Declare a bunch of static data sets that we'll select between below. These
01285   // are specifically designed to always refer to string literals to avoid any
01286   // lifetime or initialization issues.
01287   static const char *const AArch64LibDirs[] = { "/lib64", "/lib" };
01288   static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
01289                                                 "aarch64-linux-gnu",
01290                                                 "aarch64-linux-android",
01291                                                 "aarch64-redhat-linux" };
01292   static const char *const AArch64beLibDirs[] = { "/lib" };
01293   static const char *const AArch64beTriples[] = { "aarch64_be-none-linux-gnu",
01294                                                   "aarch64_be-linux-gnu" };
01295 
01296   static const char *const ARMLibDirs[] = { "/lib" };
01297   static const char *const ARMTriples[] = { "arm-linux-gnueabi",
01298                                             "arm-linux-androideabi" };
01299   static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
01300                                               "armv7hl-redhat-linux-gnueabi" };
01301   static const char *const ARMebLibDirs[] = { "/lib" };
01302   static const char *const ARMebTriples[] = { "armeb-linux-gnueabi",
01303                                               "armeb-linux-androideabi" };
01304   static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
01305                                                 "armebv7hl-redhat-linux-gnueabi" };
01306 
01307   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
01308   static const char *const X86_64Triples[] = {
01309     "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
01310     "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
01311     "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
01312     "x86_64-linux-android", "x86_64-unknown-linux"
01313   };
01314   static const char *const X32LibDirs[] = { "/libx32" };
01315   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
01316   static const char *const X86Triples[] = {
01317     "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
01318     "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
01319     "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
01320     "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
01321   };
01322 
01323   static const char *const MIPSLibDirs[] = { "/lib" };
01324   static const char *const MIPSTriples[] = { "mips-linux-gnu",
01325                                              "mips-mti-linux-gnu",
01326                                              "mips-img-linux-gnu" };
01327   static const char *const MIPSELLibDirs[] = { "/lib" };
01328   static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
01329                                                "mipsel-linux-android",
01330                                                "mips-img-linux-gnu" };
01331 
01332   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
01333   static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
01334                                                "mips-mti-linux-gnu",
01335                                                "mips-img-linux-gnu",
01336                                                "mips64-linux-gnuabi64" };
01337   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
01338   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
01339                                                  "mips-mti-linux-gnu",
01340                                                  "mips-img-linux-gnu",
01341                                                  "mips64el-linux-android",
01342                                                  "mips64el-linux-gnuabi64" };
01343 
01344   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
01345   static const char *const PPCTriples[] = {
01346     "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
01347     "powerpc-suse-linux", "powerpc-montavista-linuxspe"
01348   };
01349   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
01350   static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
01351                                               "powerpc64-unknown-linux-gnu",
01352                                               "powerpc64-suse-linux",
01353                                               "ppc64-redhat-linux" };
01354   static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
01355   static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
01356                                                 "powerpc64le-unknown-linux-gnu",
01357                                                 "powerpc64le-suse-linux",
01358                                                 "ppc64le-redhat-linux" };
01359 
01360   static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
01361   static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
01362                                                 "sparcv8-linux-gnu" };
01363   static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
01364   static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
01365                                                 "sparcv9-linux-gnu" };
01366 
01367   static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
01368   static const char *const SystemZTriples[] = {
01369     "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
01370     "s390x-suse-linux", "s390x-redhat-linux"
01371   };
01372 
01373   using std::begin;
01374   using std::end;
01375 
01376   switch (TargetTriple.getArch()) {
01377   case llvm::Triple::aarch64:
01378     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
01379     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
01380     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
01381     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
01382     break;
01383   case llvm::Triple::aarch64_be:
01384     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
01385     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
01386     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
01387     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
01388     break;
01389   case llvm::Triple::arm:
01390   case llvm::Triple::thumb:
01391     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
01392     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
01393       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
01394     } else {
01395       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
01396     }
01397     break;
01398   case llvm::Triple::armeb:
01399   case llvm::Triple::thumbeb:
01400     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
01401     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
01402       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
01403     } else {
01404       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
01405     }
01406     break;
01407   case llvm::Triple::x86_64:
01408     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
01409     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
01410     // x32 is always available when x86_64 is available, so adding it as
01411     // secondary arch with x86_64 triples
01412     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
01413       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
01414       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
01415     } else {
01416       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
01417       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
01418     }
01419     break;
01420   case llvm::Triple::x86:
01421     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
01422     TripleAliases.append(begin(X86Triples), end(X86Triples));
01423     BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
01424     BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
01425     break;
01426   case llvm::Triple::mips:
01427     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
01428     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
01429     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
01430     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
01431     break;
01432   case llvm::Triple::mipsel:
01433     LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
01434     TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
01435     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
01436     BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
01437     BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
01438     break;
01439   case llvm::Triple::mips64:
01440     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
01441     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
01442     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
01443     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
01444     break;
01445   case llvm::Triple::mips64el:
01446     LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
01447     TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
01448     BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
01449     BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
01450     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
01451     break;
01452   case llvm::Triple::ppc:
01453     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
01454     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
01455     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
01456     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
01457     break;
01458   case llvm::Triple::ppc64:
01459     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
01460     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
01461     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
01462     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
01463     break;
01464   case llvm::Triple::ppc64le:
01465     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
01466     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
01467     break;
01468   case llvm::Triple::sparc:
01469     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
01470     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
01471     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
01472     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
01473     break;
01474   case llvm::Triple::sparcv9:
01475     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
01476     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
01477     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
01478     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
01479     break;
01480   case llvm::Triple::systemz:
01481     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
01482     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
01483     break;
01484 
01485   default:
01486     // By default, just rely on the standard lib directories and the original
01487     // triple.
01488     break;
01489   }
01490 
01491   // Always append the drivers target triple to the end, in case it doesn't
01492   // match any of our aliases.
01493   TripleAliases.push_back(TargetTriple.str());
01494 
01495   // Also include the multiarch variant if it's different.
01496   if (TargetTriple.str() != BiarchTriple.str())
01497     BiarchTripleAliases.push_back(BiarchTriple.str());
01498 }
01499 
01500 namespace {
01501 // Filter to remove Multilibs that don't exist as a suffix to Path
01502 class FilterNonExistent : public MultilibSet::FilterCallback {
01503   std::string Base;
01504 public:
01505   FilterNonExistent(std::string Base) : Base(Base) {}
01506   bool operator()(const Multilib &M) const override {
01507     return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
01508   }
01509 };
01510 } // end anonymous namespace
01511 
01512 static void addMultilibFlag(bool Enabled, const char *const Flag,
01513                             std::vector<std::string> &Flags) {
01514   if (Enabled)
01515     Flags.push_back(std::string("+") + Flag);
01516   else
01517     Flags.push_back(std::string("-") + Flag);
01518 }
01519 
01520 static bool isMipsArch(llvm::Triple::ArchType Arch) {
01521   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
01522          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
01523 }
01524 
01525 static bool isMips32(llvm::Triple::ArchType Arch) {
01526   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
01527 }
01528 
01529 static bool isMips64(llvm::Triple::ArchType Arch) {
01530   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
01531 }
01532 
01533 static bool isMipsEL(llvm::Triple::ArchType Arch) {
01534   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
01535 }
01536 
01537 static bool isMips16(const ArgList &Args) {
01538   Arg *A = Args.getLastArg(options::OPT_mips16,
01539                            options::OPT_mno_mips16);
01540   return A && A->getOption().matches(options::OPT_mips16);
01541 }
01542 
01543 static bool isMicroMips(const ArgList &Args) {
01544   Arg *A = Args.getLastArg(options::OPT_mmicromips,
01545                            options::OPT_mno_micromips);
01546   return A && A->getOption().matches(options::OPT_mmicromips);
01547 }
01548 
01549 struct DetectedMultilibs {
01550   /// The set of multilibs that the detected installation supports.
01551   MultilibSet Multilibs;
01552 
01553   /// The primary multilib appropriate for the given flags.
01554   Multilib SelectedMultilib;
01555 
01556   /// On Biarch systems, this corresponds to the default multilib when
01557   /// targeting the non-default multilib. Otherwise, it is empty.
01558   llvm::Optional<Multilib> BiarchSibling;
01559 };
01560 
01561 static Multilib makeMultilib(StringRef commonSuffix) {
01562   return Multilib(commonSuffix, commonSuffix, commonSuffix);
01563 }
01564 
01565 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
01566                               const llvm::opt::ArgList &Args,
01567                               DetectedMultilibs &Result) {
01568   // Some MIPS toolchains put libraries and object files compiled
01569   // using different options in to the sub-directoris which names
01570   // reflects the flags used for compilation. For example sysroot
01571   // directory might looks like the following examples:
01572   //
01573   // /usr
01574   //   /lib      <= crt*.o files compiled with '-mips32'
01575   // /mips16
01576   //   /usr
01577   //     /lib    <= crt*.o files compiled with '-mips16'
01578   //   /el
01579   //     /usr
01580   //       /lib  <= crt*.o files compiled with '-mips16 -EL'
01581   //
01582   // or
01583   //
01584   // /usr
01585   //   /lib      <= crt*.o files compiled with '-mips32r2'
01586   // /mips16
01587   //   /usr
01588   //     /lib    <= crt*.o files compiled with '-mips32r2 -mips16'
01589   // /mips32
01590   //     /usr
01591   //       /lib  <= crt*.o files compiled with '-mips32'
01592 
01593   FilterNonExistent NonExistent(Path);
01594 
01595   // Check for FSF toolchain multilibs
01596   MultilibSet FSFMipsMultilibs;
01597   {
01598     auto MArchMips32 = makeMultilib("/mips32")
01599       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32");
01600 
01601     auto MArchMicroMips = makeMultilib("/micromips")
01602       .flag("+m32").flag("-m64").flag("+mmicromips");
01603 
01604     auto MArchMips64r2 = makeMultilib("/mips64r2")
01605       .flag("-m32").flag("+m64").flag("+march=mips64r2");
01606 
01607     auto MArchMips64 = makeMultilib("/mips64")
01608       .flag("-m32").flag("+m64").flag("-march=mips64r2");
01609 
01610     auto MArchDefault = makeMultilib("")
01611       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32r2");
01612 
01613     auto Mips16 = makeMultilib("/mips16")
01614       .flag("+mips16");
01615 
01616     auto UCLibc = makeMultilib("/uclibc")
01617       .flag("+muclibc");
01618 
01619     auto MAbi64 = makeMultilib("/64")
01620       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
01621 
01622     auto BigEndian = makeMultilib("")
01623       .flag("+EB").flag("-EL");
01624 
01625     auto LittleEndian = makeMultilib("/el")
01626       .flag("+EL").flag("-EB");
01627 
01628     auto SoftFloat = makeMultilib("/sof")
01629       .flag("+msoft-float");
01630 
01631     auto Nan2008 = makeMultilib("/nan2008")
01632       .flag("+mnan=2008");
01633 
01634     FSFMipsMultilibs = MultilibSet()
01635       .Either(MArchMips32, MArchMicroMips, 
01636               MArchMips64r2, MArchMips64, MArchDefault)
01637       .Maybe(UCLibc)
01638       .Maybe(Mips16)
01639       .FilterOut("/mips64/mips16")
01640       .FilterOut("/mips64r2/mips16")
01641       .FilterOut("/micromips/mips16")
01642       .Maybe(MAbi64)
01643       .FilterOut("/micromips/64")
01644       .FilterOut("/mips32/64")
01645       .FilterOut("^/64")
01646       .FilterOut("/mips16/64")
01647       .Either(BigEndian, LittleEndian)
01648       .Maybe(SoftFloat)
01649       .Maybe(Nan2008)
01650       .FilterOut(".*sof/nan2008")
01651       .FilterOut(NonExistent)
01652       .setIncludeDirsCallback([](
01653           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
01654         std::vector<std::string> Dirs;
01655         Dirs.push_back((InstallDir + "/include").str());
01656         std::string SysRootInc = InstallDir.str() + "/../../../../sysroot";
01657         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
01658           Dirs.push_back(SysRootInc + "/uclibc/usr/include");
01659         else
01660           Dirs.push_back(SysRootInc + "/usr/include");
01661         return Dirs;
01662       });
01663   }
01664 
01665   // Check for Code Sourcery toolchain multilibs
01666   MultilibSet CSMipsMultilibs;
01667   {
01668     auto MArchMips16 = makeMultilib("/mips16")
01669       .flag("+m32").flag("+mips16");
01670 
01671     auto MArchMicroMips = makeMultilib("/micromips")
01672       .flag("+m32").flag("+mmicromips");
01673 
01674     auto MArchDefault = makeMultilib("")
01675       .flag("-mips16").flag("-mmicromips");
01676 
01677     auto UCLibc = makeMultilib("/uclibc")
01678       .flag("+muclibc");
01679 
01680     auto SoftFloat = makeMultilib("/soft-float")
01681       .flag("+msoft-float");
01682 
01683     auto Nan2008 = makeMultilib("/nan2008")
01684       .flag("+mnan=2008");
01685 
01686     auto DefaultFloat = makeMultilib("")
01687       .flag("-msoft-float").flag("-mnan=2008");
01688 
01689     auto BigEndian = makeMultilib("")
01690       .flag("+EB").flag("-EL");
01691 
01692     auto LittleEndian = makeMultilib("/el")
01693       .flag("+EL").flag("-EB");
01694 
01695     // Note that this one's osSuffix is ""
01696     auto MAbi64 = makeMultilib("")
01697       .gccSuffix("/64")
01698       .includeSuffix("/64")
01699       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
01700 
01701     CSMipsMultilibs = MultilibSet()
01702       .Either(MArchMips16, MArchMicroMips, MArchDefault)
01703       .Maybe(UCLibc)
01704       .Either(SoftFloat, Nan2008, DefaultFloat)
01705       .FilterOut("/micromips/nan2008")
01706       .FilterOut("/mips16/nan2008")
01707       .Either(BigEndian, LittleEndian)
01708       .Maybe(MAbi64)
01709       .FilterOut("/mips16.*/64")
01710       .FilterOut("/micromips.*/64")
01711       .FilterOut(NonExistent)
01712       .setIncludeDirsCallback([](
01713           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
01714         std::vector<std::string> Dirs;
01715         Dirs.push_back((InstallDir + "/include").str());
01716         std::string SysRootInc =
01717             InstallDir.str() + "/../../../../" + TripleStr.str();
01718         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
01719           Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
01720         else
01721           Dirs.push_back(SysRootInc + "/libc/usr/include");
01722         return Dirs;
01723       });
01724   }
01725 
01726   MultilibSet AndroidMipsMultilibs = MultilibSet()
01727     .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
01728     .FilterOut(NonExistent);
01729 
01730   MultilibSet DebianMipsMultilibs;
01731   {
01732     Multilib MAbiN32 = Multilib()
01733       .gccSuffix("/n32")
01734       .includeSuffix("/n32")
01735       .flag("+mabi=n32");
01736 
01737     Multilib M64 = Multilib()
01738       .gccSuffix("/64")
01739       .includeSuffix("/64")
01740       .flag("+m64").flag("-m32").flag("-mabi=n32");
01741 
01742     Multilib M32 = Multilib()
01743       .flag("-m64").flag("+m32").flag("-mabi=n32");
01744 
01745     DebianMipsMultilibs = MultilibSet()
01746       .Either(M32, M64, MAbiN32)
01747       .FilterOut(NonExistent);
01748   }
01749 
01750   MultilibSet ImgMultilibs;
01751   {
01752     auto Mips64r6 = makeMultilib("/mips64r6")
01753       .flag("+m64").flag("-m32");
01754 
01755     auto LittleEndian = makeMultilib("/el")
01756       .flag("+EL").flag("-EB");
01757 
01758     auto MAbi64 = makeMultilib("/64")
01759       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
01760 
01761     ImgMultilibs = MultilibSet()
01762       .Maybe(Mips64r6)
01763       .Maybe(MAbi64)
01764       .Maybe(LittleEndian)
01765       .FilterOut(NonExistent)
01766       .setIncludeDirsCallback([](
01767           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
01768         std::vector<std::string> Dirs;
01769         Dirs.push_back((InstallDir + "/include").str());
01770         Dirs.push_back((InstallDir + "/../../../../sysroot/usr/include").str());
01771         return Dirs;
01772       });
01773   }
01774 
01775   StringRef CPUName;
01776   StringRef ABIName;
01777   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
01778 
01779   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
01780 
01781   Multilib::flags_list Flags;
01782   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
01783   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
01784   addMultilibFlag(isMips16(Args), "mips16", Flags);
01785   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
01786   addMultilibFlag(CPUName == "mips32r2", "march=mips32r2", Flags);
01787   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
01788   addMultilibFlag(CPUName == "mips64r2" || CPUName == "octeon",
01789                   "march=mips64r2", Flags);
01790   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
01791   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
01792   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
01793                   Flags);
01794   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
01795   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
01796   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
01797   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
01798   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
01799   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
01800 
01801   if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
01802     // Select Android toolchain. It's the only choice in that case.
01803     if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
01804       Result.Multilibs = AndroidMipsMultilibs;
01805       return true;
01806     }
01807     return false;
01808   }
01809 
01810   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
01811       TargetTriple.getOS() == llvm::Triple::Linux &&
01812       TargetTriple.getEnvironment() == llvm::Triple::GNU) {
01813     // Select mips-img-linux-gnu toolchain.
01814     if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
01815       Result.Multilibs = ImgMultilibs;
01816       return true;
01817     }
01818     return false;
01819   }
01820 
01821   // Sort candidates. Toolchain that best meets the directories goes first.
01822   // Then select the first toolchains matches command line flags.
01823   MultilibSet *candidates[] = { &DebianMipsMultilibs, &FSFMipsMultilibs,
01824                                 &CSMipsMultilibs };
01825   std::sort(
01826       std::begin(candidates), std::end(candidates),
01827       [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
01828   for (const auto &candidate : candidates) {
01829     if (candidate->select(Flags, Result.SelectedMultilib)) {
01830       if (candidate == &DebianMipsMultilibs)
01831         Result.BiarchSibling = Multilib();
01832       Result.Multilibs = *candidate;
01833       return true;
01834     }
01835   }
01836 
01837   {
01838     // Fallback to the regular toolchain-tree structure.
01839     Multilib Default;
01840     Result.Multilibs.push_back(Default);
01841     Result.Multilibs.FilterOut(NonExistent);
01842 
01843     if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
01844       Result.BiarchSibling = Multilib();
01845       return true;
01846     }
01847   }
01848 
01849   return false;
01850 }
01851 
01852 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
01853                                 StringRef Path, const ArgList &Args,
01854                                 bool NeedsBiarchSuffix,
01855                                 DetectedMultilibs &Result) {
01856 
01857   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
01858   // in what would normally be GCCInstallPath and put the 64-bit
01859   // libs in a subdirectory named 64. The simple logic we follow is that
01860   // *if* there is a subdirectory of the right name with crtbegin.o in it,
01861   // we use that. If not, and if not a biarch triple alias, we look for
01862   // crtbegin.o without the subdirectory.
01863 
01864   Multilib Default;
01865   Multilib Alt64 = Multilib()
01866     .gccSuffix("/64")
01867     .includeSuffix("/64")
01868     .flag("-m32").flag("+m64").flag("-mx32");
01869   Multilib Alt32 = Multilib()
01870     .gccSuffix("/32")
01871     .includeSuffix("/32")
01872     .flag("+m32").flag("-m64").flag("-mx32");
01873   Multilib Altx32 = Multilib()
01874     .gccSuffix("/x32")
01875     .includeSuffix("/x32")
01876     .flag("-m32").flag("-m64").flag("+mx32");
01877 
01878   FilterNonExistent NonExistent(Path);
01879 
01880   // Determine default multilib from: 32, 64, x32
01881   // Also handle cases such as 64 on 32, 32 on 64, etc.
01882   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
01883   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
01884   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
01885     Want = WANT64;
01886   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
01887     Want = WANT64;
01888   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
01889     Want = WANT32;
01890   else {
01891     if (TargetTriple.isArch32Bit())
01892       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
01893     else if (IsX32)
01894       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
01895     else
01896       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
01897   }
01898 
01899   if (Want == WANT32)
01900     Default.flag("+m32").flag("-m64").flag("-mx32");
01901   else if (Want == WANT64)
01902     Default.flag("-m32").flag("+m64").flag("-mx32");
01903   else if (Want == WANTX32)
01904     Default.flag("-m32").flag("-m64").flag("+mx32");
01905   else
01906     return false;
01907 
01908   Result.Multilibs.push_back(Default);
01909   Result.Multilibs.push_back(Alt64);
01910   Result.Multilibs.push_back(Alt32);
01911   Result.Multilibs.push_back(Altx32);
01912 
01913   Result.Multilibs.FilterOut(NonExistent);
01914 
01915   Multilib::flags_list Flags;
01916   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
01917   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
01918   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
01919 
01920   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
01921     return false;
01922 
01923   if (Result.SelectedMultilib == Alt64 ||
01924       Result.SelectedMultilib == Alt32 ||
01925       Result.SelectedMultilib == Altx32)
01926     Result.BiarchSibling = Default;
01927 
01928   return true;
01929 }
01930 
01931 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
01932     const llvm::Triple &TargetTriple, const ArgList &Args,
01933     const std::string &LibDir, StringRef CandidateTriple,
01934     bool NeedsBiarchSuffix) {
01935   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
01936   // There are various different suffixes involving the triple we
01937   // check for. We also record what is necessary to walk from each back
01938   // up to the lib directory.
01939   const std::string LibSuffixes[] = {
01940     "/gcc/" + CandidateTriple.str(),
01941     // Debian puts cross-compilers in gcc-cross
01942     "/gcc-cross/" + CandidateTriple.str(),
01943     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
01944 
01945     // The Freescale PPC SDK has the gcc libraries in
01946     // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
01947     "/" + CandidateTriple.str(),
01948 
01949     // Ubuntu has a strange mis-matched pair of triples that this happens to
01950     // match.
01951     // FIXME: It may be worthwhile to generalize this and look for a second
01952     // triple.
01953     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
01954   };
01955   const std::string InstallSuffixes[] = {
01956     "/../../..",    // gcc/
01957     "/../../..",    // gcc-cross/
01958     "/../../../..", // <triple>/gcc/
01959     "/../..",       // <triple>/
01960     "/../../../.."  // i386-linux-gnu/gcc/<triple>/
01961   };
01962   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
01963   const unsigned NumLibSuffixes =
01964       (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
01965   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
01966     StringRef LibSuffix = LibSuffixes[i];
01967     std::error_code EC;
01968     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
01969          !EC && LI != LE; LI = LI.increment(EC)) {
01970       StringRef VersionText = llvm::sys::path::filename(LI->path());
01971       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
01972       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
01973         if (!CandidateGCCInstallPaths.insert(LI->path()).second)
01974           continue; // Saw this path before; no need to look at it again.
01975       if (CandidateVersion.isOlderThan(4, 1, 1))
01976         continue;
01977       if (CandidateVersion <= Version)
01978         continue;
01979 
01980       DetectedMultilibs Detected;
01981 
01982       // Debian mips multilibs behave more like the rest of the biarch ones,
01983       // so handle them there
01984       if (isMipsArch(TargetArch)) {
01985         if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
01986           continue;
01987       } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
01988                                       NeedsBiarchSuffix, Detected)) {
01989         continue;
01990       }
01991 
01992       Multilibs = Detected.Multilibs;
01993       SelectedMultilib = Detected.SelectedMultilib;
01994       BiarchSibling = Detected.BiarchSibling;
01995       Version = CandidateVersion;
01996       GCCTriple.setTriple(CandidateTriple);
01997       // FIXME: We hack together the directory name here instead of
01998       // using LI to ensure stable path separators across Windows and
01999       // Linux.
02000       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
02001       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
02002       IsValid = true;
02003     }
02004   }
02005 }
02006 
02007 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
02008                          const ArgList &Args)
02009   : ToolChain(D, Triple, Args), GCCInstallation() {
02010   getProgramPaths().push_back(getDriver().getInstalledDir());
02011   if (getDriver().getInstalledDir() != getDriver().Dir)
02012     getProgramPaths().push_back(getDriver().Dir);
02013 }
02014 
02015 Generic_GCC::~Generic_GCC() {
02016 }
02017 
02018 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
02019   switch (AC) {
02020   case Action::PreprocessJobClass:
02021     if (!Preprocess)
02022       Preprocess.reset(new tools::gcc::Preprocess(*this));
02023     return Preprocess.get();
02024   case Action::CompileJobClass:
02025     if (!Compile)
02026       Compile.reset(new tools::gcc::Compile(*this));
02027     return Compile.get();
02028   default:
02029     return ToolChain::getTool(AC);
02030   }
02031 }
02032 
02033 Tool *Generic_GCC::buildAssembler() const {
02034   return new tools::gnutools::Assemble(*this);
02035 }
02036 
02037 Tool *Generic_GCC::buildLinker() const {
02038   return new tools::gcc::Link(*this);
02039 }
02040 
02041 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
02042   // Print the information about how we detected the GCC installation.
02043   GCCInstallation.print(OS);
02044 }
02045 
02046 bool Generic_GCC::IsUnwindTablesDefault() const {
02047   return getArch() == llvm::Triple::x86_64;
02048 }
02049 
02050 bool Generic_GCC::isPICDefault() const {
02051   return false;
02052 }
02053 
02054 bool Generic_GCC::isPIEDefault() const {
02055   return false;
02056 }
02057 
02058 bool Generic_GCC::isPICDefaultForced() const {
02059   return false;
02060 }
02061 
02062 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
02063   return getTriple().getArch() == llvm::Triple::x86 ||
02064          getTriple().getArch() == llvm::Triple::x86_64 ||
02065          getTriple().getArch() == llvm::Triple::aarch64 ||
02066          getTriple().getArch() == llvm::Triple::aarch64_be ||
02067          getTriple().getArch() == llvm::Triple::arm ||
02068          getTriple().getArch() == llvm::Triple::armeb ||
02069          getTriple().getArch() == llvm::Triple::thumb ||
02070          getTriple().getArch() == llvm::Triple::thumbeb ||
02071          getTriple().getArch() == llvm::Triple::ppc64 ||
02072          getTriple().getArch() == llvm::Triple::ppc64le ||
02073          getTriple().getArch() == llvm::Triple::systemz;
02074 }
02075 
02076 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
02077                                         ArgStringList &CC1Args) const {
02078   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
02079   bool UseInitArrayDefault =
02080       getTriple().getArch() == llvm::Triple::aarch64 ||
02081       getTriple().getArch() == llvm::Triple::aarch64_be ||
02082       (getTriple().getOS() == llvm::Triple::Linux &&
02083        (!V.isOlderThan(4, 7, 0) ||
02084         getTriple().getEnvironment() == llvm::Triple::Android));
02085 
02086   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
02087                          options::OPT_fno_use_init_array,
02088                          UseInitArrayDefault))
02089     CC1Args.push_back("-fuse-init-array");
02090 }
02091 
02092 /// Hexagon Toolchain
02093 
02094 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
02095                                   const ArgList &Args) {
02096 
02097   // Locate the rest of the toolchain ...
02098   std::string GccToolchain = getGCCToolchainDir(Args);
02099 
02100   if (!GccToolchain.empty())
02101     return GccToolchain;
02102 
02103   std::string InstallRelDir = InstalledDir + "/../../gnu";
02104   if (llvm::sys::fs::exists(InstallRelDir))
02105     return InstallRelDir;
02106 
02107   std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
02108   if (llvm::sys::fs::exists(PrefixRelDir))
02109     return PrefixRelDir;
02110 
02111   return InstallRelDir;
02112 }
02113 
02114 static void GetHexagonLibraryPaths(
02115   const ArgList &Args,
02116   const std::string &Ver,
02117   const std::string &MarchString,
02118   const std::string &InstalledDir,
02119   ToolChain::path_list *LibPaths)
02120 {
02121   bool buildingLib = Args.hasArg(options::OPT_shared);
02122 
02123   //----------------------------------------------------------------------------
02124   // -L Args
02125   //----------------------------------------------------------------------------
02126   for (arg_iterator
02127          it = Args.filtered_begin(options::OPT_L),
02128          ie = Args.filtered_end();
02129        it != ie;
02130        ++it) {
02131     for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
02132       LibPaths->push_back((*it)->getValue(i));
02133   }
02134 
02135   //----------------------------------------------------------------------------
02136   // Other standard paths
02137   //----------------------------------------------------------------------------
02138   const std::string MarchSuffix = "/" + MarchString;
02139   const std::string G0Suffix = "/G0";
02140   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
02141   const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
02142 
02143   // lib/gcc/hexagon/...
02144   std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
02145   if (buildingLib) {
02146     LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
02147     LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
02148   }
02149   LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
02150   LibPaths->push_back(LibGCCHexagonDir + Ver);
02151 
02152   // lib/gcc/...
02153   LibPaths->push_back(RootDir + "lib/gcc");
02154 
02155   // hexagon/lib/...
02156   std::string HexagonLibDir = RootDir + "hexagon/lib";
02157   if (buildingLib) {
02158     LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
02159     LibPaths->push_back(HexagonLibDir + G0Suffix);
02160   }
02161   LibPaths->push_back(HexagonLibDir + MarchSuffix);
02162   LibPaths->push_back(HexagonLibDir);
02163 }
02164 
02165 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
02166                        const ArgList &Args)
02167   : Linux(D, Triple, Args) {
02168   const std::string InstalledDir(getDriver().getInstalledDir());
02169   const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
02170 
02171   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
02172   // program paths
02173   const std::string BinDir(GnuDir + "/bin");
02174   if (llvm::sys::fs::exists(BinDir))
02175     getProgramPaths().push_back(BinDir);
02176 
02177   // Determine version of GCC libraries and headers to use.
02178   const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
02179   std::error_code ec;
02180   GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
02181   for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
02182        !ec && di != de; di = di.increment(ec)) {
02183     GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
02184     if (MaxVersion < cv)
02185       MaxVersion = cv;
02186   }
02187   GCCLibAndIncVersion = MaxVersion;
02188 
02189   ToolChain::path_list *LibPaths= &getFilePaths();
02190 
02191   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
02192   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
02193   // support 'linux' we'll need to fix this up
02194   LibPaths->clear();
02195 
02196   GetHexagonLibraryPaths(
02197     Args,
02198     GetGCCLibAndIncVersion(),
02199     GetTargetCPU(Args),
02200     InstalledDir,
02201     LibPaths);
02202 }
02203 
02204 Hexagon_TC::~Hexagon_TC() {
02205 }
02206 
02207 Tool *Hexagon_TC::buildAssembler() const {
02208   return new tools::hexagon::Assemble(*this);
02209 }
02210 
02211 Tool *Hexagon_TC::buildLinker() const {
02212   return new tools::hexagon::Link(*this);
02213 }
02214 
02215 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
02216                                            ArgStringList &CC1Args) const {
02217   const Driver &D = getDriver();
02218 
02219   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
02220       DriverArgs.hasArg(options::OPT_nostdlibinc))
02221     return;
02222 
02223   std::string Ver(GetGCCLibAndIncVersion());
02224   std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
02225   std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
02226   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
02227   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
02228   addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
02229 }
02230 
02231 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
02232                                               ArgStringList &CC1Args) const {
02233 
02234   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
02235       DriverArgs.hasArg(options::OPT_nostdincxx))
02236     return;
02237 
02238   const Driver &D = getDriver();
02239   std::string Ver(GetGCCLibAndIncVersion());
02240   SmallString<128> IncludeDir(
02241       Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
02242 
02243   llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
02244   llvm::sys::path::append(IncludeDir, Ver);
02245   addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
02246 }
02247 
02248 ToolChain::CXXStdlibType
02249 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
02250   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
02251   if (!A)
02252     return ToolChain::CST_Libstdcxx;
02253 
02254   StringRef Value = A->getValue();
02255   if (Value != "libstdc++") {
02256     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
02257       << A->getAsString(Args);
02258   }
02259 
02260   return ToolChain::CST_Libstdcxx;
02261 }
02262 
02263 static int getHexagonVersion(const ArgList &Args) {
02264   Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
02265   // Select the default CPU (v4) if none was given.
02266   if (!A)
02267     return 4;
02268 
02269   // FIXME: produce errors if we cannot parse the version.
02270   StringRef WhichHexagon = A->getValue();
02271   if (WhichHexagon.startswith("hexagonv")) {
02272     int Val;
02273     if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
02274       return Val;
02275   }
02276   if (WhichHexagon.startswith("v")) {
02277     int Val;
02278     if (!WhichHexagon.substr(1).getAsInteger(10, Val))
02279       return Val;
02280   }
02281 
02282   // FIXME: should probably be an error.
02283   return 4;
02284 }
02285 
02286 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
02287 {
02288   int V = getHexagonVersion(Args);
02289   // FIXME: We don't support versions < 4. We should error on them.
02290   switch (V) {
02291   default:
02292     llvm_unreachable("Unexpected version");
02293   case 5:
02294     return "v5";
02295   case 4:
02296     return "v4";
02297   case 3:
02298     return "v3";
02299   case 2:
02300     return "v2";
02301   case 1:
02302     return "v1";
02303   }
02304 }
02305 // End Hexagon
02306 
02307 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
02308 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
02309 /// Currently does not support anything else but compilation.
02310 
02311 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
02312                            const ArgList &Args)
02313   : ToolChain(D, Triple, Args) {
02314   // Path mangling to find libexec
02315   std::string Path(getDriver().Dir);
02316 
02317   Path += "/../libexec";
02318   getProgramPaths().push_back(Path);
02319 }
02320 
02321 TCEToolChain::~TCEToolChain() {
02322 }
02323 
02324 bool TCEToolChain::IsMathErrnoDefault() const {
02325   return true;
02326 }
02327 
02328 bool TCEToolChain::isPICDefault() const {
02329   return false;
02330 }
02331 
02332 bool TCEToolChain::isPIEDefault() const {
02333   return false;
02334 }
02335 
02336 bool TCEToolChain::isPICDefaultForced() const {
02337   return false;
02338 }
02339 
02340 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
02341 
02342 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02343   : Generic_ELF(D, Triple, Args) {
02344   getFilePaths().push_back(getDriver().Dir + "/../lib");
02345   getFilePaths().push_back("/usr/lib");
02346 }
02347 
02348 Tool *OpenBSD::buildAssembler() const {
02349   return new tools::openbsd::Assemble(*this);
02350 }
02351 
02352 Tool *OpenBSD::buildLinker() const {
02353   return new tools::openbsd::Link(*this);
02354 }
02355 
02356 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
02357 
02358 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02359   : Generic_ELF(D, Triple, Args) {
02360   getFilePaths().push_back(getDriver().Dir + "/../lib");
02361   getFilePaths().push_back("/usr/lib");
02362 }
02363 
02364 Tool *Bitrig::buildAssembler() const {
02365   return new tools::bitrig::Assemble(*this);
02366 }
02367 
02368 Tool *Bitrig::buildLinker() const {
02369   return new tools::bitrig::Link(*this);
02370 }
02371 
02372 ToolChain::CXXStdlibType
02373 Bitrig::GetCXXStdlibType(const ArgList &Args) const {
02374   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
02375     StringRef Value = A->getValue();
02376     if (Value == "libstdc++")
02377       return ToolChain::CST_Libstdcxx;
02378     if (Value == "libc++")
02379       return ToolChain::CST_Libcxx;
02380 
02381     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
02382       << A->getAsString(Args);
02383   }
02384   return ToolChain::CST_Libcxx;
02385 }
02386 
02387 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
02388                                           ArgStringList &CC1Args) const {
02389   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
02390       DriverArgs.hasArg(options::OPT_nostdincxx))
02391     return;
02392 
02393   switch (GetCXXStdlibType(DriverArgs)) {
02394   case ToolChain::CST_Libcxx:
02395     addSystemInclude(DriverArgs, CC1Args,
02396                      getDriver().SysRoot + "/usr/include/c++/v1");
02397     break;
02398   case ToolChain::CST_Libstdcxx:
02399     addSystemInclude(DriverArgs, CC1Args,
02400                      getDriver().SysRoot + "/usr/include/c++/stdc++");
02401     addSystemInclude(DriverArgs, CC1Args,
02402                      getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
02403 
02404     StringRef Triple = getTriple().str();
02405     if (Triple.startswith("amd64"))
02406       addSystemInclude(DriverArgs, CC1Args,
02407                        getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
02408                        Triple.substr(5));
02409     else
02410       addSystemInclude(DriverArgs, CC1Args,
02411                        getDriver().SysRoot + "/usr/include/c++/stdc++/" +
02412                        Triple);
02413     break;
02414   }
02415 }
02416 
02417 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
02418                                  ArgStringList &CmdArgs) const {
02419   switch (GetCXXStdlibType(Args)) {
02420   case ToolChain::CST_Libcxx:
02421     CmdArgs.push_back("-lc++");
02422     CmdArgs.push_back("-lc++abi");
02423     CmdArgs.push_back("-lpthread");
02424     break;
02425   case ToolChain::CST_Libstdcxx:
02426     CmdArgs.push_back("-lstdc++");
02427     break;
02428   }
02429 }
02430 
02431 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
02432 
02433 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02434   : Generic_ELF(D, Triple, Args) {
02435 
02436   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
02437   // back to '/usr/lib' if it doesn't exist.
02438   if ((Triple.getArch() == llvm::Triple::x86 ||
02439        Triple.getArch() == llvm::Triple::ppc) &&
02440       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
02441     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
02442   else
02443     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
02444 }
02445 
02446 ToolChain::CXXStdlibType
02447 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
02448   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
02449     StringRef Value = A->getValue();
02450     if (Value == "libstdc++")
02451       return ToolChain::CST_Libstdcxx;
02452     if (Value == "libc++")
02453       return ToolChain::CST_Libcxx;
02454 
02455     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
02456       << A->getAsString(Args);
02457   }
02458   if (getTriple().getOSMajorVersion() >= 10) 
02459     return ToolChain::CST_Libcxx;
02460   return ToolChain::CST_Libstdcxx;
02461 }
02462 
02463 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
02464                                            ArgStringList &CC1Args) const {
02465   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
02466       DriverArgs.hasArg(options::OPT_nostdincxx))
02467     return;
02468 
02469   switch (GetCXXStdlibType(DriverArgs)) {
02470   case ToolChain::CST_Libcxx:
02471     addSystemInclude(DriverArgs, CC1Args,
02472                      getDriver().SysRoot + "/usr/include/c++/v1");
02473     break;
02474   case ToolChain::CST_Libstdcxx:
02475     addSystemInclude(DriverArgs, CC1Args,
02476                      getDriver().SysRoot + "/usr/include/c++/4.2");
02477     addSystemInclude(DriverArgs, CC1Args,
02478                      getDriver().SysRoot + "/usr/include/c++/4.2/backward");
02479     break;
02480   }
02481 }
02482 
02483 Tool *FreeBSD::buildAssembler() const {
02484   return new tools::freebsd::Assemble(*this);
02485 }
02486 
02487 Tool *FreeBSD::buildLinker() const {
02488   return new tools::freebsd::Link(*this);
02489 }
02490 
02491 bool FreeBSD::UseSjLjExceptions() const {
02492   // FreeBSD uses SjLj exceptions on ARM oabi.
02493   switch (getTriple().getEnvironment()) {
02494   case llvm::Triple::GNUEABIHF:
02495   case llvm::Triple::GNUEABI:
02496   case llvm::Triple::EABI:
02497     return false;
02498 
02499   default:
02500     return (getTriple().getArch() == llvm::Triple::arm ||
02501             getTriple().getArch() == llvm::Triple::thumb);
02502   }
02503 }
02504 
02505 bool FreeBSD::HasNativeLLVMSupport() const {
02506   return true;
02507 }
02508 
02509 bool FreeBSD::isPIEDefault() const {
02510   return getSanitizerArgs().hasZeroBaseShadow();
02511 }
02512 
02513 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
02514 
02515 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02516   : Generic_ELF(D, Triple, Args) {
02517 
02518   if (getDriver().UseStdLib) {
02519     // When targeting a 32-bit platform, try the special directory used on
02520     // 64-bit hosts, and only fall back to the main library directory if that
02521     // doesn't work.
02522     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
02523     // what all logic is needed to emulate the '=' prefix here.
02524     switch (Triple.getArch()) {
02525     case llvm::Triple::x86:
02526       getFilePaths().push_back("=/usr/lib/i386");
02527       break;
02528     case llvm::Triple::arm:
02529     case llvm::Triple::armeb:
02530     case llvm::Triple::thumb:
02531     case llvm::Triple::thumbeb:
02532       switch (Triple.getEnvironment()) {
02533       case llvm::Triple::EABI:
02534       case llvm::Triple::GNUEABI:
02535         getFilePaths().push_back("=/usr/lib/eabi");
02536         break;
02537       case llvm::Triple::EABIHF:
02538       case llvm::Triple::GNUEABIHF:
02539         getFilePaths().push_back("=/usr/lib/eabihf");
02540         break;
02541       default:
02542         getFilePaths().push_back("=/usr/lib/oabi");
02543         break;
02544       }
02545       break;
02546     case llvm::Triple::mips64:
02547     case llvm::Triple::mips64el:
02548       if (tools::mips::hasMipsAbiArg(Args, "o32"))
02549         getFilePaths().push_back("=/usr/lib/o32");
02550       else if (tools::mips::hasMipsAbiArg(Args, "64"))
02551         getFilePaths().push_back("=/usr/lib/64");
02552       break;
02553     case llvm::Triple::ppc:
02554       getFilePaths().push_back("=/usr/lib/powerpc");
02555       break;
02556     case llvm::Triple::sparc:
02557       getFilePaths().push_back("=/usr/lib/sparc");
02558       break;
02559     default:
02560       break;
02561     }
02562 
02563     getFilePaths().push_back("=/usr/lib");
02564   }
02565 }
02566 
02567 Tool *NetBSD::buildAssembler() const {
02568   return new tools::netbsd::Assemble(*this);
02569 }
02570 
02571 Tool *NetBSD::buildLinker() const {
02572   return new tools::netbsd::Link(*this);
02573 }
02574 
02575 ToolChain::CXXStdlibType
02576 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
02577   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
02578     StringRef Value = A->getValue();
02579     if (Value == "libstdc++")
02580       return ToolChain::CST_Libstdcxx;
02581     if (Value == "libc++")
02582       return ToolChain::CST_Libcxx;
02583 
02584     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
02585       << A->getAsString(Args);
02586   }
02587 
02588   unsigned Major, Minor, Micro;
02589   getTriple().getOSVersion(Major, Minor, Micro);
02590   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
02591     switch (getArch()) {
02592     case llvm::Triple::aarch64:
02593     case llvm::Triple::arm:
02594     case llvm::Triple::armeb:
02595     case llvm::Triple::thumb:
02596     case llvm::Triple::thumbeb:
02597     case llvm::Triple::ppc:
02598     case llvm::Triple::ppc64:
02599     case llvm::Triple::ppc64le:
02600     case llvm::Triple::x86:
02601     case llvm::Triple::x86_64:
02602       return ToolChain::CST_Libcxx;
02603     default:
02604       break;
02605     }
02606   }
02607   return ToolChain::CST_Libstdcxx;
02608 }
02609 
02610 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
02611                                           ArgStringList &CC1Args) const {
02612   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
02613       DriverArgs.hasArg(options::OPT_nostdincxx))
02614     return;
02615 
02616   switch (GetCXXStdlibType(DriverArgs)) {
02617   case ToolChain::CST_Libcxx:
02618     addSystemInclude(DriverArgs, CC1Args,
02619                      getDriver().SysRoot + "/usr/include/c++/");
02620     break;
02621   case ToolChain::CST_Libstdcxx:
02622     addSystemInclude(DriverArgs, CC1Args,
02623                      getDriver().SysRoot + "/usr/include/g++");
02624     addSystemInclude(DriverArgs, CC1Args,
02625                      getDriver().SysRoot + "/usr/include/g++/backward");
02626     break;
02627   }
02628 }
02629 
02630 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
02631 
02632 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02633   : Generic_ELF(D, Triple, Args) {
02634   getFilePaths().push_back(getDriver().Dir + "/../lib");
02635   getFilePaths().push_back("/usr/lib");
02636 }
02637 
02638 Tool *Minix::buildAssembler() const {
02639   return new tools::minix::Assemble(*this);
02640 }
02641 
02642 Tool *Minix::buildLinker() const {
02643   return new tools::minix::Link(*this);
02644 }
02645 
02646 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
02647 
02648 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
02649                  const ArgList &Args)
02650   : Generic_GCC(D, Triple, Args) {
02651 
02652   getProgramPaths().push_back(getDriver().getInstalledDir());
02653   if (getDriver().getInstalledDir() != getDriver().Dir)
02654     getProgramPaths().push_back(getDriver().Dir);
02655 
02656   getFilePaths().push_back(getDriver().Dir + "/../lib");
02657   getFilePaths().push_back("/usr/lib");
02658 }
02659 
02660 Tool *Solaris::buildAssembler() const {
02661   return new tools::solaris::Assemble(*this);
02662 }
02663 
02664 Tool *Solaris::buildLinker() const {
02665   return new tools::solaris::Link(*this);
02666 }
02667 
02668 /// Distribution (very bare-bones at the moment).
02669 
02670 enum Distro {
02671   ArchLinux,
02672   DebianLenny,
02673   DebianSqueeze,
02674   DebianWheezy,
02675   DebianJessie,
02676   Exherbo,
02677   RHEL4,
02678   RHEL5,
02679   RHEL6,
02680   Fedora,
02681   OpenSUSE,
02682   UbuntuHardy,
02683   UbuntuIntrepid,
02684   UbuntuJaunty,
02685   UbuntuKarmic,
02686   UbuntuLucid,
02687   UbuntuMaverick,
02688   UbuntuNatty,
02689   UbuntuOneiric,
02690   UbuntuPrecise,
02691   UbuntuQuantal,
02692   UbuntuRaring,
02693   UbuntuSaucy,
02694   UbuntuTrusty,
02695   UnknownDistro
02696 };
02697 
02698 static bool IsRedhat(enum Distro Distro) {
02699   return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
02700 }
02701 
02702 static bool IsOpenSUSE(enum Distro Distro) {
02703   return Distro == OpenSUSE;
02704 }
02705 
02706 static bool IsDebian(enum Distro Distro) {
02707   return Distro >= DebianLenny && Distro <= DebianJessie;
02708 }
02709 
02710 static bool IsUbuntu(enum Distro Distro) {
02711   return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
02712 }
02713 
02714 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
02715   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
02716       llvm::MemoryBuffer::getFile("/etc/lsb-release");
02717   if (File) {
02718     StringRef Data = File.get()->getBuffer();
02719     SmallVector<StringRef, 16> Lines;
02720     Data.split(Lines, "\n");
02721     Distro Version = UnknownDistro;
02722     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
02723       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
02724         Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
02725           .Case("hardy", UbuntuHardy)
02726           .Case("intrepid", UbuntuIntrepid)
02727           .Case("jaunty", UbuntuJaunty)
02728           .Case("karmic", UbuntuKarmic)
02729           .Case("lucid", UbuntuLucid)
02730           .Case("maverick", UbuntuMaverick)
02731           .Case("natty", UbuntuNatty)
02732           .Case("oneiric", UbuntuOneiric)
02733           .Case("precise", UbuntuPrecise)
02734           .Case("quantal", UbuntuQuantal)
02735           .Case("raring", UbuntuRaring)
02736           .Case("saucy", UbuntuSaucy)
02737           .Case("trusty", UbuntuTrusty)
02738           .Default(UnknownDistro);
02739     return Version;
02740   }
02741 
02742   File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
02743   if (File) {
02744     StringRef Data = File.get()->getBuffer();
02745     if (Data.startswith("Fedora release"))
02746       return Fedora;
02747     if (Data.startswith("Red Hat Enterprise Linux") ||
02748         Data.startswith("CentOS")) {
02749       if (Data.find("release 6") != StringRef::npos)
02750         return RHEL6;
02751       else if (Data.find("release 5") != StringRef::npos)
02752         return RHEL5;
02753       else if (Data.find("release 4") != StringRef::npos)
02754         return RHEL4;
02755     }
02756     return UnknownDistro;
02757   }
02758 
02759   File = llvm::MemoryBuffer::getFile("/etc/debian_version");
02760   if (File) {
02761     StringRef Data = File.get()->getBuffer();
02762     if (Data[0] == '5')
02763       return DebianLenny;
02764     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
02765       return DebianSqueeze;
02766     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
02767       return DebianWheezy;
02768     else if (Data.startswith("jessie/sid")  || Data[0] == '8')
02769       return DebianJessie;
02770     return UnknownDistro;
02771   }
02772 
02773   if (llvm::sys::fs::exists("/etc/SuSE-release"))
02774     return OpenSUSE;
02775 
02776   if (llvm::sys::fs::exists("/etc/exherbo-release"))
02777     return Exherbo;
02778 
02779   if (llvm::sys::fs::exists("/etc/arch-release"))
02780     return ArchLinux;
02781 
02782   return UnknownDistro;
02783 }
02784 
02785 /// \brief Get our best guess at the multiarch triple for a target.
02786 ///
02787 /// Debian-based systems are starting to use a multiarch setup where they use
02788 /// a target-triple directory in the library and header search paths.
02789 /// Unfortunately, this triple does not align with the vanilla target triple,
02790 /// so we provide a rough mapping here.
02791 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
02792                                       StringRef SysRoot) {
02793   // For most architectures, just use whatever we have rather than trying to be
02794   // clever.
02795   switch (TargetTriple.getArch()) {
02796   default:
02797     return TargetTriple.str();
02798 
02799     // We use the existence of '/lib/<triple>' as a directory to detect some
02800     // common linux triples that don't quite match the Clang triple for both
02801     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
02802     // regardless of what the actual target triple is.
02803   case llvm::Triple::arm:
02804   case llvm::Triple::thumb:
02805     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
02806       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
02807         return "arm-linux-gnueabihf";
02808     } else {
02809       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
02810         return "arm-linux-gnueabi";
02811     }
02812     return TargetTriple.str();
02813   case llvm::Triple::armeb:
02814   case llvm::Triple::thumbeb:
02815     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
02816       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
02817         return "armeb-linux-gnueabihf";
02818     } else {
02819       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
02820         return "armeb-linux-gnueabi";
02821     }
02822     return TargetTriple.str();
02823   case llvm::Triple::x86:
02824     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
02825       return "i386-linux-gnu";
02826     return TargetTriple.str();
02827   case llvm::Triple::x86_64:
02828     // We don't want this for x32, otherwise it will match x86_64 libs
02829     if (TargetTriple.getEnvironment() != llvm::Triple::GNUX32 &&
02830         llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
02831       return "x86_64-linux-gnu";
02832     return TargetTriple.str();
02833   case llvm::Triple::aarch64:
02834     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
02835       return "aarch64-linux-gnu";
02836     return TargetTriple.str();
02837   case llvm::Triple::aarch64_be:
02838     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
02839       return "aarch64_be-linux-gnu";
02840     return TargetTriple.str();
02841   case llvm::Triple::mips:
02842     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
02843       return "mips-linux-gnu";
02844     return TargetTriple.str();
02845   case llvm::Triple::mipsel:
02846     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
02847       return "mipsel-linux-gnu";
02848     return TargetTriple.str();
02849   case llvm::Triple::mips64:
02850     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
02851       return "mips64-linux-gnu";
02852     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
02853       return "mips64-linux-gnuabi64";
02854     return TargetTriple.str();
02855   case llvm::Triple::mips64el:
02856     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
02857       return "mips64el-linux-gnu";
02858     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
02859       return "mips64el-linux-gnuabi64";
02860     return TargetTriple.str();
02861   case llvm::Triple::ppc:
02862     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
02863       return "powerpc-linux-gnuspe";
02864     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
02865       return "powerpc-linux-gnu";
02866     return TargetTriple.str();
02867   case llvm::Triple::ppc64:
02868     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
02869       return "powerpc64-linux-gnu";
02870   case llvm::Triple::ppc64le:
02871     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
02872       return "powerpc64le-linux-gnu";
02873     return TargetTriple.str();
02874   }
02875 }
02876 
02877 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
02878   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
02879 }
02880 
02881 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
02882   if (isMipsArch(Triple.getArch())) {
02883     // lib32 directory has a special meaning on MIPS targets.
02884     // It contains N32 ABI binaries. Use this folder if produce
02885     // code for N32 ABI only.
02886     if (tools::mips::hasMipsAbiArg(Args, "n32"))
02887       return "lib32";
02888     return Triple.isArch32Bit() ? "lib" : "lib64";
02889   }
02890 
02891   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
02892   // using that variant while targeting other architectures causes problems
02893   // because the libraries are laid out in shared system roots that can't cope
02894   // with a 'lib32' library search path being considered. So we only enable
02895   // them when we know we may need it.
02896   //
02897   // FIXME: This is a bit of a hack. We should really unify this code for
02898   // reasoning about oslibdir spellings with the lib dir spellings in the
02899   // GCCInstallationDetector, but that is a more significant refactoring.
02900   if (Triple.getArch() == llvm::Triple::x86 ||
02901       Triple.getArch() == llvm::Triple::ppc)
02902     return "lib32";
02903 
02904   if (Triple.getArch() == llvm::Triple::x86_64 &&
02905       Triple.getEnvironment() == llvm::Triple::GNUX32)
02906     return "libx32";
02907 
02908   return Triple.isArch32Bit() ? "lib" : "lib64";
02909 }
02910 
02911 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
02912   : Generic_ELF(D, Triple, Args) {
02913   GCCInstallation.init(D, Triple, Args);
02914   Multilibs = GCCInstallation.getMultilibs();
02915   llvm::Triple::ArchType Arch = Triple.getArch();
02916   std::string SysRoot = computeSysRoot();
02917 
02918   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
02919   // least) put various tools in a triple-prefixed directory off of the parent
02920   // of the GCC installation. We use the GCC triple here to ensure that we end
02921   // up with tools that support the same amount of cross compiling as the
02922   // detected GCC installation. For example, if we find a GCC installation
02923   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
02924   // used to target i386.
02925   // FIXME: This seems unlikely to be Linux-specific.
02926   ToolChain::path_list &PPaths = getProgramPaths();
02927   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
02928                          GCCInstallation.getTriple().str() + "/bin").str());
02929 
02930   Linker = GetLinkerPath();
02931 
02932   Distro Distro = DetectDistro(Arch);
02933 
02934   if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
02935     ExtraOpts.push_back("-z");
02936     ExtraOpts.push_back("relro");
02937   }
02938 
02939   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
02940     ExtraOpts.push_back("-X");
02941 
02942   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
02943   const bool IsMips = isMipsArch(Arch);
02944 
02945   if (IsMips && !SysRoot.empty())
02946     ExtraOpts.push_back("--sysroot=" + SysRoot);
02947 
02948   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
02949   // and the MIPS ABI require .dynsym to be sorted in different ways.
02950   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
02951   // ABI requires a mapping between the GOT and the symbol table.
02952   // Android loader does not support .gnu.hash.
02953   if (!IsMips && !IsAndroid) {
02954     if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
02955         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
02956       ExtraOpts.push_back("--hash-style=gnu");
02957 
02958     if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
02959         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
02960       ExtraOpts.push_back("--hash-style=both");
02961   }
02962 
02963   if (IsRedhat(Distro))
02964     ExtraOpts.push_back("--no-add-needed");
02965 
02966   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
02967       Distro == DebianJessie || IsOpenSUSE(Distro) ||
02968       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
02969       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
02970     ExtraOpts.push_back("--build-id");
02971 
02972   if (IsOpenSUSE(Distro))
02973     ExtraOpts.push_back("--enable-new-dtags");
02974 
02975   // The selection of paths to try here is designed to match the patterns which
02976   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
02977   // This was determined by running GCC in a fake filesystem, creating all
02978   // possible permutations of these directories, and seeing which ones it added
02979   // to the link paths.
02980   path_list &Paths = getFilePaths();
02981 
02982   const std::string OSLibDir = getOSLibDir(Triple, Args);
02983   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
02984 
02985   // Add the multilib suffixed paths where they are available.
02986   if (GCCInstallation.isValid()) {
02987     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
02988     const std::string &LibPath = GCCInstallation.getParentLibPath();
02989     const Multilib &Multilib = GCCInstallation.getMultilib();
02990 
02991     // Sourcery CodeBench MIPS toolchain holds some libraries under
02992     // a biarch-like suffix of the GCC installation.
02993     addPathIfExists((GCCInstallation.getInstallPath() +
02994                      Multilib.gccSuffix()),
02995                     Paths);
02996 
02997     // GCC cross compiling toolchains will install target libraries which ship
02998     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
02999     // any part of the GCC installation in
03000     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
03001     // debatable, but is the reality today. We need to search this tree even
03002     // when we have a sysroot somewhere else. It is the responsibility of
03003     // whomever is doing the cross build targeting a sysroot using a GCC
03004     // installation that is *not* within the system root to ensure two things:
03005     //
03006     //  1) Any DSOs that are linked in from this tree or from the install path
03007     //     above must be present on the system root and found via an
03008     //     appropriate rpath.
03009     //  2) There must not be libraries installed into
03010     //     <prefix>/<triple>/<libdir> unless they should be preferred over
03011     //     those within the system root.
03012     //
03013     // Note that this matches the GCC behavior. See the below comment for where
03014     // Clang diverges from GCC's behavior.
03015     addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
03016                     Multilib.osSuffix(),
03017                     Paths);
03018 
03019     // If the GCC installation we found is inside of the sysroot, we want to
03020     // prefer libraries installed in the parent prefix of the GCC installation.
03021     // It is important to *not* use these paths when the GCC installation is
03022     // outside of the system root as that can pick up unintended libraries.
03023     // This usually happens when there is an external cross compiler on the
03024     // host system, and a more minimal sysroot available that is the target of
03025     // the cross. Note that GCC does include some of these directories in some
03026     // configurations but this seems somewhere between questionable and simply
03027     // a bug.
03028     if (StringRef(LibPath).startswith(SysRoot)) {
03029       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
03030       addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
03031     }
03032   }
03033 
03034   // Similar to the logic for GCC above, if we currently running Clang inside
03035   // of the requested system root, add its parent library paths to
03036   // those searched.
03037   // FIXME: It's not clear whether we should use the driver's installed
03038   // directory ('Dir' below) or the ResourceDir.
03039   if (StringRef(D.Dir).startswith(SysRoot)) {
03040     addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
03041     addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
03042   }
03043 
03044   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
03045   addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
03046   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
03047   addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
03048 
03049   // Try walking via the GCC triple path in case of biarch or multiarch GCC
03050   // installations with strange symlinks.
03051   if (GCCInstallation.isValid()) {
03052     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
03053                     "/../../" + OSLibDir, Paths);
03054 
03055     // Add the 'other' biarch variant path
03056     Multilib BiarchSibling;
03057     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
03058       addPathIfExists(GCCInstallation.getInstallPath() +
03059                       BiarchSibling.gccSuffix(), Paths);
03060     }
03061 
03062     // See comments above on the multilib variant for details of why this is
03063     // included even from outside the sysroot.
03064     const std::string &LibPath = GCCInstallation.getParentLibPath();
03065     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
03066     const Multilib &Multilib = GCCInstallation.getMultilib();
03067     addPathIfExists(LibPath + "/../" + GCCTriple.str() +
03068                     "/lib" + Multilib.osSuffix(), Paths);
03069 
03070     // See comments above on the multilib variant for details of why this is
03071     // only included from within the sysroot.
03072     if (StringRef(LibPath).startswith(SysRoot))
03073       addPathIfExists(LibPath, Paths);
03074   }
03075 
03076   // Similar to the logic for GCC above, if we are currently running Clang
03077   // inside of the requested system root, add its parent library path to those
03078   // searched.
03079   // FIXME: It's not clear whether we should use the driver's installed
03080   // directory ('Dir' below) or the ResourceDir.
03081   if (StringRef(D.Dir).startswith(SysRoot))
03082     addPathIfExists(D.Dir + "/../lib", Paths);
03083 
03084   addPathIfExists(SysRoot + "/lib", Paths);
03085   addPathIfExists(SysRoot + "/usr/lib", Paths);
03086 }
03087 
03088 bool Linux::HasNativeLLVMSupport() const {
03089   return true;
03090 }
03091 
03092 Tool *Linux::buildLinker() const {
03093   return new tools::gnutools::Link(*this);
03094 }
03095 
03096 Tool *Linux::buildAssembler() const {
03097   return new tools::gnutools::Assemble(*this);
03098 }
03099 
03100 std::string Linux::computeSysRoot() const {
03101   if (!getDriver().SysRoot.empty())
03102     return getDriver().SysRoot;
03103 
03104   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
03105     return std::string();
03106 
03107   // Standalone MIPS toolchains use different names for sysroot folder
03108   // and put it into different places. Here we try to check some known
03109   // variants.
03110 
03111   const StringRef InstallDir = GCCInstallation.getInstallPath();
03112   const StringRef TripleStr = GCCInstallation.getTriple().str();
03113   const Multilib &Multilib = GCCInstallation.getMultilib();
03114 
03115   std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
03116                       Multilib.osSuffix()).str();
03117 
03118   if (llvm::sys::fs::exists(Path))
03119     return Path;
03120 
03121   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
03122 
03123   if (llvm::sys::fs::exists(Path))
03124     return Path;
03125 
03126   return std::string();
03127 }
03128 
03129 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
03130                                       ArgStringList &CC1Args) const {
03131   const Driver &D = getDriver();
03132   std::string SysRoot = computeSysRoot();
03133 
03134   if (DriverArgs.hasArg(options::OPT_nostdinc))
03135     return;
03136 
03137   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
03138     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
03139 
03140   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
03141     SmallString<128> P(D.ResourceDir);
03142     llvm::sys::path::append(P, "include");
03143     addSystemInclude(DriverArgs, CC1Args, P.str());
03144   }
03145 
03146   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
03147     return;
03148 
03149   // Check for configure-time C include directories.
03150   StringRef CIncludeDirs(C_INCLUDE_DIRS);
03151   if (CIncludeDirs != "") {
03152     SmallVector<StringRef, 5> dirs;
03153     CIncludeDirs.split(dirs, ":");
03154     for (StringRef dir : dirs) {
03155       StringRef Prefix = llvm::sys::path::is_absolute(dir) ? SysRoot : "";
03156       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
03157     }
03158     return;
03159   }
03160 
03161   // Lacking those, try to detect the correct set of system includes for the
03162   // target triple.
03163 
03164   // Add include directories specific to the selected multilib set and multilib.
03165   if (GCCInstallation.isValid()) {
03166     auto Callback = Multilibs.includeDirsCallback();
03167     if (Callback) {
03168       const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
03169                                          GCCInstallation.getTriple().str(),
03170                                          GCCInstallation.getMultilib());
03171       for (const auto &Path : IncludePaths)
03172         addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
03173     }
03174   }
03175 
03176   // Implement generic Debian multiarch support.
03177   const StringRef X86_64MultiarchIncludeDirs[] = {
03178     "/usr/include/x86_64-linux-gnu",
03179 
03180     // FIXME: These are older forms of multiarch. It's not clear that they're
03181     // in use in any released version of Debian, so we should consider
03182     // removing them.
03183     "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
03184   };
03185   const StringRef X86MultiarchIncludeDirs[] = {
03186     "/usr/include/i386-linux-gnu",
03187 
03188     // FIXME: These are older forms of multiarch. It's not clear that they're
03189     // in use in any released version of Debian, so we should consider
03190     // removing them.
03191     "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
03192     "/usr/include/i486-linux-gnu"
03193   };
03194   const StringRef AArch64MultiarchIncludeDirs[] = {
03195     "/usr/include/aarch64-linux-gnu"
03196   };
03197   const StringRef ARMMultiarchIncludeDirs[] = {
03198     "/usr/include/arm-linux-gnueabi"
03199   };
03200   const StringRef ARMHFMultiarchIncludeDirs[] = {
03201     "/usr/include/arm-linux-gnueabihf"
03202   };
03203   const StringRef MIPSMultiarchIncludeDirs[] = {
03204     "/usr/include/mips-linux-gnu"
03205   };
03206   const StringRef MIPSELMultiarchIncludeDirs[] = {
03207     "/usr/include/mipsel-linux-gnu"
03208   };
03209   const StringRef MIPS64MultiarchIncludeDirs[] = {
03210     "/usr/include/mips64-linux-gnu",
03211     "/usr/include/mips64-linux-gnuabi64"
03212   };
03213   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
03214     "/usr/include/mips64el-linux-gnu",
03215     "/usr/include/mips64el-linux-gnuabi64"
03216   };
03217   const StringRef PPCMultiarchIncludeDirs[] = {
03218     "/usr/include/powerpc-linux-gnu"
03219   };
03220   const StringRef PPC64MultiarchIncludeDirs[] = {
03221     "/usr/include/powerpc64-linux-gnu"
03222   };
03223   const StringRef PPC64LEMultiarchIncludeDirs[] = {
03224     "/usr/include/powerpc64le-linux-gnu"
03225   };
03226   ArrayRef<StringRef> MultiarchIncludeDirs;
03227   if (getTriple().getArch() == llvm::Triple::x86_64) {
03228     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
03229   } else if (getTriple().getArch() == llvm::Triple::x86) {
03230     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
03231   } else if (getTriple().getArch() == llvm::Triple::aarch64 ||
03232              getTriple().getArch() == llvm::Triple::aarch64_be) {
03233     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
03234   } else if (getTriple().getArch() == llvm::Triple::arm) {
03235     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
03236       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
03237     else
03238       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
03239   } else if (getTriple().getArch() == llvm::Triple::mips) {
03240     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
03241   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
03242     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
03243   } else if (getTriple().getArch() == llvm::Triple::mips64) {
03244     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
03245   } else if (getTriple().getArch() == llvm::Triple::mips64el) {
03246     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
03247   } else if (getTriple().getArch() == llvm::Triple::ppc) {
03248     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
03249   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
03250     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
03251   } else if (getTriple().getArch() == llvm::Triple::ppc64le) {
03252     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
03253   }
03254   for (StringRef Dir : MultiarchIncludeDirs) {
03255     if (llvm::sys::fs::exists(SysRoot + Dir)) {
03256       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
03257       break;
03258     }
03259   }
03260 
03261   if (getTriple().getOS() == llvm::Triple::RTEMS)
03262     return;
03263 
03264   // Add an include of '/include' directly. This isn't provided by default by
03265   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
03266   // add even when Clang is acting as-if it were a system compiler.
03267   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
03268 
03269   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
03270 }
03271 
03272 /// \brief Helper to add the variant paths of a libstdc++ installation.
03273 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
03274                                                 StringRef GCCTriple,
03275                                                 StringRef GCCMultiarchTriple,
03276                                                 StringRef TargetMultiarchTriple,
03277                                                 Twine IncludeSuffix,
03278                                                 const ArgList &DriverArgs,
03279                                                 ArgStringList &CC1Args) {
03280   if (!llvm::sys::fs::exists(Base + Suffix))
03281     return false;
03282 
03283   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
03284 
03285   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
03286   // that path exists or we have neither a GCC nor target multiarch triple, use
03287   // this vanilla search path.
03288   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
03289       llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
03290     addSystemInclude(DriverArgs, CC1Args,
03291                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
03292   } else {
03293     // Otherwise try to use multiarch naming schemes which have normalized the
03294     // triples and put the triple before the suffix.
03295     //
03296     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
03297     // the target triple, so we support that here.
03298     addSystemInclude(DriverArgs, CC1Args,
03299                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
03300     addSystemInclude(DriverArgs, CC1Args,
03301                      Base + "/" + TargetMultiarchTriple + Suffix);
03302   }
03303 
03304   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
03305   return true;
03306 }
03307 
03308 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
03309                                          ArgStringList &CC1Args) const {
03310   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
03311       DriverArgs.hasArg(options::OPT_nostdincxx))
03312     return;
03313 
03314   // Check if libc++ has been enabled and provide its include paths if so.
03315   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
03316     const std::string LibCXXIncludePathCandidates[] = {
03317       // The primary location is within the Clang installation.
03318       // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
03319       // newer ABI versions.
03320       getDriver().Dir + "/../include/c++/v1",
03321 
03322       // We also check the system as for a long time this is the only place Clang looked.
03323       // FIXME: We should really remove this. It doesn't make any sense.
03324       getDriver().SysRoot + "/usr/include/c++/v1"
03325     };
03326     for (const auto &IncludePath : LibCXXIncludePathCandidates) {
03327       if (!llvm::sys::fs::exists(IncludePath))
03328         continue;
03329       // Add the first candidate that exists.
03330       addSystemInclude(DriverArgs, CC1Args, IncludePath);
03331       break;
03332     }
03333     return;
03334   }
03335 
03336   // We need a detected GCC installation on Linux to provide libstdc++'s
03337   // headers. We handled the libc++ case above.
03338   if (!GCCInstallation.isValid())
03339     return;
03340 
03341   // By default, look for the C++ headers in an include directory adjacent to
03342   // the lib directory of the GCC installation. Note that this is expect to be
03343   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
03344   StringRef LibDir = GCCInstallation.getParentLibPath();
03345   StringRef InstallDir = GCCInstallation.getInstallPath();
03346   StringRef TripleStr = GCCInstallation.getTriple().str();
03347   const Multilib &Multilib = GCCInstallation.getMultilib();
03348   const std::string GCCMultiarchTriple =
03349       getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
03350   const std::string TargetMultiarchTriple =
03351       getMultiarchTriple(getTriple(), getDriver().SysRoot);
03352   const GCCVersion &Version = GCCInstallation.getVersion();
03353 
03354   // The primary search for libstdc++ supports multiarch variants.
03355   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
03356                                "/c++/" + Version.Text, TripleStr, GCCMultiarchTriple,
03357                                TargetMultiarchTriple,
03358                                Multilib.includeSuffix(), DriverArgs, CC1Args))
03359     return;
03360 
03361   // Otherwise, fall back on a bunch of options which don't use multiarch
03362   // layouts for simplicity.
03363   const std::string LibStdCXXIncludePathCandidates[] = {
03364     // Gentoo is weird and places its headers inside the GCC install, so if the
03365     // first attempt to find the headers fails, try these patterns.
03366     InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
03367         Version.MinorStr,
03368     InstallDir.str() + "/include/g++-v" + Version.MajorStr,
03369     // Android standalone toolchain has C++ headers in yet another place.
03370     LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
03371     // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
03372     // without a subdirectory corresponding to the gcc version.
03373     LibDir.str() + "/../include/c++",
03374   };
03375 
03376   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
03377     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
03378                                  /*GCCMultiarchTriple*/ "",
03379                                  /*TargetMultiarchTriple*/ "",
03380                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
03381       break;
03382   }
03383 }
03384 
03385 bool Linux::isPIEDefault() const {
03386   return getSanitizerArgs().hasZeroBaseShadow();
03387 }
03388 
03389 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
03390 
03391 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
03392   : Generic_ELF(D, Triple, Args) {
03393 
03394   // Path mangling to find libexec
03395   getProgramPaths().push_back(getDriver().getInstalledDir());
03396   if (getDriver().getInstalledDir() != getDriver().Dir)
03397     getProgramPaths().push_back(getDriver().Dir);
03398 
03399   getFilePaths().push_back(getDriver().Dir + "/../lib");
03400   getFilePaths().push_back("/usr/lib");
03401   if (llvm::sys::fs::exists("/usr/lib/gcc47"))
03402     getFilePaths().push_back("/usr/lib/gcc47");
03403   else
03404     getFilePaths().push_back("/usr/lib/gcc44");
03405 }
03406 
03407 Tool *DragonFly::buildAssembler() const {
03408   return new tools::dragonfly::Assemble(*this);
03409 }
03410 
03411 Tool *DragonFly::buildLinker() const {
03412   return new tools::dragonfly::Link(*this);
03413 }
03414 
03415 
03416 /// XCore tool chain
03417 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
03418              const ArgList &Args) : ToolChain(D, Triple, Args) {
03419   // ProgramPaths are found via 'PATH' environment variable.
03420 }
03421 
03422 Tool *XCore::buildAssembler() const {
03423   return new tools::XCore::Assemble(*this);
03424 }
03425 
03426 Tool *XCore::buildLinker() const {
03427   return new tools::XCore::Link(*this);
03428 }
03429 
03430 bool XCore::isPICDefault() const {
03431   return false;
03432 }
03433 
03434 bool XCore::isPIEDefault() const {
03435   return false;
03436 }
03437 
03438 bool XCore::isPICDefaultForced() const {
03439   return false;
03440 }
03441 
03442 bool XCore::SupportsProfiling() const {
03443   return false;
03444 }
03445 
03446 bool XCore::hasBlocksRuntime() const {
03447   return false;
03448 }
03449 
03450 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
03451                                       ArgStringList &CC1Args) const {
03452   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
03453       DriverArgs.hasArg(options::OPT_nostdlibinc))
03454     return;
03455   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
03456     SmallVector<StringRef, 4> Dirs;
03457     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
03458     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
03459     ArrayRef<StringRef> DirVec(Dirs);
03460     addSystemIncludes(DriverArgs, CC1Args, DirVec);
03461   }
03462 }
03463 
03464 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
03465                                      llvm::opt::ArgStringList &CC1Args) const {
03466   CC1Args.push_back("-nostdsysteminc");
03467 }
03468 
03469 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
03470                                          ArgStringList &CC1Args) const {
03471   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
03472       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
03473       DriverArgs.hasArg(options::OPT_nostdincxx))
03474     return;
03475   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
03476     SmallVector<StringRef, 4> Dirs;
03477     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
03478     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
03479     ArrayRef<StringRef> DirVec(Dirs);
03480     addSystemIncludes(DriverArgs, CC1Args, DirVec);
03481   }
03482 }
03483 
03484 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
03485                                 ArgStringList &CmdArgs) const {
03486   // We don't output any lib args. This is handled by xcc.
03487 }