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