ToolChains.cpp revision 85b7f7ddf2f09778ec303f5a39f9e67e3aae1115
1//===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ToolChains.h"
11
12#include "clang/Driver/Arg.h"
13#include "clang/Driver/ArgList.h"
14#include "clang/Driver/Compilation.h"
15#include "clang/Driver/Driver.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/OptTable.h"
18#include "clang/Driver/Option.h"
19#include "clang/Driver/Options.h"
20#include "clang/Basic/ObjCRuntime.h"
21#include "clang/Basic/Version.h"
22
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/Path.h"
32#include "llvm/Support/system_error.h"
33
34#include "SanitizerArgs.h"
35
36#include <cstdlib> // ::getenv
37
38#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
39
40using namespace clang::driver;
41using namespace clang::driver::toolchains;
42using namespace clang;
43
44/// Darwin - Darwin tool chain for i386 and x86_64.
45
46Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
47  : ToolChain(D, Triple), TargetInitialized(false)
48{
49  // Compute the initial Darwin version from the triple
50  unsigned Major, Minor, Micro;
51  if (!Triple.getMacOSXVersion(Major, Minor, Micro))
52    getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
53      Triple.getOSName();
54  llvm::raw_string_ostream(MacosxVersionMin)
55    << Major << '.' << Minor << '.' << Micro;
56
57  // FIXME: DarwinVersion is only used to find GCC's libexec directory.
58  // It should be removed when we stop supporting that.
59  DarwinVersion[0] = Minor + 4;
60  DarwinVersion[1] = Micro;
61  DarwinVersion[2] = 0;
62
63  // Compute the initial iOS version from the triple
64  Triple.getiOSVersion(Major, Minor, Micro);
65  llvm::raw_string_ostream(iOSVersionMin)
66    << Major << '.' << Minor << '.' << Micro;
67}
68
69types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
70  types::ID Ty = types::lookupTypeForExtension(Ext);
71
72  // Darwin always preprocesses assembly files (unless -x is used explicitly).
73  if (Ty == types::TY_PP_Asm)
74    return types::TY_Asm;
75
76  return Ty;
77}
78
79bool Darwin::HasNativeLLVMSupport() const {
80  return true;
81}
82
83/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
84ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
85  if (isTargetIPhoneOS()) {
86    return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
87  } else if (TargetSimulatorVersionFromDefines != VersionTuple()) {
88    return ObjCRuntime(ObjCRuntime::iOS, TargetSimulatorVersionFromDefines);
89  } else {
90    if (isNonFragile) {
91      return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
92    } else {
93      return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
94    }
95  }
96}
97
98/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
99bool Darwin::hasBlocksRuntime() const {
100  if (isTargetIPhoneOS())
101    return !isIPhoneOSVersionLT(3, 2);
102  else
103    return !isMacosxVersionLT(10, 6);
104}
105
106static const char *GetArmArchForMArch(StringRef Value) {
107  return llvm::StringSwitch<const char*>(Value)
108    .Case("armv6k", "armv6")
109    .Case("armv5tej", "armv5")
110    .Case("xscale", "xscale")
111    .Case("armv4t", "armv4t")
112    .Case("armv7", "armv7")
113    .Cases("armv7a", "armv7-a", "armv7")
114    .Cases("armv7r", "armv7-r", "armv7")
115    .Cases("armv7m", "armv7-m", "armv7")
116    .Cases("armv7f", "armv7-f", "armv7f")
117    .Cases("armv7k", "armv7-k", "armv7k")
118    .Cases("armv7s", "armv7-s", "armv7s")
119    .Default(0);
120}
121
122static const char *GetArmArchForMCpu(StringRef Value) {
123  return llvm::StringSwitch<const char *>(Value)
124    .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
125    .Cases("arm10e", "arm10tdmi", "armv5")
126    .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
127    .Case("xscale", "xscale")
128    .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s",
129           "arm1176jzf-s", "cortex-m0", "armv6")
130    .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "cortex-a15",
131           "armv7")
132    .Case("cortex-a9-mp", "armv7f")
133    .Case("swift", "armv7s")
134    .Default(0);
135}
136
137StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
138  switch (getTriple().getArch()) {
139  default:
140    return getArchName();
141
142  case llvm::Triple::thumb:
143  case llvm::Triple::arm: {
144    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
145      if (const char *Arch = GetArmArchForMArch(A->getValue()))
146        return Arch;
147
148    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
149      if (const char *Arch = GetArmArchForMCpu(A->getValue()))
150        return Arch;
151
152    return "arm";
153  }
154  }
155}
156
157Darwin::~Darwin() {
158  // Free tool implementations.
159  for (llvm::DenseMap<unsigned, Tool*>::iterator
160         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
161    delete it->second;
162}
163
164std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
165                                                types::ID InputType) const {
166  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
167
168  // If the target isn't initialized (e.g., an unknown Darwin platform, return
169  // the default triple).
170  if (!isTargetInitialized())
171    return Triple.getTriple();
172
173  SmallString<16> Str;
174  Str += isTargetIPhoneOS() ? "ios" : "macosx";
175  Str += getTargetVersion().getAsString();
176  Triple.setOSName(Str);
177
178  return Triple.getTriple();
179}
180
181void Generic_ELF::anchor() {}
182
183Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
184                         const ActionList &Inputs) const {
185  Action::ActionClass Key = JA.getKind();
186  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
187                                             options::OPT_no_integrated_as,
188                                             IsIntegratedAssemblerDefault());
189
190  Tool *&T = Tools[Key];
191  if (!T) {
192    switch (Key) {
193    case Action::InputClass:
194    case Action::BindArchClass:
195      llvm_unreachable("Invalid tool kind.");
196    case Action::PreprocessJobClass:
197    case Action::AnalyzeJobClass:
198    case Action::MigrateJobClass:
199    case Action::PrecompileJobClass:
200    case Action::CompileJobClass:
201      T = new tools::Clang(*this); break;
202    case Action::AssembleJobClass: {
203      if (UseIntegratedAs)
204        T = new tools::ClangAs(*this);
205      else
206        T = new tools::darwin::Assemble(*this);
207      break;
208    }
209    case Action::LinkJobClass:
210      T = new tools::darwin::Link(*this); break;
211    case Action::LipoJobClass:
212      T = new tools::darwin::Lipo(*this); break;
213    case Action::DsymutilJobClass:
214      T = new tools::darwin::Dsymutil(*this); break;
215    case Action::VerifyJobClass:
216      T = new tools::darwin::VerifyDebug(*this); break;
217    }
218  }
219
220  return *T;
221}
222
223
224DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
225  : Darwin(D, Triple)
226{
227  getProgramPaths().push_back(getDriver().getInstalledDir());
228  if (getDriver().getInstalledDir() != getDriver().Dir)
229    getProgramPaths().push_back(getDriver().Dir);
230
231  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
232  getProgramPaths().push_back(getDriver().getInstalledDir());
233  if (getDriver().getInstalledDir() != getDriver().Dir)
234    getProgramPaths().push_back(getDriver().Dir);
235
236  // For fallback, we need to know how to find the GCC cc1 executables, so we
237  // also add the GCC libexec paths. This is legacy code that can be removed
238  // once fallback is no longer useful.
239  AddGCCLibexecPath(DarwinVersion[0]);
240  AddGCCLibexecPath(DarwinVersion[0] - 2);
241  AddGCCLibexecPath(DarwinVersion[0] - 1);
242  AddGCCLibexecPath(DarwinVersion[0] + 1);
243  AddGCCLibexecPath(DarwinVersion[0] + 2);
244}
245
246void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) {
247  std::string ToolChainDir = "i686-apple-darwin";
248  ToolChainDir += llvm::utostr(darwinVersion);
249  ToolChainDir += "/4.2.1";
250
251  std::string Path = getDriver().Dir;
252  Path += "/../llvm-gcc-4.2/libexec/gcc/";
253  Path += ToolChainDir;
254  getProgramPaths().push_back(Path);
255
256  Path = "/usr/llvm-gcc-4.2/libexec/gcc/";
257  Path += ToolChainDir;
258  getProgramPaths().push_back(Path);
259}
260
261void DarwinClang::AddLinkARCArgs(const ArgList &Args,
262                                 ArgStringList &CmdArgs) const {
263
264  CmdArgs.push_back("-force_load");
265  llvm::sys::Path P(getDriver().ClangExecutable);
266  P.eraseComponent(); // 'clang'
267  P.eraseComponent(); // 'bin'
268  P.appendComponent("lib");
269  P.appendComponent("arc");
270  P.appendComponent("libarclite_");
271  std::string s = P.str();
272  // Mash in the platform.
273  if (isTargetIOSSimulator())
274    s += "iphonesimulator";
275  else if (isTargetIPhoneOS())
276    s += "iphoneos";
277  // FIXME: Remove this once we depend fully on -mios-simulator-version-min.
278  else if (TargetSimulatorVersionFromDefines != VersionTuple())
279    s += "iphonesimulator";
280  else
281    s += "macosx";
282  s += ".a";
283
284  CmdArgs.push_back(Args.MakeArgString(s));
285}
286
287void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
288                                    ArgStringList &CmdArgs,
289                                    const char *DarwinStaticLib) const {
290  llvm::sys::Path P(getDriver().ResourceDir);
291  P.appendComponent("lib");
292  P.appendComponent("darwin");
293  P.appendComponent(DarwinStaticLib);
294
295  // For now, allow missing resource libraries to support developers who may
296  // not have compiler-rt checked out or integrated into their build.
297  bool Exists;
298  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
299    CmdArgs.push_back(Args.MakeArgString(P.str()));
300}
301
302void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
303                                        ArgStringList &CmdArgs) const {
304  // Darwin only supports the compiler-rt based runtime libraries.
305  switch (GetRuntimeLibType(Args)) {
306  case ToolChain::RLT_CompilerRT:
307    break;
308  default:
309    getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
310      << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
311    return;
312  }
313
314  // Darwin doesn't support real static executables, don't link any runtime
315  // libraries with -static.
316  if (Args.hasArg(options::OPT_static) ||
317      Args.hasArg(options::OPT_fapple_kext) ||
318      Args.hasArg(options::OPT_mkernel))
319    return;
320
321  // Reject -static-libgcc for now, we can deal with this when and if someone
322  // cares. This is useful in situations where someone wants to statically link
323  // something like libstdc++, and needs its runtime support routines.
324  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
325    getDriver().Diag(diag::err_drv_unsupported_opt)
326      << A->getAsString(Args);
327    return;
328  }
329
330  // If we are building profile support, link that library in.
331  if (Args.hasArg(options::OPT_fprofile_arcs) ||
332      Args.hasArg(options::OPT_fprofile_generate) ||
333      Args.hasArg(options::OPT_fcreate_profile) ||
334      Args.hasArg(options::OPT_coverage)) {
335    // Select the appropriate runtime library for the target.
336    if (isTargetIPhoneOS()) {
337      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
338    } else {
339      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
340    }
341  }
342
343  SanitizerArgs Sanitize(getDriver(), Args);
344
345  // Add ASAN runtime library, if required. Dynamic libraries and bundles
346  // should not be linked with the runtime library.
347  if (Sanitize.needsAsanRt()) {
348    if (Args.hasArg(options::OPT_dynamiclib) ||
349        Args.hasArg(options::OPT_bundle)) return;
350    if (isTargetIPhoneOS()) {
351      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
352        << "-fsanitize=address";
353    } else {
354      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
355
356      // The ASAN runtime library requires C++ and CoreFoundation.
357      AddCXXStdlibLibArgs(Args, CmdArgs);
358      CmdArgs.push_back("-framework");
359      CmdArgs.push_back("CoreFoundation");
360    }
361  }
362
363  // Otherwise link libSystem, then the dynamic runtime library, and finally any
364  // target specific static runtime library.
365  CmdArgs.push_back("-lSystem");
366
367  // Select the dynamic runtime library and the target specific static library.
368  if (isTargetIPhoneOS()) {
369    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
370    // it never went into the SDK.
371    // Linking against libgcc_s.1 isn't needed for iOS 5.0+
372    if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
373      CmdArgs.push_back("-lgcc_s.1");
374
375    // We currently always need a static runtime library for iOS.
376    AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
377  } else {
378    // The dynamic runtime library was merged with libSystem for 10.6 and
379    // beyond; only 10.4 and 10.5 need an additional runtime library.
380    if (isMacosxVersionLT(10, 5))
381      CmdArgs.push_back("-lgcc_s.10.4");
382    else if (isMacosxVersionLT(10, 6))
383      CmdArgs.push_back("-lgcc_s.10.5");
384
385    // For OS X, we thought we would only need a static runtime library when
386    // targeting 10.4, to provide versions of the static functions which were
387    // omitted from 10.4.dylib.
388    //
389    // Unfortunately, that turned out to not be true, because Darwin system
390    // headers can still use eprintf on i386, and it is not exported from
391    // libSystem. Therefore, we still must provide a runtime library just for
392    // the tiny tiny handful of projects that *might* use that symbol.
393    if (isMacosxVersionLT(10, 5)) {
394      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
395    } else {
396      if (getTriple().getArch() == llvm::Triple::x86)
397        AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
398      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
399    }
400  }
401}
402
403static inline StringRef SimulatorVersionDefineName() {
404  return "__IPHONE_OS_VERSION_MIN_REQUIRED";
405}
406
407/// \brief Parse the simulator version define:
408/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
409// and return the grouped values as integers, e.g:
410//   __IPHONE_OS_VERSION_MIN_REQUIRED=40201
411// will return Major=4, Minor=2, Micro=1.
412static bool GetVersionFromSimulatorDefine(StringRef define,
413                                          unsigned &Major, unsigned &Minor,
414                                          unsigned &Micro) {
415  assert(define.startswith(SimulatorVersionDefineName()));
416  StringRef name, version;
417  llvm::tie(name, version) = define.split('=');
418  if (version.empty())
419    return false;
420  std::string verstr = version.str();
421  char *end;
422  unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
423  if (*end != '\0')
424    return false;
425  Major = num / 10000;
426  num = num % 10000;
427  Minor = num / 100;
428  Micro = num % 100;
429  return true;
430}
431
432void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
433  const OptTable &Opts = getDriver().getOpts();
434
435  // Support allowing the SDKROOT environment variable used by xcrun and other
436  // Xcode tools to define the default sysroot, by making it the default for
437  // isysroot.
438  if (!Args.hasArg(options::OPT_isysroot)) {
439    if (char *env = ::getenv("SDKROOT")) {
440      // We only use this value as the default if it is an absolute path and
441      // exists.
442      if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env)) {
443        Args.append(Args.MakeSeparateArg(
444                      0, Opts.getOption(options::OPT_isysroot), env));
445      }
446    }
447  }
448
449  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
450  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
451  Arg *iOSSimVersion = Args.getLastArg(
452    options::OPT_mios_simulator_version_min_EQ);
453
454  // FIXME: HACK! When compiling for the simulator we don't get a
455  // '-miphoneos-version-min' to help us know whether there is an ARC runtime
456  // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED
457  // define passed in command-line.
458  if (!iOSVersion && !iOSSimVersion) {
459    for (arg_iterator it = Args.filtered_begin(options::OPT_D),
460           ie = Args.filtered_end(); it != ie; ++it) {
461      StringRef define = (*it)->getValue();
462      if (define.startswith(SimulatorVersionDefineName())) {
463        unsigned Major = 0, Minor = 0, Micro = 0;
464        if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
465            Major < 10 && Minor < 100 && Micro < 100) {
466          TargetSimulatorVersionFromDefines = VersionTuple(Major, Minor, Micro);
467        }
468        // When using the define to indicate the simulator, we force
469        // 10.6 macosx target.
470        const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
471        OSXVersion = Args.MakeJoinedArg(0, O, "10.6");
472        Args.append(OSXVersion);
473        break;
474      }
475    }
476  }
477
478  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
479    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
480          << OSXVersion->getAsString(Args)
481          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
482    iOSVersion = iOSSimVersion = 0;
483  } else if (iOSVersion && iOSSimVersion) {
484    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
485          << iOSVersion->getAsString(Args)
486          << iOSSimVersion->getAsString(Args);
487    iOSSimVersion = 0;
488  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
489    // If no deployment target was specified on the command line, check for
490    // environment defines.
491    StringRef OSXTarget;
492    StringRef iOSTarget;
493    StringRef iOSSimTarget;
494    if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
495      OSXTarget = env;
496    if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
497      iOSTarget = env;
498    if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
499      iOSSimTarget = env;
500
501    // If no '-miphoneos-version-min' specified on the command line and
502    // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
503    // based on -isysroot.
504    if (iOSTarget.empty()) {
505      if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
506        StringRef first, second;
507        StringRef isysroot = A->getValue();
508        llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
509        if (second != "")
510          iOSTarget = second.substr(0,3);
511      }
512    }
513
514    // If no OSX or iOS target has been specified and we're compiling for armv7,
515    // go ahead as assume we're targeting iOS.
516    if (OSXTarget.empty() && iOSTarget.empty() &&
517        (getDarwinArchName(Args) == "armv7" ||
518         getDarwinArchName(Args) == "armv7s"))
519        iOSTarget = iOSVersionMin;
520
521    // Handle conflicting deployment targets
522    //
523    // FIXME: Don't hardcode default here.
524
525    // Do not allow conflicts with the iOS simulator target.
526    if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
527      getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
528        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
529        << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
530            "IPHONEOS_DEPLOYMENT_TARGET");
531    }
532
533    // Allow conflicts among OSX and iOS for historical reasons, but choose the
534    // default platform.
535    if (!OSXTarget.empty() && !iOSTarget.empty()) {
536      if (getTriple().getArch() == llvm::Triple::arm ||
537          getTriple().getArch() == llvm::Triple::thumb)
538        OSXTarget = "";
539      else
540        iOSTarget = "";
541    }
542
543    if (!OSXTarget.empty()) {
544      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
545      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
546      Args.append(OSXVersion);
547    } else if (!iOSTarget.empty()) {
548      const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
549      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
550      Args.append(iOSVersion);
551    } else if (!iOSSimTarget.empty()) {
552      const Option O = Opts.getOption(
553        options::OPT_mios_simulator_version_min_EQ);
554      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
555      Args.append(iOSSimVersion);
556    } else {
557      // Otherwise, assume we are targeting OS X.
558      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
559      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
560      Args.append(OSXVersion);
561    }
562  }
563
564  // Reject invalid architecture combinations.
565  if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
566                        getTriple().getArch() != llvm::Triple::x86_64)) {
567    getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
568      << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
569  }
570
571  // Set the tool chain target information.
572  unsigned Major, Minor, Micro;
573  bool HadExtra;
574  if (OSXVersion) {
575    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
576    if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
577                                   Micro, HadExtra) || HadExtra ||
578        Major != 10 || Minor >= 100 || Micro >= 100)
579      getDriver().Diag(diag::err_drv_invalid_version_number)
580        << OSXVersion->getAsString(Args);
581  } else {
582    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
583    assert(Version && "Unknown target platform!");
584    if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
585                                   Micro, HadExtra) || HadExtra ||
586        Major >= 10 || Minor >= 100 || Micro >= 100)
587      getDriver().Diag(diag::err_drv_invalid_version_number)
588        << Version->getAsString(Args);
589  }
590
591  bool IsIOSSim = bool(iOSSimVersion);
592
593  // In GCC, the simulator historically was treated as being OS X in some
594  // contexts, like determining the link logic, despite generally being called
595  // with an iOS deployment target. For compatibility, we detect the
596  // simulator as iOS + x86, and treat it differently in a few contexts.
597  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
598                     getTriple().getArch() == llvm::Triple::x86_64))
599    IsIOSSim = true;
600
601  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
602}
603
604void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
605                                      ArgStringList &CmdArgs) const {
606  CXXStdlibType Type = GetCXXStdlibType(Args);
607
608  switch (Type) {
609  case ToolChain::CST_Libcxx:
610    CmdArgs.push_back("-lc++");
611    break;
612
613  case ToolChain::CST_Libstdcxx: {
614    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
615    // it was previously found in the gcc lib dir. However, for all the Darwin
616    // platforms we care about it was -lstdc++.6, so we search for that
617    // explicitly if we can't see an obvious -lstdc++ candidate.
618
619    // Check in the sysroot first.
620    bool Exists;
621    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
622      llvm::sys::Path P(A->getValue());
623      P.appendComponent("usr");
624      P.appendComponent("lib");
625      P.appendComponent("libstdc++.dylib");
626
627      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
628        P.eraseComponent();
629        P.appendComponent("libstdc++.6.dylib");
630        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
631          CmdArgs.push_back(Args.MakeArgString(P.str()));
632          return;
633        }
634      }
635    }
636
637    // Otherwise, look in the root.
638    // FIXME: This should be removed someday when we don't have to care about
639    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
640    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
641      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
642      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
643      return;
644    }
645
646    // Otherwise, let the linker search.
647    CmdArgs.push_back("-lstdc++");
648    break;
649  }
650  }
651}
652
653void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
654                                   ArgStringList &CmdArgs) const {
655
656  // For Darwin platforms, use the compiler-rt-based support library
657  // instead of the gcc-provided one (which is also incidentally
658  // only present in the gcc lib dir, which makes it hard to find).
659
660  llvm::sys::Path P(getDriver().ResourceDir);
661  P.appendComponent("lib");
662  P.appendComponent("darwin");
663
664  // Use the newer cc_kext for iOS ARM after 6.0.
665  if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
666      !isIPhoneOSVersionLT(6, 0)) {
667    P.appendComponent("libclang_rt.cc_kext.a");
668  } else {
669    P.appendComponent("libclang_rt.cc_kext_ios5.a");
670  }
671
672  // For now, allow missing resource libraries to support developers who may
673  // not have compiler-rt checked out or integrated into their build.
674  bool Exists;
675  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
676    CmdArgs.push_back(Args.MakeArgString(P.str()));
677}
678
679DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
680                                      const char *BoundArch) const {
681  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
682  const OptTable &Opts = getDriver().getOpts();
683
684  // FIXME: We really want to get out of the tool chain level argument
685  // translation business, as it makes the driver functionality much
686  // more opaque. For now, we follow gcc closely solely for the
687  // purpose of easily achieving feature parity & testability. Once we
688  // have something that works, we should reevaluate each translation
689  // and try to push it down into tool specific logic.
690
691  for (ArgList::const_iterator it = Args.begin(),
692         ie = Args.end(); it != ie; ++it) {
693    Arg *A = *it;
694
695    if (A->getOption().matches(options::OPT_Xarch__)) {
696      // Skip this argument unless the architecture matches either the toolchain
697      // triple arch, or the arch being bound.
698      llvm::Triple::ArchType XarchArch =
699        tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
700      if (!(XarchArch == getArch()  ||
701            (BoundArch && XarchArch ==
702             tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
703        continue;
704
705      Arg *OriginalArg = A;
706      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
707      unsigned Prev = Index;
708      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
709
710      // If the argument parsing failed or more than one argument was
711      // consumed, the -Xarch_ argument's parameter tried to consume
712      // extra arguments. Emit an error and ignore.
713      //
714      // We also want to disallow any options which would alter the
715      // driver behavior; that isn't going to work in our model. We
716      // use isDriverOption() as an approximation, although things
717      // like -O4 are going to slip through.
718      if (!XarchArg || Index > Prev + 1) {
719        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
720          << A->getAsString(Args);
721        continue;
722      } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
723        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
724          << A->getAsString(Args);
725        continue;
726      }
727
728      XarchArg->setBaseArg(A);
729      A = XarchArg;
730
731      DAL->AddSynthesizedArg(A);
732
733      // Linker input arguments require custom handling. The problem is that we
734      // have already constructed the phase actions, so we can not treat them as
735      // "input arguments".
736      if (A->getOption().hasFlag(options::LinkerInput)) {
737        // Convert the argument into individual Zlinker_input_args.
738        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
739          DAL->AddSeparateArg(OriginalArg,
740                              Opts.getOption(options::OPT_Zlinker_input),
741                              A->getValue(i));
742
743        }
744        continue;
745      }
746    }
747
748    // Sob. These is strictly gcc compatible for the time being. Apple
749    // gcc translates options twice, which means that self-expanding
750    // options add duplicates.
751    switch ((options::ID) A->getOption().getID()) {
752    default:
753      DAL->append(A);
754      break;
755
756    case options::OPT_mkernel:
757    case options::OPT_fapple_kext:
758      DAL->append(A);
759      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
760      break;
761
762    case options::OPT_dependency_file:
763      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
764                          A->getValue());
765      break;
766
767    case options::OPT_gfull:
768      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
769      DAL->AddFlagArg(A,
770               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
771      break;
772
773    case options::OPT_gused:
774      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
775      DAL->AddFlagArg(A,
776             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
777      break;
778
779    case options::OPT_shared:
780      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
781      break;
782
783    case options::OPT_fconstant_cfstrings:
784      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
785      break;
786
787    case options::OPT_fno_constant_cfstrings:
788      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
789      break;
790
791    case options::OPT_Wnonportable_cfstrings:
792      DAL->AddFlagArg(A,
793                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
794      break;
795
796    case options::OPT_Wno_nonportable_cfstrings:
797      DAL->AddFlagArg(A,
798                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
799      break;
800
801    case options::OPT_fpascal_strings:
802      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
803      break;
804
805    case options::OPT_fno_pascal_strings:
806      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
807      break;
808    }
809  }
810
811  if (getTriple().getArch() == llvm::Triple::x86 ||
812      getTriple().getArch() == llvm::Triple::x86_64)
813    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
814      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
815
816  // Add the arch options based on the particular spelling of -arch, to match
817  // how the driver driver works.
818  if (BoundArch) {
819    StringRef Name = BoundArch;
820    const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
821    const Option MArch = Opts.getOption(options::OPT_march_EQ);
822
823    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
824    // which defines the list of which architectures we accept.
825    if (Name == "ppc")
826      ;
827    else if (Name == "ppc601")
828      DAL->AddJoinedArg(0, MCpu, "601");
829    else if (Name == "ppc603")
830      DAL->AddJoinedArg(0, MCpu, "603");
831    else if (Name == "ppc604")
832      DAL->AddJoinedArg(0, MCpu, "604");
833    else if (Name == "ppc604e")
834      DAL->AddJoinedArg(0, MCpu, "604e");
835    else if (Name == "ppc750")
836      DAL->AddJoinedArg(0, MCpu, "750");
837    else if (Name == "ppc7400")
838      DAL->AddJoinedArg(0, MCpu, "7400");
839    else if (Name == "ppc7450")
840      DAL->AddJoinedArg(0, MCpu, "7450");
841    else if (Name == "ppc970")
842      DAL->AddJoinedArg(0, MCpu, "970");
843
844    else if (Name == "ppc64")
845      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
846
847    else if (Name == "i386")
848      ;
849    else if (Name == "i486")
850      DAL->AddJoinedArg(0, MArch, "i486");
851    else if (Name == "i586")
852      DAL->AddJoinedArg(0, MArch, "i586");
853    else if (Name == "i686")
854      DAL->AddJoinedArg(0, MArch, "i686");
855    else if (Name == "pentium")
856      DAL->AddJoinedArg(0, MArch, "pentium");
857    else if (Name == "pentium2")
858      DAL->AddJoinedArg(0, MArch, "pentium2");
859    else if (Name == "pentpro")
860      DAL->AddJoinedArg(0, MArch, "pentiumpro");
861    else if (Name == "pentIIm3")
862      DAL->AddJoinedArg(0, MArch, "pentium2");
863
864    else if (Name == "x86_64")
865      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
866
867    else if (Name == "arm")
868      DAL->AddJoinedArg(0, MArch, "armv4t");
869    else if (Name == "armv4t")
870      DAL->AddJoinedArg(0, MArch, "armv4t");
871    else if (Name == "armv5")
872      DAL->AddJoinedArg(0, MArch, "armv5tej");
873    else if (Name == "xscale")
874      DAL->AddJoinedArg(0, MArch, "xscale");
875    else if (Name == "armv6")
876      DAL->AddJoinedArg(0, MArch, "armv6k");
877    else if (Name == "armv7")
878      DAL->AddJoinedArg(0, MArch, "armv7a");
879    else if (Name == "armv7f")
880      DAL->AddJoinedArg(0, MArch, "armv7f");
881    else if (Name == "armv7k")
882      DAL->AddJoinedArg(0, MArch, "armv7k");
883    else if (Name == "armv7s")
884      DAL->AddJoinedArg(0, MArch, "armv7s");
885
886    else
887      llvm_unreachable("invalid Darwin arch");
888  }
889
890  // Add an explicit version min argument for the deployment target. We do this
891  // after argument translation because -Xarch_ arguments may add a version min
892  // argument.
893  if (BoundArch)
894    AddDeploymentTarget(*DAL);
895
896  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
897  // FIXME: It would be far better to avoid inserting those -static arguments,
898  // but we can't check the deployment target in the translation code until
899  // it is set here.
900  if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
901    for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
902      Arg *A = *it;
903      ++it;
904      if (A->getOption().getID() != options::OPT_mkernel &&
905          A->getOption().getID() != options::OPT_fapple_kext)
906        continue;
907      assert(it != ie && "unexpected argument translation");
908      A = *it;
909      assert(A->getOption().getID() == options::OPT_static &&
910             "missing expected -static argument");
911      it = DAL->getArgs().erase(it);
912    }
913  }
914
915  // Validate the C++ standard library choice.
916  CXXStdlibType Type = GetCXXStdlibType(*DAL);
917  if (Type == ToolChain::CST_Libcxx) {
918    // Check whether the target provides libc++.
919    StringRef where;
920
921    // Complain about targetting iOS < 5.0 in any way.
922    if (TargetSimulatorVersionFromDefines != VersionTuple()) {
923      if (TargetSimulatorVersionFromDefines < VersionTuple(5, 0))
924        where = "iOS 5.0";
925    } else if (isTargetIPhoneOS()) {
926      if (isIPhoneOSVersionLT(5, 0))
927        where = "iOS 5.0";
928    }
929
930    if (where != StringRef()) {
931      getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
932        << where;
933    }
934  }
935
936  return DAL;
937}
938
939bool Darwin::IsUnwindTablesDefault() const {
940  return getArch() == llvm::Triple::x86_64;
941}
942
943bool Darwin::UseDwarfDebugFlags() const {
944  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
945    return S[0] != '\0';
946  return false;
947}
948
949bool Darwin::UseSjLjExceptions() const {
950  // Darwin uses SjLj exceptions on ARM.
951  return (getTriple().getArch() == llvm::Triple::arm ||
952          getTriple().getArch() == llvm::Triple::thumb);
953}
954
955const char *Darwin::GetDefaultRelocationModel() const {
956  return "pic";
957}
958
959const char *Darwin::GetForcedPicModel() const {
960  if (getArch() == llvm::Triple::x86_64)
961    return "pic";
962  return 0;
963}
964
965bool Darwin::SupportsProfiling() const {
966  // Profiling instrumentation is only supported on x86.
967  return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
968}
969
970bool Darwin::SupportsObjCGC() const {
971  // Garbage collection is supported everywhere except on iPhone OS.
972  return !isTargetIPhoneOS();
973}
974
975void Darwin::CheckObjCARC() const {
976  if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
977    return;
978  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
979}
980
981std::string
982Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
983                                                types::ID InputType) const {
984  return ComputeLLVMTriple(Args, InputType);
985}
986
987/// Generic_GCC - A tool chain using the 'gcc' command to perform
988/// all subcommands; this relies on gcc translating the majority of
989/// command line options.
990
991/// \brief Parse a GCCVersion object out of a string of text.
992///
993/// This is the primary means of forming GCCVersion objects.
994/*static*/
995Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
996  const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
997  std::pair<StringRef, StringRef> First = VersionText.split('.');
998  std::pair<StringRef, StringRef> Second = First.second.split('.');
999
1000  GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
1001  if (First.first.getAsInteger(10, GoodVersion.Major) ||
1002      GoodVersion.Major < 0)
1003    return BadVersion;
1004  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1005      GoodVersion.Minor < 0)
1006    return BadVersion;
1007
1008  // First look for a number prefix and parse that if present. Otherwise just
1009  // stash the entire patch string in the suffix, and leave the number
1010  // unspecified. This covers versions strings such as:
1011  //   4.4
1012  //   4.4.0
1013  //   4.4.x
1014  //   4.4.2-rc4
1015  //   4.4.x-patched
1016  // And retains any patch number it finds.
1017  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1018  if (!PatchText.empty()) {
1019    if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
1020      // Try to parse the number and any suffix.
1021      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1022          GoodVersion.Patch < 0)
1023        return BadVersion;
1024      GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
1025    }
1026  }
1027
1028  return GoodVersion;
1029}
1030
1031/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1032bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
1033  if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
1034  if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
1035
1036  // Note that we rank versions with *no* patch specified is better than ones
1037  // hard-coding a patch version. Thus if the RHS has no patch, it always
1038  // wins, and the LHS only wins if it has no patch and the RHS does have
1039  // a patch.
1040  if (RHS.Patch == -1) return true;   if (Patch == -1) return false;
1041  if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
1042  if (PatchSuffix == RHS.PatchSuffix) return false;
1043
1044  // Finally, between completely tied version numbers, the version with the
1045  // suffix loses as we prefer full releases.
1046  if (RHS.PatchSuffix.empty()) return true;
1047  return false;
1048}
1049
1050static StringRef getGCCToolchainDir(const ArgList &Args) {
1051  const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1052  if (A)
1053    return A->getValue();
1054  return GCC_INSTALL_PREFIX;
1055}
1056
1057/// \brief Construct a GCCInstallationDetector from the driver.
1058///
1059/// This performs all of the autodetection and sets up the various paths.
1060/// Once constructed, a GCCInstallationDetector is essentially immutable.
1061///
1062/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1063/// should instead pull the target out of the driver. This is currently
1064/// necessary because the driver doesn't store the final version of the target
1065/// triple.
1066Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
1067    const Driver &D,
1068    const llvm::Triple &TargetTriple,
1069    const ArgList &Args)
1070    : IsValid(false) {
1071  llvm::Triple MultiarchTriple
1072    = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1073                                 : TargetTriple.get32BitArchVariant();
1074  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1075  // The library directories which may contain GCC installations.
1076  SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
1077  // The compatible GCC triples for this particular architecture.
1078  SmallVector<StringRef, 10> CandidateTripleAliases;
1079  SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
1080  CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
1081                           CandidateTripleAliases,
1082                           CandidateMultiarchLibDirs,
1083                           CandidateMultiarchTripleAliases);
1084
1085  // Compute the set of prefixes for our search.
1086  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1087                                       D.PrefixDirs.end());
1088
1089  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1090  if (GCCToolchainDir != "") {
1091    if (GCCToolchainDir.back() == '/')
1092      GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1093
1094    Prefixes.push_back(GCCToolchainDir);
1095  } else {
1096    Prefixes.push_back(D.SysRoot);
1097    Prefixes.push_back(D.SysRoot + "/usr");
1098    Prefixes.push_back(D.InstalledDir + "/..");
1099  }
1100
1101  // Loop over the various components which exist and select the best GCC
1102  // installation available. GCC installs are ranked by version number.
1103  Version = GCCVersion::Parse("0.0.0");
1104  for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1105    if (!llvm::sys::fs::exists(Prefixes[i]))
1106      continue;
1107    for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1108      const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1109      if (!llvm::sys::fs::exists(LibDir))
1110        continue;
1111      for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1112        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1113                               CandidateTripleAliases[k]);
1114    }
1115    for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1116      const std::string LibDir
1117        = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1118      if (!llvm::sys::fs::exists(LibDir))
1119        continue;
1120      for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1121           ++k)
1122        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1123                               CandidateMultiarchTripleAliases[k],
1124                               /*NeedsMultiarchSuffix=*/true);
1125    }
1126  }
1127}
1128
1129/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1130    const llvm::Triple &TargetTriple,
1131    const llvm::Triple &MultiarchTriple,
1132    SmallVectorImpl<StringRef> &LibDirs,
1133    SmallVectorImpl<StringRef> &TripleAliases,
1134    SmallVectorImpl<StringRef> &MultiarchLibDirs,
1135    SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1136  // Declare a bunch of static data sets that we'll select between below. These
1137  // are specifically designed to always refer to string literals to avoid any
1138  // lifetime or initialization issues.
1139  static const char *const ARMLibDirs[] = { "/lib" };
1140  static const char *const ARMTriples[] = {
1141    "arm-linux-gnueabi",
1142    "arm-linux-androideabi"
1143  };
1144  static const char *const ARMHFTriples[] = {
1145    "arm-linux-gnueabihf",
1146  };
1147
1148  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1149  static const char *const X86_64Triples[] = {
1150    "x86_64-linux-gnu",
1151    "x86_64-unknown-linux-gnu",
1152    "x86_64-pc-linux-gnu",
1153    "x86_64-redhat-linux6E",
1154    "x86_64-redhat-linux",
1155    "x86_64-suse-linux",
1156    "x86_64-manbo-linux-gnu",
1157    "x86_64-linux-gnu",
1158    "x86_64-slackware-linux"
1159  };
1160  static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1161  static const char *const X86Triples[] = {
1162    "i686-linux-gnu",
1163    "i686-pc-linux-gnu",
1164    "i486-linux-gnu",
1165    "i386-linux-gnu",
1166    "i686-redhat-linux",
1167    "i586-redhat-linux",
1168    "i386-redhat-linux",
1169    "i586-suse-linux",
1170    "i486-slackware-linux",
1171    "i686-montavista-linux"
1172  };
1173
1174  static const char *const MIPSLibDirs[] = { "/lib" };
1175  static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1176  static const char *const MIPSELLibDirs[] = { "/lib" };
1177  static const char *const MIPSELTriples[] = {
1178    "mipsel-linux-gnu",
1179    "mipsel-linux-android"
1180  };
1181
1182  static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1183  static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1184  static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1185  static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1186
1187  static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1188  static const char *const PPCTriples[] = {
1189    "powerpc-linux-gnu",
1190    "powerpc-unknown-linux-gnu",
1191    "powerpc-suse-linux",
1192    "powerpc-montavista-linuxspe"
1193  };
1194  static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1195  static const char *const PPC64Triples[] = {
1196    "powerpc64-linux-gnu",
1197    "powerpc64-unknown-linux-gnu",
1198    "powerpc64-suse-linux",
1199    "ppc64-redhat-linux"
1200  };
1201
1202  switch (TargetTriple.getArch()) {
1203  case llvm::Triple::arm:
1204  case llvm::Triple::thumb:
1205    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1206    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1207      TripleAliases.append(
1208        ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1209    } else {
1210      TripleAliases.append(
1211        ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1212    }
1213    break;
1214  case llvm::Triple::x86_64:
1215    LibDirs.append(
1216      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1217    TripleAliases.append(
1218      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1219    MultiarchLibDirs.append(
1220      X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1221    MultiarchTripleAliases.append(
1222      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1223    break;
1224  case llvm::Triple::x86:
1225    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1226    TripleAliases.append(
1227      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1228    MultiarchLibDirs.append(
1229      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1230    MultiarchTripleAliases.append(
1231      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1232    break;
1233  case llvm::Triple::mips:
1234    LibDirs.append(
1235      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1236    TripleAliases.append(
1237      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1238    MultiarchLibDirs.append(
1239      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1240    MultiarchTripleAliases.append(
1241      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1242    break;
1243  case llvm::Triple::mipsel:
1244    LibDirs.append(
1245      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1246    TripleAliases.append(
1247      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1248    MultiarchLibDirs.append(
1249      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1250    MultiarchTripleAliases.append(
1251      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1252    break;
1253  case llvm::Triple::mips64:
1254    LibDirs.append(
1255      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1256    TripleAliases.append(
1257      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1258    MultiarchLibDirs.append(
1259      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1260    MultiarchTripleAliases.append(
1261      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1262    break;
1263  case llvm::Triple::mips64el:
1264    LibDirs.append(
1265      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1266    TripleAliases.append(
1267      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1268    MultiarchLibDirs.append(
1269      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1270    MultiarchTripleAliases.append(
1271      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1272    break;
1273  case llvm::Triple::ppc:
1274    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1275    TripleAliases.append(
1276      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1277    MultiarchLibDirs.append(
1278      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1279    MultiarchTripleAliases.append(
1280      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1281    break;
1282  case llvm::Triple::ppc64:
1283    LibDirs.append(
1284      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1285    TripleAliases.append(
1286      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1287    MultiarchLibDirs.append(
1288      PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1289    MultiarchTripleAliases.append(
1290      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1291    break;
1292
1293  default:
1294    // By default, just rely on the standard lib directories and the original
1295    // triple.
1296    break;
1297  }
1298
1299  // Always append the drivers target triple to the end, in case it doesn't
1300  // match any of our aliases.
1301  TripleAliases.push_back(TargetTriple.str());
1302
1303  // Also include the multiarch variant if it's different.
1304  if (TargetTriple.str() != MultiarchTriple.str())
1305    MultiarchTripleAliases.push_back(MultiarchTriple.str());
1306}
1307
1308// FIXME: There is the same routine in the Tools.cpp.
1309static bool hasMipsN32ABIArg(const ArgList &Args) {
1310  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1311  return A && (A->getValue() == StringRef("n32"));
1312}
1313
1314static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
1315                                          const ArgList &Args) {
1316  if (TargetArch == llvm::Triple::x86_64 ||
1317      TargetArch == llvm::Triple::ppc64)
1318    return "/64";
1319
1320  if (TargetArch == llvm::Triple::mips64 ||
1321      TargetArch == llvm::Triple::mips64el) {
1322    if (hasMipsN32ABIArg(Args))
1323      return "/n32";
1324    else
1325      return "/64";
1326  }
1327
1328  return "/32";
1329}
1330
1331void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1332    llvm::Triple::ArchType TargetArch, const ArgList &Args,
1333    const std::string &LibDir,
1334    StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1335  // There are various different suffixes involving the triple we
1336  // check for. We also record what is necessary to walk from each back
1337  // up to the lib directory.
1338  const std::string LibSuffixes[] = {
1339    "/gcc/" + CandidateTriple.str(),
1340    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1341
1342    // The Freescale PPC SDK has the gcc libraries in
1343    // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1344    "/" + CandidateTriple.str(),
1345
1346    // Ubuntu has a strange mis-matched pair of triples that this happens to
1347    // match.
1348    // FIXME: It may be worthwhile to generalize this and look for a second
1349    // triple.
1350    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1351  };
1352  const std::string InstallSuffixes[] = {
1353    "/../../..",
1354    "/../../../..",
1355    "/../..",
1356    "/../../../.."
1357  };
1358  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1359  const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1360                                   (TargetArch != llvm::Triple::x86));
1361  for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1362    StringRef LibSuffix = LibSuffixes[i];
1363    llvm::error_code EC;
1364    for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1365         !EC && LI != LE; LI = LI.increment(EC)) {
1366      StringRef VersionText = llvm::sys::path::filename(LI->path());
1367      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1368      static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1369      if (CandidateVersion < MinVersion)
1370        continue;
1371      if (CandidateVersion <= Version)
1372        continue;
1373
1374      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1375      // in what would normally be GCCInstallPath and put the 64-bit
1376      // libs in a subdirectory named 64. The simple logic we follow is that
1377      // *if* there is a subdirectory of the right name with crtbegin.o in it,
1378      // we use that. If not, and if not a multiarch triple, we look for
1379      // crtbegin.o without the subdirectory.
1380      StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
1381      if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1382        GCCMultiarchSuffix = MultiarchSuffix.str();
1383      } else {
1384        if (NeedsMultiarchSuffix ||
1385            !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1386          continue;
1387        GCCMultiarchSuffix.clear();
1388      }
1389
1390      Version = CandidateVersion;
1391      GCCTriple.setTriple(CandidateTriple);
1392      // FIXME: We hack together the directory name here instead of
1393      // using LI to ensure stable path separators across Windows and
1394      // Linux.
1395      GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1396      GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1397      IsValid = true;
1398    }
1399  }
1400}
1401
1402Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1403                         const ArgList &Args)
1404  : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
1405  getProgramPaths().push_back(getDriver().getInstalledDir());
1406  if (getDriver().getInstalledDir() != getDriver().Dir)
1407    getProgramPaths().push_back(getDriver().Dir);
1408}
1409
1410Generic_GCC::~Generic_GCC() {
1411  // Free tool implementations.
1412  for (llvm::DenseMap<unsigned, Tool*>::iterator
1413         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1414    delete it->second;
1415}
1416
1417Tool &Generic_GCC::SelectTool(const Compilation &C,
1418                              const JobAction &JA,
1419                              const ActionList &Inputs) const {
1420  Action::ActionClass Key = JA.getKind();
1421
1422  Tool *&T = Tools[Key];
1423  if (!T) {
1424    switch (Key) {
1425    case Action::InputClass:
1426    case Action::BindArchClass:
1427      llvm_unreachable("Invalid tool kind.");
1428    case Action::PreprocessJobClass:
1429    case Action::PrecompileJobClass:
1430    case Action::AnalyzeJobClass:
1431    case Action::MigrateJobClass:
1432    case Action::CompileJobClass:
1433      T = new tools::Clang(*this); break;
1434    case Action::AssembleJobClass:
1435      T = new tools::gcc::Assemble(*this); break;
1436    case Action::LinkJobClass:
1437      T = new tools::gcc::Link(*this); break;
1438
1439      // This is a bit ungeneric, but the only platform using a driver
1440      // driver is Darwin.
1441    case Action::LipoJobClass:
1442      T = new tools::darwin::Lipo(*this); break;
1443    case Action::DsymutilJobClass:
1444      T = new tools::darwin::Dsymutil(*this); break;
1445    case Action::VerifyJobClass:
1446      T = new tools::darwin::VerifyDebug(*this); break;
1447    }
1448  }
1449
1450  return *T;
1451}
1452
1453bool Generic_GCC::IsUnwindTablesDefault() const {
1454  return getArch() == llvm::Triple::x86_64;
1455}
1456
1457const char *Generic_GCC::GetDefaultRelocationModel() const {
1458  return "static";
1459}
1460
1461const char *Generic_GCC::GetForcedPicModel() const {
1462  return 0;
1463}
1464/// Hexagon Toolchain
1465
1466Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
1467  : ToolChain(D, Triple) {
1468  getProgramPaths().push_back(getDriver().getInstalledDir());
1469  if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
1470    getProgramPaths().push_back(getDriver().Dir);
1471}
1472
1473Hexagon_TC::~Hexagon_TC() {
1474  // Free tool implementations.
1475  for (llvm::DenseMap<unsigned, Tool*>::iterator
1476         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1477    delete it->second;
1478}
1479
1480Tool &Hexagon_TC::SelectTool(const Compilation &C,
1481                             const JobAction &JA,
1482                             const ActionList &Inputs) const {
1483  Action::ActionClass Key = JA.getKind();
1484  Tool *&T = Tools[Key];
1485  if (!T) {
1486    switch (Key) {
1487    case Action::InputClass:
1488    case Action::BindArchClass:
1489      assert(0 && "Invalid tool kind.");
1490    case Action::PreprocessJobClass:
1491    case Action::PrecompileJobClass:
1492    case Action::AnalyzeJobClass:
1493    case Action::MigrateJobClass:
1494    case Action::CompileJobClass:
1495      T = new tools::Clang(*this); break;
1496    case Action::AssembleJobClass:
1497      T = new tools::hexagon::Assemble(*this); break;
1498    case Action::LinkJobClass:
1499      T = new tools::hexagon::Link(*this); break;
1500    default:
1501      assert(false && "Unsupported action for Hexagon target.");
1502    }
1503  }
1504
1505  return *T;
1506}
1507
1508const char *Hexagon_TC::GetDefaultRelocationModel() const {
1509  return "static";
1510}
1511
1512const char *Hexagon_TC::GetForcedPicModel() const {
1513  return 0;
1514} // End Hexagon
1515
1516
1517/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1518/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1519/// Currently does not support anything else but compilation.
1520
1521TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
1522  : ToolChain(D, Triple) {
1523  // Path mangling to find libexec
1524  std::string Path(getDriver().Dir);
1525
1526  Path += "/../libexec";
1527  getProgramPaths().push_back(Path);
1528}
1529
1530TCEToolChain::~TCEToolChain() {
1531  for (llvm::DenseMap<unsigned, Tool*>::iterator
1532           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1533      delete it->second;
1534}
1535
1536bool TCEToolChain::IsMathErrnoDefault() const {
1537  return true;
1538}
1539
1540const char *TCEToolChain::GetDefaultRelocationModel() const {
1541  return "static";
1542}
1543
1544const char *TCEToolChain::GetForcedPicModel() const {
1545  return 0;
1546}
1547
1548Tool &TCEToolChain::SelectTool(const Compilation &C,
1549                            const JobAction &JA,
1550                               const ActionList &Inputs) const {
1551  Action::ActionClass Key;
1552  Key = Action::AnalyzeJobClass;
1553
1554  Tool *&T = Tools[Key];
1555  if (!T) {
1556    switch (Key) {
1557    case Action::PreprocessJobClass:
1558      T = new tools::gcc::Preprocess(*this); break;
1559    case Action::AnalyzeJobClass:
1560      T = new tools::Clang(*this); break;
1561    default:
1562     llvm_unreachable("Unsupported action for TCE target.");
1563    }
1564  }
1565  return *T;
1566}
1567
1568/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1569
1570OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1571  : Generic_ELF(D, Triple, Args) {
1572  getFilePaths().push_back(getDriver().Dir + "/../lib");
1573  getFilePaths().push_back("/usr/lib");
1574}
1575
1576Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1577                          const ActionList &Inputs) const {
1578  Action::ActionClass Key = JA.getKind();
1579  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1580                                             options::OPT_no_integrated_as,
1581                                             IsIntegratedAssemblerDefault());
1582
1583  Tool *&T = Tools[Key];
1584  if (!T) {
1585    switch (Key) {
1586    case Action::AssembleJobClass: {
1587      if (UseIntegratedAs)
1588        T = new tools::ClangAs(*this);
1589      else
1590        T = new tools::openbsd::Assemble(*this);
1591      break;
1592    }
1593    case Action::LinkJobClass:
1594      T = new tools::openbsd::Link(*this); break;
1595    default:
1596      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1597    }
1598  }
1599
1600  return *T;
1601}
1602
1603/// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1604
1605Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1606  : Generic_ELF(D, Triple, Args) {
1607  getFilePaths().push_back(getDriver().Dir + "/../lib");
1608  getFilePaths().push_back("/usr/lib");
1609}
1610
1611Tool &Bitrig::SelectTool(const Compilation &C, const JobAction &JA,
1612                         const ActionList &Inputs) const {
1613  Action::ActionClass Key = JA.getKind();
1614  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1615                                             options::OPT_no_integrated_as,
1616                                             IsIntegratedAssemblerDefault());
1617
1618  Tool *&T = Tools[Key];
1619  if (!T) {
1620    switch (Key) {
1621    case Action::AssembleJobClass: {
1622      if (UseIntegratedAs)
1623        T = new tools::ClangAs(*this);
1624      else
1625        T = new tools::bitrig::Assemble(*this);
1626      break;
1627    }
1628    case Action::LinkJobClass:
1629      T = new tools::bitrig::Link(*this); break;
1630    default:
1631      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1632    }
1633  }
1634
1635  return *T;
1636}
1637
1638void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1639                                          ArgStringList &CC1Args) const {
1640  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1641      DriverArgs.hasArg(options::OPT_nostdincxx))
1642    return;
1643
1644  switch (GetCXXStdlibType(DriverArgs)) {
1645  case ToolChain::CST_Libcxx:
1646    addSystemInclude(DriverArgs, CC1Args,
1647                     getDriver().SysRoot + "/usr/include/c++/");
1648    break;
1649  case ToolChain::CST_Libstdcxx:
1650    addSystemInclude(DriverArgs, CC1Args,
1651                     getDriver().SysRoot + "/usr/include/c++/stdc++");
1652    addSystemInclude(DriverArgs, CC1Args,
1653                     getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1654
1655    StringRef Triple = getTriple().str();
1656    if (Triple.startswith("amd64"))
1657      addSystemInclude(DriverArgs, CC1Args,
1658                       getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1659                       Triple.substr(5));
1660    else
1661      addSystemInclude(DriverArgs, CC1Args,
1662                       getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1663                       Triple);
1664    break;
1665  }
1666}
1667
1668void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1669                                 ArgStringList &CmdArgs) const {
1670  switch (GetCXXStdlibType(Args)) {
1671  case ToolChain::CST_Libcxx:
1672    CmdArgs.push_back("-lc++");
1673    CmdArgs.push_back("-lcxxrt");
1674    // Include supc++ to provide Unwind until provided by libcxx.
1675    CmdArgs.push_back("-lgcc");
1676    break;
1677  case ToolChain::CST_Libstdcxx:
1678    CmdArgs.push_back("-lstdc++");
1679    break;
1680  }
1681}
1682
1683/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1684
1685FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1686  : Generic_ELF(D, Triple, Args) {
1687
1688  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1689  // back to '/usr/lib' if it doesn't exist.
1690  if ((Triple.getArch() == llvm::Triple::x86 ||
1691       Triple.getArch() == llvm::Triple::ppc) &&
1692      llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1693    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1694  else
1695    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1696}
1697
1698Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1699                          const ActionList &Inputs) const {
1700  Action::ActionClass Key = JA.getKind();
1701  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1702                                             options::OPT_no_integrated_as,
1703                                             IsIntegratedAssemblerDefault());
1704
1705  Tool *&T = Tools[Key];
1706  if (!T) {
1707    switch (Key) {
1708    case Action::AssembleJobClass:
1709      if (UseIntegratedAs)
1710        T = new tools::ClangAs(*this);
1711      else
1712        T = new tools::freebsd::Assemble(*this);
1713      break;
1714    case Action::LinkJobClass:
1715      T = new tools::freebsd::Link(*this); break;
1716    default:
1717      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1718    }
1719  }
1720
1721  return *T;
1722}
1723
1724/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1725
1726NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1727  : Generic_ELF(D, Triple, Args) {
1728
1729  if (getDriver().UseStdLib) {
1730    // When targeting a 32-bit platform, try the special directory used on
1731    // 64-bit hosts, and only fall back to the main library directory if that
1732    // doesn't work.
1733    // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1734    // what all logic is needed to emulate the '=' prefix here.
1735    if (Triple.getArch() == llvm::Triple::x86)
1736      getFilePaths().push_back("=/usr/lib/i386");
1737
1738    getFilePaths().push_back("=/usr/lib");
1739  }
1740}
1741
1742Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1743                         const ActionList &Inputs) const {
1744  Action::ActionClass Key = JA.getKind();
1745  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1746                                             options::OPT_no_integrated_as,
1747                                             IsIntegratedAssemblerDefault());
1748
1749  Tool *&T = Tools[Key];
1750  if (!T) {
1751    switch (Key) {
1752    case Action::AssembleJobClass:
1753      if (UseIntegratedAs)
1754        T = new tools::ClangAs(*this);
1755      else
1756        T = new tools::netbsd::Assemble(*this);
1757      break;
1758    case Action::LinkJobClass:
1759      T = new tools::netbsd::Link(*this);
1760      break;
1761    default:
1762      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1763    }
1764  }
1765
1766  return *T;
1767}
1768
1769/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1770
1771Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1772  : Generic_ELF(D, Triple, Args) {
1773  getFilePaths().push_back(getDriver().Dir + "/../lib");
1774  getFilePaths().push_back("/usr/lib");
1775}
1776
1777Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1778                        const ActionList &Inputs) const {
1779  Action::ActionClass Key = JA.getKind();
1780
1781  Tool *&T = Tools[Key];
1782  if (!T) {
1783    switch (Key) {
1784    case Action::AssembleJobClass:
1785      T = new tools::minix::Assemble(*this); break;
1786    case Action::LinkJobClass:
1787      T = new tools::minix::Link(*this); break;
1788    default:
1789      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1790    }
1791  }
1792
1793  return *T;
1794}
1795
1796/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1797
1798AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1799                   const ArgList &Args)
1800  : Generic_GCC(D, Triple, Args) {
1801
1802  getProgramPaths().push_back(getDriver().getInstalledDir());
1803  if (getDriver().getInstalledDir() != getDriver().Dir)
1804    getProgramPaths().push_back(getDriver().Dir);
1805
1806  getFilePaths().push_back(getDriver().Dir + "/../lib");
1807  getFilePaths().push_back("/usr/lib");
1808  getFilePaths().push_back("/usr/sfw/lib");
1809  getFilePaths().push_back("/opt/gcc4/lib");
1810  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1811
1812}
1813
1814Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1815                           const ActionList &Inputs) const {
1816  Action::ActionClass Key = JA.getKind();
1817
1818  Tool *&T = Tools[Key];
1819  if (!T) {
1820    switch (Key) {
1821    case Action::AssembleJobClass:
1822      T = new tools::auroraux::Assemble(*this); break;
1823    case Action::LinkJobClass:
1824      T = new tools::auroraux::Link(*this); break;
1825    default:
1826      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1827    }
1828  }
1829
1830  return *T;
1831}
1832
1833/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1834
1835Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1836                 const ArgList &Args)
1837  : Generic_GCC(D, Triple, Args) {
1838
1839  getProgramPaths().push_back(getDriver().getInstalledDir());
1840  if (getDriver().getInstalledDir() != getDriver().Dir)
1841    getProgramPaths().push_back(getDriver().Dir);
1842
1843  getFilePaths().push_back(getDriver().Dir + "/../lib");
1844  getFilePaths().push_back("/usr/lib");
1845}
1846
1847Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
1848                           const ActionList &Inputs) const {
1849  Action::ActionClass Key = JA.getKind();
1850
1851  Tool *&T = Tools[Key];
1852  if (!T) {
1853    switch (Key) {
1854    case Action::AssembleJobClass:
1855      T = new tools::solaris::Assemble(*this); break;
1856    case Action::LinkJobClass:
1857      T = new tools::solaris::Link(*this); break;
1858    default:
1859      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1860    }
1861  }
1862
1863  return *T;
1864}
1865
1866/// Linux toolchain (very bare-bones at the moment).
1867
1868enum LinuxDistro {
1869  ArchLinux,
1870  DebianLenny,
1871  DebianSqueeze,
1872  DebianWheezy,
1873  Exherbo,
1874  RHEL4,
1875  RHEL5,
1876  RHEL6,
1877  Fedora13,
1878  Fedora14,
1879  Fedora15,
1880  Fedora16,
1881  FedoraRawhide,
1882  OpenSuse11_3,
1883  OpenSuse11_4,
1884  OpenSuse12_1,
1885  OpenSuse12_2,
1886  UbuntuHardy,
1887  UbuntuIntrepid,
1888  UbuntuJaunty,
1889  UbuntuKarmic,
1890  UbuntuLucid,
1891  UbuntuMaverick,
1892  UbuntuNatty,
1893  UbuntuOneiric,
1894  UbuntuPrecise,
1895  UnknownDistro
1896};
1897
1898static bool IsRedhat(enum LinuxDistro Distro) {
1899  return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1900         (Distro >= RHEL4    && Distro <= RHEL6);
1901}
1902
1903static bool IsOpenSuse(enum LinuxDistro Distro) {
1904  return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
1905}
1906
1907static bool IsDebian(enum LinuxDistro Distro) {
1908  return Distro >= DebianLenny && Distro <= DebianWheezy;
1909}
1910
1911static bool IsUbuntu(enum LinuxDistro Distro) {
1912  return Distro >= UbuntuHardy && Distro <= UbuntuPrecise;
1913}
1914
1915static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1916  OwningPtr<llvm::MemoryBuffer> File;
1917  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1918    StringRef Data = File.get()->getBuffer();
1919    SmallVector<StringRef, 8> Lines;
1920    Data.split(Lines, "\n");
1921    LinuxDistro Version = UnknownDistro;
1922    for (unsigned i = 0, s = Lines.size(); i != s; ++i)
1923      if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
1924        Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
1925          .Case("hardy", UbuntuHardy)
1926          .Case("intrepid", UbuntuIntrepid)
1927          .Case("jaunty", UbuntuJaunty)
1928          .Case("karmic", UbuntuKarmic)
1929          .Case("lucid", UbuntuLucid)
1930          .Case("maverick", UbuntuMaverick)
1931          .Case("natty", UbuntuNatty)
1932          .Case("oneiric", UbuntuOneiric)
1933          .Case("precise", UbuntuPrecise)
1934          .Default(UnknownDistro);
1935    return Version;
1936  }
1937
1938  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1939    StringRef Data = File.get()->getBuffer();
1940    if (Data.startswith("Fedora release 16"))
1941      return Fedora16;
1942    else if (Data.startswith("Fedora release 15"))
1943      return Fedora15;
1944    else if (Data.startswith("Fedora release 14"))
1945      return Fedora14;
1946    else if (Data.startswith("Fedora release 13"))
1947      return Fedora13;
1948    else if (Data.startswith("Fedora release") &&
1949             Data.find("Rawhide") != StringRef::npos)
1950      return FedoraRawhide;
1951    else if (Data.startswith("Red Hat Enterprise Linux") &&
1952             Data.find("release 6") != StringRef::npos)
1953      return RHEL6;
1954    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1955	      Data.startswith("CentOS")) &&
1956             Data.find("release 5") != StringRef::npos)
1957      return RHEL5;
1958    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1959	      Data.startswith("CentOS")) &&
1960             Data.find("release 4") != StringRef::npos)
1961      return RHEL4;
1962    return UnknownDistro;
1963  }
1964
1965  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1966    StringRef Data = File.get()->getBuffer();
1967    if (Data[0] == '5')
1968      return DebianLenny;
1969    else if (Data.startswith("squeeze/sid") || Data[0] == '6')
1970      return DebianSqueeze;
1971    else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
1972      return DebianWheezy;
1973    return UnknownDistro;
1974  }
1975
1976  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
1977    return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
1978      .StartsWith("openSUSE 11.3", OpenSuse11_3)
1979      .StartsWith("openSUSE 11.4", OpenSuse11_4)
1980      .StartsWith("openSUSE 12.1", OpenSuse12_1)
1981      .StartsWith("openSUSE 12.2", OpenSuse12_2)
1982      .Default(UnknownDistro);
1983
1984  bool Exists;
1985  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1986    return Exherbo;
1987
1988  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1989    return ArchLinux;
1990
1991  return UnknownDistro;
1992}
1993
1994/// \brief Get our best guess at the multiarch triple for a target.
1995///
1996/// Debian-based systems are starting to use a multiarch setup where they use
1997/// a target-triple directory in the library and header search paths.
1998/// Unfortunately, this triple does not align with the vanilla target triple,
1999/// so we provide a rough mapping here.
2000static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2001                                      StringRef SysRoot) {
2002  // For most architectures, just use whatever we have rather than trying to be
2003  // clever.
2004  switch (TargetTriple.getArch()) {
2005  default:
2006    return TargetTriple.str();
2007
2008    // We use the existence of '/lib/<triple>' as a directory to detect some
2009    // common linux triples that don't quite match the Clang triple for both
2010    // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2011    // regardless of what the actual target triple is.
2012  case llvm::Triple::arm:
2013  case llvm::Triple::thumb:
2014    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2015      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2016        return "arm-linux-gnueabihf";
2017    } else {
2018      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2019        return "arm-linux-gnueabi";
2020    }
2021    return TargetTriple.str();
2022  case llvm::Triple::x86:
2023    if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2024      return "i386-linux-gnu";
2025    return TargetTriple.str();
2026  case llvm::Triple::x86_64:
2027    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2028      return "x86_64-linux-gnu";
2029    return TargetTriple.str();
2030  case llvm::Triple::mips:
2031    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2032      return "mips-linux-gnu";
2033    return TargetTriple.str();
2034  case llvm::Triple::mipsel:
2035    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2036      return "mipsel-linux-gnu";
2037    return TargetTriple.str();
2038  case llvm::Triple::ppc:
2039    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2040      return "powerpc-linux-gnu";
2041    return TargetTriple.str();
2042  case llvm::Triple::ppc64:
2043    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2044      return "powerpc64-linux-gnu";
2045    return TargetTriple.str();
2046  }
2047}
2048
2049static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2050  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2051}
2052
2053static bool isMipsArch(llvm::Triple::ArchType Arch) {
2054  return Arch == llvm::Triple::mips ||
2055         Arch == llvm::Triple::mipsel ||
2056         Arch == llvm::Triple::mips64 ||
2057         Arch == llvm::Triple::mips64el;
2058}
2059
2060static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2061                         const ArgList &Args) {
2062  if (Arch != llvm::Triple::mips &&
2063      Arch != llvm::Triple::mipsel)
2064    return false;
2065
2066  Arg *A = Args.getLastArg(options::OPT_march_EQ,
2067                           options::OPT_mcpu_EQ,
2068                           options::OPT_mips_CPUs_Group);
2069
2070  if (!A)
2071    return false;
2072
2073  if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2074    return A->getOption().matches(options::OPT_mips32r2);
2075
2076  return A->getValue() == StringRef("mips32r2");
2077}
2078
2079static StringRef getMultilibDir(const llvm::Triple &Triple,
2080                                const ArgList &Args) {
2081  if (!isMipsArch(Triple.getArch()))
2082    return Triple.isArch32Bit() ? "lib32" : "lib64";
2083
2084  // lib32 directory has a special meaning on MIPS targets.
2085  // It contains N32 ABI binaries. Use this folder if produce
2086  // code for N32 ABI only.
2087  if (hasMipsN32ABIArg(Args))
2088    return "lib32";
2089
2090  return Triple.isArch32Bit() ? "lib" : "lib64";
2091}
2092
2093Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2094  : Generic_ELF(D, Triple, Args) {
2095  llvm::Triple::ArchType Arch = Triple.getArch();
2096  const std::string &SysRoot = getDriver().SysRoot;
2097
2098  // OpenSuse stores the linker with the compiler, add that to the search
2099  // path.
2100  ToolChain::path_list &PPaths = getProgramPaths();
2101  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2102                         GCCInstallation.getTriple().str() + "/bin").str());
2103
2104  Linker = GetProgramPath("ld");
2105
2106  LinuxDistro Distro = DetectLinuxDistro(Arch);
2107
2108  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2109    ExtraOpts.push_back("-z");
2110    ExtraOpts.push_back("relro");
2111  }
2112
2113  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2114    ExtraOpts.push_back("-X");
2115
2116  const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2117
2118  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2119  // and the MIPS ABI require .dynsym to be sorted in different ways.
2120  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2121  // ABI requires a mapping between the GOT and the symbol table.
2122  // Android loader does not support .gnu.hash.
2123  if (!isMipsArch(Arch) && !IsAndroid) {
2124    if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2125        (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2126      ExtraOpts.push_back("--hash-style=gnu");
2127
2128    if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2129        Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2130      ExtraOpts.push_back("--hash-style=both");
2131  }
2132
2133  if (IsRedhat(Distro))
2134    ExtraOpts.push_back("--no-add-needed");
2135
2136  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2137      IsOpenSuse(Distro) ||
2138      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2139      (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2140    ExtraOpts.push_back("--build-id");
2141
2142  if (IsOpenSuse(Distro))
2143    ExtraOpts.push_back("--enable-new-dtags");
2144
2145  // The selection of paths to try here is designed to match the patterns which
2146  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2147  // This was determined by running GCC in a fake filesystem, creating all
2148  // possible permutations of these directories, and seeing which ones it added
2149  // to the link paths.
2150  path_list &Paths = getFilePaths();
2151
2152  const std::string Multilib = getMultilibDir(Triple, Args);
2153  const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2154
2155  // Add the multilib suffixed paths where they are available.
2156  if (GCCInstallation.isValid()) {
2157    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2158    const std::string &LibPath = GCCInstallation.getParentLibPath();
2159
2160    if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2161      addPathIfExists(GCCInstallation.getInstallPath() +
2162                      GCCInstallation.getMultiarchSuffix() +
2163                      "/mips-r2",
2164                      Paths);
2165    else
2166      addPathIfExists((GCCInstallation.getInstallPath() +
2167                       GCCInstallation.getMultiarchSuffix()),
2168                      Paths);
2169
2170    // If the GCC installation we found is inside of the sysroot, we want to
2171    // prefer libraries installed in the parent prefix of the GCC installation.
2172    // It is important to *not* use these paths when the GCC installation is
2173    // outside of the system root as that can pick up unintended libraries.
2174    // This usually happens when there is an external cross compiler on the
2175    // host system, and a more minimal sysroot available that is the target of
2176    // the cross.
2177    if (StringRef(LibPath).startswith(SysRoot)) {
2178      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2179                      Paths);
2180      addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2181      addPathIfExists(LibPath + "/../" + Multilib, Paths);
2182    }
2183    // On Android, libraries in the parent prefix of the GCC installation are
2184    // preferred to the ones under sysroot.
2185    if (IsAndroid) {
2186      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2187    }
2188  }
2189  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2190  addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2191  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2192  addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2193
2194  // Try walking via the GCC triple path in case of multiarch GCC
2195  // installations with strange symlinks.
2196  if (GCCInstallation.isValid())
2197    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2198                    "/../../" + Multilib, Paths);
2199
2200  // Add the non-multilib suffixed paths (if potentially different).
2201  if (GCCInstallation.isValid()) {
2202    const std::string &LibPath = GCCInstallation.getParentLibPath();
2203    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2204    if (!GCCInstallation.getMultiarchSuffix().empty())
2205      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2206
2207    if (StringRef(LibPath).startswith(SysRoot)) {
2208      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2209      addPathIfExists(LibPath, Paths);
2210    }
2211  }
2212  addPathIfExists(SysRoot + "/lib", Paths);
2213  addPathIfExists(SysRoot + "/usr/lib", Paths);
2214}
2215
2216bool Linux::HasNativeLLVMSupport() const {
2217  return true;
2218}
2219
2220Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
2221                        const ActionList &Inputs) const {
2222  Action::ActionClass Key = JA.getKind();
2223  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2224                                             options::OPT_no_integrated_as,
2225                                             IsIntegratedAssemblerDefault());
2226
2227  Tool *&T = Tools[Key];
2228  if (!T) {
2229    switch (Key) {
2230    case Action::AssembleJobClass:
2231      if (UseIntegratedAs)
2232        T = new tools::ClangAs(*this);
2233      else
2234        T = new tools::linuxtools::Assemble(*this);
2235      break;
2236    case Action::LinkJobClass:
2237      T = new tools::linuxtools::Link(*this); break;
2238    default:
2239      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2240    }
2241  }
2242
2243  return *T;
2244}
2245
2246void Linux::addClangTargetOptions(ArgStringList &CC1Args) const {
2247  const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2248  if (V >= Generic_GCC::GCCVersion::Parse("4.7.0"))
2249    CC1Args.push_back("-fuse-init-array");
2250}
2251
2252void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2253                                      ArgStringList &CC1Args) const {
2254  const Driver &D = getDriver();
2255
2256  if (DriverArgs.hasArg(options::OPT_nostdinc))
2257    return;
2258
2259  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2260    addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2261
2262  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2263    llvm::sys::Path P(D.ResourceDir);
2264    P.appendComponent("include");
2265    addSystemInclude(DriverArgs, CC1Args, P.str());
2266  }
2267
2268  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2269    return;
2270
2271  // Check for configure-time C include directories.
2272  StringRef CIncludeDirs(C_INCLUDE_DIRS);
2273  if (CIncludeDirs != "") {
2274    SmallVector<StringRef, 5> dirs;
2275    CIncludeDirs.split(dirs, ":");
2276    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2277         I != E; ++I) {
2278      StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2279      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2280    }
2281    return;
2282  }
2283
2284  // Lacking those, try to detect the correct set of system includes for the
2285  // target triple.
2286
2287  // Implement generic Debian multiarch support.
2288  const StringRef X86_64MultiarchIncludeDirs[] = {
2289    "/usr/include/x86_64-linux-gnu",
2290
2291    // FIXME: These are older forms of multiarch. It's not clear that they're
2292    // in use in any released version of Debian, so we should consider
2293    // removing them.
2294    "/usr/include/i686-linux-gnu/64",
2295    "/usr/include/i486-linux-gnu/64"
2296  };
2297  const StringRef X86MultiarchIncludeDirs[] = {
2298    "/usr/include/i386-linux-gnu",
2299
2300    // FIXME: These are older forms of multiarch. It's not clear that they're
2301    // in use in any released version of Debian, so we should consider
2302    // removing them.
2303    "/usr/include/x86_64-linux-gnu/32",
2304    "/usr/include/i686-linux-gnu",
2305    "/usr/include/i486-linux-gnu"
2306  };
2307  const StringRef ARMMultiarchIncludeDirs[] = {
2308    "/usr/include/arm-linux-gnueabi"
2309  };
2310  const StringRef ARMHFMultiarchIncludeDirs[] = {
2311    "/usr/include/arm-linux-gnueabihf"
2312  };
2313  const StringRef MIPSMultiarchIncludeDirs[] = {
2314    "/usr/include/mips-linux-gnu"
2315  };
2316  const StringRef MIPSELMultiarchIncludeDirs[] = {
2317    "/usr/include/mipsel-linux-gnu"
2318  };
2319  const StringRef PPCMultiarchIncludeDirs[] = {
2320    "/usr/include/powerpc-linux-gnu"
2321  };
2322  const StringRef PPC64MultiarchIncludeDirs[] = {
2323    "/usr/include/powerpc64-linux-gnu"
2324  };
2325  ArrayRef<StringRef> MultiarchIncludeDirs;
2326  if (getTriple().getArch() == llvm::Triple::x86_64) {
2327    MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2328  } else if (getTriple().getArch() == llvm::Triple::x86) {
2329    MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2330  } else if (getTriple().getArch() == llvm::Triple::arm) {
2331    if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2332      MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2333    else
2334      MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2335  } else if (getTriple().getArch() == llvm::Triple::mips) {
2336    MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2337  } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2338    MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2339  } else if (getTriple().getArch() == llvm::Triple::ppc) {
2340    MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2341  } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2342    MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2343  }
2344  for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2345                                     E = MultiarchIncludeDirs.end();
2346       I != E; ++I) {
2347    if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2348      addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2349      break;
2350    }
2351  }
2352
2353  if (getTriple().getOS() == llvm::Triple::RTEMS)
2354    return;
2355
2356  // Add an include of '/include' directly. This isn't provided by default by
2357  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2358  // add even when Clang is acting as-if it were a system compiler.
2359  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2360
2361  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2362}
2363
2364/// \brief Helper to add the thre variant paths for a libstdc++ installation.
2365/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2366                                                const ArgList &DriverArgs,
2367                                                ArgStringList &CC1Args) {
2368  if (!llvm::sys::fs::exists(Base))
2369    return false;
2370  addSystemInclude(DriverArgs, CC1Args, Base);
2371  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2372  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2373  return true;
2374}
2375
2376void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2377                                         ArgStringList &CC1Args) const {
2378  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2379      DriverArgs.hasArg(options::OPT_nostdincxx))
2380    return;
2381
2382  // Check if libc++ has been enabled and provide its include paths if so.
2383  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2384    // libc++ is always installed at a fixed path on Linux currently.
2385    addSystemInclude(DriverArgs, CC1Args,
2386                     getDriver().SysRoot + "/usr/include/c++/v1");
2387    return;
2388  }
2389
2390  // We need a detected GCC installation on Linux to provide libstdc++'s
2391  // headers. We handled the libc++ case above.
2392  if (!GCCInstallation.isValid())
2393    return;
2394
2395  // By default, look for the C++ headers in an include directory adjacent to
2396  // the lib directory of the GCC installation. Note that this is expect to be
2397  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2398  StringRef LibDir = GCCInstallation.getParentLibPath();
2399  StringRef InstallDir = GCCInstallation.getInstallPath();
2400  StringRef Version = GCCInstallation.getVersion().Text;
2401  StringRef TripleStr = GCCInstallation.getTriple().str();
2402
2403  const std::string IncludePathCandidates[] = {
2404    LibDir.str() + "/../include/c++/" + Version.str(),
2405    // Gentoo is weird and places its headers inside the GCC install, so if the
2406    // first attempt to find the headers fails, try this pattern.
2407    InstallDir.str() + "/include/g++-v4",
2408    // Android standalone toolchain has C++ headers in yet another place.
2409    LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2410    // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2411    // without a subdirectory corresponding to the gcc version.
2412    LibDir.str() + "/../include/c++",
2413  };
2414
2415  for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2416    if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2417                GCCInstallation.getMultiarchSuffix()),
2418            DriverArgs, CC1Args))
2419      break;
2420  }
2421}
2422
2423/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2424
2425DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2426  : Generic_ELF(D, Triple, Args) {
2427
2428  // Path mangling to find libexec
2429  getProgramPaths().push_back(getDriver().getInstalledDir());
2430  if (getDriver().getInstalledDir() != getDriver().Dir)
2431    getProgramPaths().push_back(getDriver().Dir);
2432
2433  getFilePaths().push_back(getDriver().Dir + "/../lib");
2434  getFilePaths().push_back("/usr/lib");
2435  getFilePaths().push_back("/usr/lib/gcc41");
2436}
2437
2438Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
2439                            const ActionList &Inputs) const {
2440  Action::ActionClass Key = JA.getKind();
2441
2442  Tool *&T = Tools[Key];
2443  if (!T) {
2444    switch (Key) {
2445    case Action::AssembleJobClass:
2446      T = new tools::dragonfly::Assemble(*this); break;
2447    case Action::LinkJobClass:
2448      T = new tools::dragonfly::Link(*this); break;
2449    default:
2450      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2451    }
2452  }
2453
2454  return *T;
2455}
2456