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