ToolChains.cpp revision f2f3ce54fc1235bec2d0d0b0ef3b53bdff6d9655
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      //
717      // FIXME: Canonicalize name.
718      StringRef XarchArch = A->getValue(Args, 0);
719      if (!(XarchArch == getArchName()  ||
720            (BoundArch && XarchArch == 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  // FIXME: Gross; we should probably have some separate target
959  // definition, possibly even reusing the one in clang.
960  return getArchName() == "x86_64";
961}
962
963bool Darwin::UseDwarfDebugFlags() const {
964  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
965    return S[0] != '\0';
966  return false;
967}
968
969bool Darwin::UseSjLjExceptions() const {
970  // Darwin uses SjLj exceptions on ARM.
971  return (getTriple().getArch() == llvm::Triple::arm ||
972          getTriple().getArch() == llvm::Triple::thumb);
973}
974
975const char *Darwin::GetDefaultRelocationModel() const {
976  return "pic";
977}
978
979const char *Darwin::GetForcedPicModel() const {
980  if (getArchName() == "x86_64")
981    return "pic";
982  return 0;
983}
984
985bool Darwin::SupportsProfiling() const {
986  // Profiling instrumentation is only supported on x86.
987  return getArchName() == "i386" || getArchName() == "x86_64";
988}
989
990bool Darwin::SupportsObjCGC() const {
991  // Garbage collection is supported everywhere except on iPhone OS.
992  return !isTargetIPhoneOS();
993}
994
995void Darwin::CheckObjCARC() const {
996  if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
997    return;
998  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
999}
1000
1001std::string
1002Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
1003                                                types::ID InputType) const {
1004  return ComputeLLVMTriple(Args, InputType);
1005}
1006
1007/// Generic_GCC - A tool chain using the 'gcc' command to perform
1008/// all subcommands; this relies on gcc translating the majority of
1009/// command line options.
1010
1011/// \brief Parse a GCCVersion object out of a string of text.
1012///
1013/// This is the primary means of forming GCCVersion objects.
1014/*static*/
1015Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1016  const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
1017  std::pair<StringRef, StringRef> First = VersionText.split('.');
1018  std::pair<StringRef, StringRef> Second = First.second.split('.');
1019
1020  GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
1021  if (First.first.getAsInteger(10, GoodVersion.Major) ||
1022      GoodVersion.Major < 0)
1023    return BadVersion;
1024  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1025      GoodVersion.Minor < 0)
1026    return BadVersion;
1027
1028  // First look for a number prefix and parse that if present. Otherwise just
1029  // stash the entire patch string in the suffix, and leave the number
1030  // unspecified. This covers versions strings such as:
1031  //   4.4
1032  //   4.4.0
1033  //   4.4.x
1034  //   4.4.2-rc4
1035  //   4.4.x-patched
1036  // And retains any patch number it finds.
1037  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1038  if (!PatchText.empty()) {
1039    if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
1040      // Try to parse the number and any suffix.
1041      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1042          GoodVersion.Patch < 0)
1043        return BadVersion;
1044      GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
1045    }
1046  }
1047
1048  return GoodVersion;
1049}
1050
1051/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1052bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
1053  if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
1054  if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
1055
1056  // Note that we rank versions with *no* patch specified is better than ones
1057  // hard-coding a patch version. Thus if the RHS has no patch, it always
1058  // wins, and the LHS only wins if it has no patch and the RHS does have
1059  // a patch.
1060  if (RHS.Patch == -1) return true;   if (Patch == -1) return false;
1061  if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
1062  if (PatchSuffix == RHS.PatchSuffix) return false;
1063
1064  // Finally, between completely tied version numbers, the version with the
1065  // suffix loses as we prefer full releases.
1066  if (RHS.PatchSuffix.empty()) return true;
1067  return false;
1068}
1069
1070static StringRef getGCCToolchainDir(const ArgList &Args) {
1071  const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1072  if (A)
1073    return A->getValue(Args);
1074  return GCC_INSTALL_PREFIX;
1075}
1076
1077/// \brief Construct a GCCInstallationDetector from the driver.
1078///
1079/// This performs all of the autodetection and sets up the various paths.
1080/// Once constructed, a GCCInstallationDetector is essentially immutable.
1081///
1082/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1083/// should instead pull the target out of the driver. This is currently
1084/// necessary because the driver doesn't store the final version of the target
1085/// triple.
1086Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
1087    const Driver &D,
1088    const llvm::Triple &TargetTriple,
1089    const ArgList &Args)
1090    : IsValid(false) {
1091  llvm::Triple MultiarchTriple
1092    = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1093                                 : TargetTriple.get32BitArchVariant();
1094  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1095  // The library directories which may contain GCC installations.
1096  SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
1097  // The compatible GCC triples for this particular architecture.
1098  SmallVector<StringRef, 10> CandidateTripleAliases;
1099  SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
1100  CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
1101                           CandidateTripleAliases,
1102                           CandidateMultiarchLibDirs,
1103                           CandidateMultiarchTripleAliases);
1104
1105  // Compute the set of prefixes for our search.
1106  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1107                                       D.PrefixDirs.end());
1108
1109  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1110  if (GCCToolchainDir != "") {
1111    if (GCCToolchainDir.back() == '/')
1112      GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1113
1114    Prefixes.push_back(GCCToolchainDir);
1115  } else {
1116    Prefixes.push_back(D.SysRoot);
1117    Prefixes.push_back(D.SysRoot + "/usr");
1118    Prefixes.push_back(D.InstalledDir + "/..");
1119  }
1120
1121  // Loop over the various components which exist and select the best GCC
1122  // installation available. GCC installs are ranked by version number.
1123  Version = GCCVersion::Parse("0.0.0");
1124  for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1125    if (!llvm::sys::fs::exists(Prefixes[i]))
1126      continue;
1127    for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1128      const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1129      if (!llvm::sys::fs::exists(LibDir))
1130        continue;
1131      for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1132        ScanLibDirForGCCTriple(TargetArch, LibDir, CandidateTripleAliases[k]);
1133    }
1134    for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1135      const std::string LibDir
1136        = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1137      if (!llvm::sys::fs::exists(LibDir))
1138        continue;
1139      for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1140           ++k)
1141        ScanLibDirForGCCTriple(TargetArch, LibDir,
1142                               CandidateMultiarchTripleAliases[k],
1143                               /*NeedsMultiarchSuffix=*/true);
1144    }
1145  }
1146}
1147
1148/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1149    const llvm::Triple &TargetTriple,
1150    const llvm::Triple &MultiarchTriple,
1151    SmallVectorImpl<StringRef> &LibDirs,
1152    SmallVectorImpl<StringRef> &TripleAliases,
1153    SmallVectorImpl<StringRef> &MultiarchLibDirs,
1154    SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1155  // Declare a bunch of static data sets that we'll select between below. These
1156  // are specifically designed to always refer to string literals to avoid any
1157  // lifetime or initialization issues.
1158  static const char *const ARMLibDirs[] = { "/lib" };
1159  static const char *const ARMTriples[] = {
1160    "arm-linux-gnueabi",
1161    "arm-linux-androideabi"
1162  };
1163  static const char *const ARMHFTriples[] = {
1164    "arm-linux-gnueabihf",
1165  };
1166
1167  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1168  static const char *const X86_64Triples[] = {
1169    "x86_64-linux-gnu",
1170    "x86_64-unknown-linux-gnu",
1171    "x86_64-pc-linux-gnu",
1172    "x86_64-redhat-linux6E",
1173    "x86_64-redhat-linux",
1174    "x86_64-suse-linux",
1175    "x86_64-manbo-linux-gnu",
1176    "x86_64-linux-gnu",
1177    "x86_64-slackware-linux"
1178  };
1179  static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1180  static const char *const X86Triples[] = {
1181    "i686-linux-gnu",
1182    "i686-pc-linux-gnu",
1183    "i486-linux-gnu",
1184    "i386-linux-gnu",
1185    "i686-redhat-linux",
1186    "i586-redhat-linux",
1187    "i386-redhat-linux",
1188    "i586-suse-linux",
1189    "i486-slackware-linux",
1190    "i686-montavista-linux"
1191  };
1192
1193  static const char *const MIPSLibDirs[] = { "/lib" };
1194  static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1195  static const char *const MIPSELLibDirs[] = { "/lib" };
1196  static const char *const MIPSELTriples[] = { "mipsel-linux-gnu" };
1197
1198  static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1199  static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1200  static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1201  static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1202
1203  static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1204  static const char *const PPCTriples[] = {
1205    "powerpc-linux-gnu",
1206    "powerpc-unknown-linux-gnu",
1207    "powerpc-suse-linux",
1208    "powerpc-montavista-linuxspe"
1209  };
1210  static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1211  static const char *const PPC64Triples[] = {
1212    "powerpc64-linux-gnu",
1213    "powerpc64-unknown-linux-gnu",
1214    "powerpc64-suse-linux",
1215    "ppc64-redhat-linux"
1216  };
1217
1218  switch (TargetTriple.getArch()) {
1219  case llvm::Triple::arm:
1220  case llvm::Triple::thumb:
1221    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1222    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1223      TripleAliases.append(
1224        ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1225    } else {
1226      TripleAliases.append(
1227        ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1228    }
1229    break;
1230  case llvm::Triple::x86_64:
1231    LibDirs.append(
1232      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1233    TripleAliases.append(
1234      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1235    MultiarchLibDirs.append(
1236      X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1237    MultiarchTripleAliases.append(
1238      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1239    break;
1240  case llvm::Triple::x86:
1241    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1242    TripleAliases.append(
1243      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1244    MultiarchLibDirs.append(
1245      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1246    MultiarchTripleAliases.append(
1247      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1248    break;
1249  case llvm::Triple::mips:
1250    LibDirs.append(
1251      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1252    TripleAliases.append(
1253      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1254    MultiarchLibDirs.append(
1255      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1256    MultiarchTripleAliases.append(
1257      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1258    break;
1259  case llvm::Triple::mipsel:
1260    LibDirs.append(
1261      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1262    TripleAliases.append(
1263      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1264    MultiarchLibDirs.append(
1265      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1266    MultiarchTripleAliases.append(
1267      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1268    break;
1269  case llvm::Triple::mips64:
1270    LibDirs.append(
1271      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1272    TripleAliases.append(
1273      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1274    MultiarchLibDirs.append(
1275      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1276    MultiarchTripleAliases.append(
1277      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1278    break;
1279  case llvm::Triple::mips64el:
1280    LibDirs.append(
1281      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1282    TripleAliases.append(
1283      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1284    MultiarchLibDirs.append(
1285      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1286    MultiarchTripleAliases.append(
1287      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1288    break;
1289  case llvm::Triple::ppc:
1290    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1291    TripleAliases.append(
1292      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1293    MultiarchLibDirs.append(
1294      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1295    MultiarchTripleAliases.append(
1296      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1297    break;
1298  case llvm::Triple::ppc64:
1299    LibDirs.append(
1300      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1301    TripleAliases.append(
1302      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1303    MultiarchLibDirs.append(
1304      PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1305    MultiarchTripleAliases.append(
1306      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1307    break;
1308
1309  default:
1310    // By default, just rely on the standard lib directories and the original
1311    // triple.
1312    break;
1313  }
1314
1315  // Always append the drivers target triple to the end, in case it doesn't
1316  // match any of our aliases.
1317  TripleAliases.push_back(TargetTriple.str());
1318
1319  // Also include the multiarch variant if it's different.
1320  if (TargetTriple.str() != MultiarchTriple.str())
1321    MultiarchTripleAliases.push_back(MultiarchTriple.str());
1322}
1323
1324void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1325    llvm::Triple::ArchType TargetArch, const std::string &LibDir,
1326    StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1327  // There are various different suffixes involving the triple we
1328  // check for. We also record what is necessary to walk from each back
1329  // up to the lib directory.
1330  const std::string LibSuffixes[] = {
1331    "/gcc/" + CandidateTriple.str(),
1332    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1333
1334    // The Freescale PPC SDK has the gcc libraries in
1335    // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1336    "/" + CandidateTriple.str(),
1337
1338    // Ubuntu has a strange mis-matched pair of triples that this happens to
1339    // match.
1340    // FIXME: It may be worthwhile to generalize this and look for a second
1341    // triple.
1342    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1343  };
1344  const std::string InstallSuffixes[] = {
1345    "/../../..",
1346    "/../../../..",
1347    "/../..",
1348    "/../../../.."
1349  };
1350  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1351  const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1352                                   (TargetArch != llvm::Triple::x86));
1353  for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1354    StringRef LibSuffix = LibSuffixes[i];
1355    llvm::error_code EC;
1356    for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1357         !EC && LI != LE; LI = LI.increment(EC)) {
1358      StringRef VersionText = llvm::sys::path::filename(LI->path());
1359      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1360      static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1361      if (CandidateVersion < MinVersion)
1362        continue;
1363      if (CandidateVersion <= Version)
1364        continue;
1365
1366      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1367      // in what would normally be GCCInstallPath and put the 64-bit
1368      // libs in a subdirectory named 64. The simple logic we follow is that
1369      // *if* there is a subdirectory of the right name with crtbegin.o in it,
1370      // we use that. If not, and if not a multiarch triple, we look for
1371      // crtbegin.o without the subdirectory.
1372      StringRef MultiarchSuffix
1373        = (TargetArch == llvm::Triple::x86_64 ||
1374           TargetArch == llvm::Triple::ppc64 ||
1375           TargetArch == llvm::Triple::mips64 ||
1376           TargetArch == llvm::Triple::mips64el) ? "/64" : "/32";
1377      if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1378        GCCMultiarchSuffix = MultiarchSuffix.str();
1379      } else {
1380        if (NeedsMultiarchSuffix ||
1381            !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1382          continue;
1383        GCCMultiarchSuffix.clear();
1384      }
1385
1386      Version = CandidateVersion;
1387      GCCTriple.setTriple(CandidateTriple);
1388      // FIXME: We hack together the directory name here instead of
1389      // using LI to ensure stable path separators across Windows and
1390      // Linux.
1391      GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1392      GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1393      IsValid = true;
1394    }
1395  }
1396}
1397
1398Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1399                         const ArgList &Args)
1400  : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
1401  getProgramPaths().push_back(getDriver().getInstalledDir());
1402  if (getDriver().getInstalledDir() != getDriver().Dir)
1403    getProgramPaths().push_back(getDriver().Dir);
1404}
1405
1406Generic_GCC::~Generic_GCC() {
1407  // Free tool implementations.
1408  for (llvm::DenseMap<unsigned, Tool*>::iterator
1409         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1410    delete it->second;
1411}
1412
1413Tool &Generic_GCC::SelectTool(const Compilation &C,
1414                              const JobAction &JA,
1415                              const ActionList &Inputs) const {
1416  Action::ActionClass Key;
1417  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1418    Key = Action::AnalyzeJobClass;
1419  else
1420    Key = JA.getKind();
1421
1422  Tool *&T = Tools[Key];
1423  if (!T) {
1424    switch (Key) {
1425    case Action::InputClass:
1426    case Action::BindArchClass:
1427      llvm_unreachable("Invalid tool kind.");
1428    case Action::PreprocessJobClass:
1429      T = new tools::gcc::Preprocess(*this); break;
1430    case Action::PrecompileJobClass:
1431      T = new tools::gcc::Precompile(*this); break;
1432    case Action::AnalyzeJobClass:
1433    case Action::MigrateJobClass:
1434      T = new tools::Clang(*this); break;
1435    case Action::CompileJobClass:
1436      T = new tools::gcc::Compile(*this); break;
1437    case Action::AssembleJobClass:
1438      T = new tools::gcc::Assemble(*this); break;
1439    case Action::LinkJobClass:
1440      T = new tools::gcc::Link(*this); break;
1441
1442      // This is a bit ungeneric, but the only platform using a driver
1443      // driver is Darwin.
1444    case Action::LipoJobClass:
1445      T = new tools::darwin::Lipo(*this); break;
1446    case Action::DsymutilJobClass:
1447      T = new tools::darwin::Dsymutil(*this); break;
1448    case Action::VerifyJobClass:
1449      T = new tools::darwin::VerifyDebug(*this); break;
1450    }
1451  }
1452
1453  return *T;
1454}
1455
1456bool Generic_GCC::IsUnwindTablesDefault() const {
1457  // FIXME: Gross; we should probably have some separate target
1458  // definition, possibly even reusing the one in clang.
1459  return getArch() == llvm::Triple::x86_64;
1460}
1461
1462const char *Generic_GCC::GetDefaultRelocationModel() const {
1463  return "static";
1464}
1465
1466const char *Generic_GCC::GetForcedPicModel() const {
1467  return 0;
1468}
1469/// Hexagon Toolchain
1470
1471Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
1472  : ToolChain(D, Triple) {
1473  getProgramPaths().push_back(getDriver().getInstalledDir());
1474  if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
1475    getProgramPaths().push_back(getDriver().Dir);
1476}
1477
1478Hexagon_TC::~Hexagon_TC() {
1479  // Free tool implementations.
1480  for (llvm::DenseMap<unsigned, Tool*>::iterator
1481         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1482    delete it->second;
1483}
1484
1485Tool &Hexagon_TC::SelectTool(const Compilation &C,
1486                             const JobAction &JA,
1487                             const ActionList &Inputs) const {
1488  Action::ActionClass Key;
1489  //   if (JA.getKind () == Action::CompileJobClass)
1490  //     Key = JA.getKind ();
1491  //     else
1492
1493  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1494    Key = Action::AnalyzeJobClass;
1495  else
1496    Key = JA.getKind();
1497  //   if ((JA.getKind () == Action::CompileJobClass)
1498  //     && (JA.getType () != types::TY_LTO_BC)) {
1499  //     Key = JA.getKind ();
1500  //   }
1501
1502  Tool *&T = Tools[Key];
1503  if (!T) {
1504    switch (Key) {
1505    case Action::InputClass:
1506    case Action::BindArchClass:
1507      assert(0 && "Invalid tool kind.");
1508    case Action::AnalyzeJobClass:
1509      T = new tools::Clang(*this); break;
1510    case Action::AssembleJobClass:
1511      T = new tools::hexagon::Assemble(*this); break;
1512    case Action::LinkJobClass:
1513      T = new tools::hexagon::Link(*this); break;
1514    default:
1515      assert(false && "Unsupported action for Hexagon target.");
1516    }
1517  }
1518
1519  return *T;
1520}
1521
1522const char *Hexagon_TC::GetDefaultRelocationModel() const {
1523  return "static";
1524}
1525
1526const char *Hexagon_TC::GetForcedPicModel() const {
1527  return 0;
1528} // End Hexagon
1529
1530
1531/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1532/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1533/// Currently does not support anything else but compilation.
1534
1535TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
1536  : ToolChain(D, Triple) {
1537  // Path mangling to find libexec
1538  std::string Path(getDriver().Dir);
1539
1540  Path += "/../libexec";
1541  getProgramPaths().push_back(Path);
1542}
1543
1544TCEToolChain::~TCEToolChain() {
1545  for (llvm::DenseMap<unsigned, Tool*>::iterator
1546           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1547      delete it->second;
1548}
1549
1550bool TCEToolChain::IsMathErrnoDefault() const {
1551  return true;
1552}
1553
1554const char *TCEToolChain::GetDefaultRelocationModel() const {
1555  return "static";
1556}
1557
1558const char *TCEToolChain::GetForcedPicModel() const {
1559  return 0;
1560}
1561
1562Tool &TCEToolChain::SelectTool(const Compilation &C,
1563                            const JobAction &JA,
1564                               const ActionList &Inputs) const {
1565  Action::ActionClass Key;
1566  Key = Action::AnalyzeJobClass;
1567
1568  Tool *&T = Tools[Key];
1569  if (!T) {
1570    switch (Key) {
1571    case Action::PreprocessJobClass:
1572      T = new tools::gcc::Preprocess(*this); break;
1573    case Action::AnalyzeJobClass:
1574      T = new tools::Clang(*this); break;
1575    default:
1576     llvm_unreachable("Unsupported action for TCE target.");
1577    }
1578  }
1579  return *T;
1580}
1581
1582/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1583
1584OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1585  : Generic_ELF(D, Triple, Args) {
1586  getFilePaths().push_back(getDriver().Dir + "/../lib");
1587  getFilePaths().push_back("/usr/lib");
1588}
1589
1590Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1591                          const ActionList &Inputs) const {
1592  Action::ActionClass Key;
1593  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1594    Key = Action::AnalyzeJobClass;
1595  else
1596    Key = JA.getKind();
1597
1598  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1599                                             options::OPT_no_integrated_as,
1600                                             IsIntegratedAssemblerDefault());
1601
1602  Tool *&T = Tools[Key];
1603  if (!T) {
1604    switch (Key) {
1605    case Action::AssembleJobClass: {
1606      if (UseIntegratedAs)
1607        T = new tools::ClangAs(*this);
1608      else
1609        T = new tools::openbsd::Assemble(*this);
1610      break;
1611    }
1612    case Action::LinkJobClass:
1613      T = new tools::openbsd::Link(*this); break;
1614    default:
1615      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1616    }
1617  }
1618
1619  return *T;
1620}
1621
1622/// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1623
1624Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1625  : Generic_ELF(D, Triple, Args) {
1626  getFilePaths().push_back(getDriver().Dir + "/../lib");
1627  getFilePaths().push_back("/usr/lib");
1628}
1629
1630Tool &Bitrig::SelectTool(const Compilation &C, const JobAction &JA,
1631                         const ActionList &Inputs) const {
1632  Action::ActionClass Key;
1633  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1634    Key = Action::AnalyzeJobClass;
1635  else
1636    Key = JA.getKind();
1637
1638  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1639                                             options::OPT_no_integrated_as,
1640                                             IsIntegratedAssemblerDefault());
1641
1642  Tool *&T = Tools[Key];
1643  if (!T) {
1644    switch (Key) {
1645    case Action::AssembleJobClass: {
1646      if (UseIntegratedAs)
1647        T = new tools::ClangAs(*this);
1648      else
1649        T = new tools::bitrig::Assemble(*this);
1650      break;
1651    }
1652    case Action::LinkJobClass:
1653      T = new tools::bitrig::Link(*this); break;
1654    default:
1655      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1656    }
1657  }
1658
1659  return *T;
1660}
1661
1662void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1663                                          ArgStringList &CC1Args) const {
1664  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1665      DriverArgs.hasArg(options::OPT_nostdincxx))
1666    return;
1667
1668  std::string Triple = getTriple().str();
1669  if (Triple.substr(0, 5) == "amd64")
1670    Triple.replace(0, 5, "x86_64");
1671
1672  addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/4.6.2");
1673  addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/4.6.2/backward");
1674  addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/4.6.2/" + Triple);
1675
1676}
1677
1678void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1679                                 ArgStringList &CmdArgs) const {
1680  CmdArgs.push_back("-lstdc++");
1681}
1682
1683/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1684
1685FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1686  : Generic_ELF(D, Triple, Args) {
1687
1688  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1689  // back to '/usr/lib' if it doesn't exist.
1690  if ((Triple.getArch() == llvm::Triple::x86 ||
1691       Triple.getArch() == llvm::Triple::ppc) &&
1692      llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1693    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1694  else
1695    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1696}
1697
1698Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1699                          const ActionList &Inputs) const {
1700  Action::ActionClass Key;
1701  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1702    Key = Action::AnalyzeJobClass;
1703  else
1704    Key = JA.getKind();
1705
1706  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1707                                             options::OPT_no_integrated_as,
1708                                             IsIntegratedAssemblerDefault());
1709
1710  Tool *&T = Tools[Key];
1711  if (!T) {
1712    switch (Key) {
1713    case Action::AssembleJobClass:
1714      if (UseIntegratedAs)
1715        T = new tools::ClangAs(*this);
1716      else
1717        T = new tools::freebsd::Assemble(*this);
1718      break;
1719    case Action::LinkJobClass:
1720      T = new tools::freebsd::Link(*this); break;
1721    default:
1722      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1723    }
1724  }
1725
1726  return *T;
1727}
1728
1729/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1730
1731NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1732  : Generic_ELF(D, Triple, Args) {
1733
1734  if (getDriver().UseStdLib) {
1735    // When targeting a 32-bit platform, try the special directory used on
1736    // 64-bit hosts, and only fall back to the main library directory if that
1737    // doesn't work.
1738    // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1739    // what all logic is needed to emulate the '=' prefix here.
1740    if (Triple.getArch() == llvm::Triple::x86)
1741      getFilePaths().push_back("=/usr/lib/i386");
1742
1743    getFilePaths().push_back("=/usr/lib");
1744  }
1745}
1746
1747Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1748                         const ActionList &Inputs) const {
1749  Action::ActionClass Key;
1750  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1751    Key = Action::AnalyzeJobClass;
1752  else
1753    Key = JA.getKind();
1754
1755  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1756                                             options::OPT_no_integrated_as,
1757                                             IsIntegratedAssemblerDefault());
1758
1759  Tool *&T = Tools[Key];
1760  if (!T) {
1761    switch (Key) {
1762    case Action::AssembleJobClass:
1763      if (UseIntegratedAs)
1764        T = new tools::ClangAs(*this);
1765      else
1766        T = new tools::netbsd::Assemble(*this);
1767      break;
1768    case Action::LinkJobClass:
1769      T = new tools::netbsd::Link(*this);
1770      break;
1771    default:
1772      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1773    }
1774  }
1775
1776  return *T;
1777}
1778
1779/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1780
1781Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1782  : Generic_ELF(D, Triple, Args) {
1783  getFilePaths().push_back(getDriver().Dir + "/../lib");
1784  getFilePaths().push_back("/usr/lib");
1785}
1786
1787Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1788                        const ActionList &Inputs) const {
1789  Action::ActionClass Key;
1790  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1791    Key = Action::AnalyzeJobClass;
1792  else
1793    Key = JA.getKind();
1794
1795  Tool *&T = Tools[Key];
1796  if (!T) {
1797    switch (Key) {
1798    case Action::AssembleJobClass:
1799      T = new tools::minix::Assemble(*this); break;
1800    case Action::LinkJobClass:
1801      T = new tools::minix::Link(*this); break;
1802    default:
1803      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1804    }
1805  }
1806
1807  return *T;
1808}
1809
1810/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1811
1812AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1813                   const ArgList &Args)
1814  : Generic_GCC(D, Triple, Args) {
1815
1816  getProgramPaths().push_back(getDriver().getInstalledDir());
1817  if (getDriver().getInstalledDir() != getDriver().Dir)
1818    getProgramPaths().push_back(getDriver().Dir);
1819
1820  getFilePaths().push_back(getDriver().Dir + "/../lib");
1821  getFilePaths().push_back("/usr/lib");
1822  getFilePaths().push_back("/usr/sfw/lib");
1823  getFilePaths().push_back("/opt/gcc4/lib");
1824  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1825
1826}
1827
1828Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1829                           const ActionList &Inputs) const {
1830  Action::ActionClass Key;
1831  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1832    Key = Action::AnalyzeJobClass;
1833  else
1834    Key = JA.getKind();
1835
1836  Tool *&T = Tools[Key];
1837  if (!T) {
1838    switch (Key) {
1839    case Action::AssembleJobClass:
1840      T = new tools::auroraux::Assemble(*this); break;
1841    case Action::LinkJobClass:
1842      T = new tools::auroraux::Link(*this); break;
1843    default:
1844      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1845    }
1846  }
1847
1848  return *T;
1849}
1850
1851/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1852
1853Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1854                 const ArgList &Args)
1855  : Generic_GCC(D, Triple, Args) {
1856
1857  getProgramPaths().push_back(getDriver().getInstalledDir());
1858  if (getDriver().getInstalledDir() != getDriver().Dir)
1859    getProgramPaths().push_back(getDriver().Dir);
1860
1861  getFilePaths().push_back(getDriver().Dir + "/../lib");
1862  getFilePaths().push_back("/usr/lib");
1863}
1864
1865Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
1866                           const ActionList &Inputs) const {
1867  Action::ActionClass Key;
1868  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1869    Key = Action::AnalyzeJobClass;
1870  else
1871    Key = JA.getKind();
1872
1873  Tool *&T = Tools[Key];
1874  if (!T) {
1875    switch (Key) {
1876    case Action::AssembleJobClass:
1877      T = new tools::solaris::Assemble(*this); break;
1878    case Action::LinkJobClass:
1879      T = new tools::solaris::Link(*this); break;
1880    default:
1881      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1882    }
1883  }
1884
1885  return *T;
1886}
1887
1888/// Linux toolchain (very bare-bones at the moment).
1889
1890enum LinuxDistro {
1891  ArchLinux,
1892  DebianLenny,
1893  DebianSqueeze,
1894  DebianWheezy,
1895  Exherbo,
1896  RHEL4,
1897  RHEL5,
1898  RHEL6,
1899  Fedora13,
1900  Fedora14,
1901  Fedora15,
1902  Fedora16,
1903  FedoraRawhide,
1904  OpenSuse11_3,
1905  OpenSuse11_4,
1906  OpenSuse12_1,
1907  OpenSuse12_2,
1908  UbuntuHardy,
1909  UbuntuIntrepid,
1910  UbuntuJaunty,
1911  UbuntuKarmic,
1912  UbuntuLucid,
1913  UbuntuMaverick,
1914  UbuntuNatty,
1915  UbuntuOneiric,
1916  UbuntuPrecise,
1917  UnknownDistro
1918};
1919
1920static bool IsRedhat(enum LinuxDistro Distro) {
1921  return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1922         (Distro >= RHEL4    && Distro <= RHEL6);
1923}
1924
1925static bool IsOpenSuse(enum LinuxDistro Distro) {
1926  return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
1927}
1928
1929static bool IsDebian(enum LinuxDistro Distro) {
1930  return Distro >= DebianLenny && Distro <= DebianWheezy;
1931}
1932
1933static bool IsUbuntu(enum LinuxDistro Distro) {
1934  return Distro >= UbuntuHardy && Distro <= UbuntuPrecise;
1935}
1936
1937static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1938  OwningPtr<llvm::MemoryBuffer> File;
1939  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1940    StringRef Data = File.get()->getBuffer();
1941    SmallVector<StringRef, 8> Lines;
1942    Data.split(Lines, "\n");
1943    LinuxDistro Version = UnknownDistro;
1944    for (unsigned i = 0, s = Lines.size(); i != s; ++i)
1945      if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
1946        Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
1947          .Case("hardy", UbuntuHardy)
1948          .Case("intrepid", UbuntuIntrepid)
1949          .Case("jaunty", UbuntuJaunty)
1950          .Case("karmic", UbuntuKarmic)
1951          .Case("lucid", UbuntuLucid)
1952          .Case("maverick", UbuntuMaverick)
1953          .Case("natty", UbuntuNatty)
1954          .Case("oneiric", UbuntuOneiric)
1955          .Case("precise", UbuntuPrecise)
1956          .Default(UnknownDistro);
1957    return Version;
1958  }
1959
1960  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1961    StringRef Data = File.get()->getBuffer();
1962    if (Data.startswith("Fedora release 16"))
1963      return Fedora16;
1964    else if (Data.startswith("Fedora release 15"))
1965      return Fedora15;
1966    else if (Data.startswith("Fedora release 14"))
1967      return Fedora14;
1968    else if (Data.startswith("Fedora release 13"))
1969      return Fedora13;
1970    else if (Data.startswith("Fedora release") &&
1971             Data.find("Rawhide") != StringRef::npos)
1972      return FedoraRawhide;
1973    else if (Data.startswith("Red Hat Enterprise Linux") &&
1974             Data.find("release 6") != StringRef::npos)
1975      return RHEL6;
1976    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1977	      Data.startswith("CentOS")) &&
1978             Data.find("release 5") != StringRef::npos)
1979      return RHEL5;
1980    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1981	      Data.startswith("CentOS")) &&
1982             Data.find("release 4") != StringRef::npos)
1983      return RHEL4;
1984    return UnknownDistro;
1985  }
1986
1987  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1988    StringRef Data = File.get()->getBuffer();
1989    if (Data[0] == '5')
1990      return DebianLenny;
1991    else if (Data.startswith("squeeze/sid") || Data[0] == '6')
1992      return DebianSqueeze;
1993    else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
1994      return DebianWheezy;
1995    return UnknownDistro;
1996  }
1997
1998  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
1999    return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
2000      .StartsWith("openSUSE 11.3", OpenSuse11_3)
2001      .StartsWith("openSUSE 11.4", OpenSuse11_4)
2002      .StartsWith("openSUSE 12.1", OpenSuse12_1)
2003      .StartsWith("openSUSE 12.2", OpenSuse12_2)
2004      .Default(UnknownDistro);
2005
2006  bool Exists;
2007  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
2008    return Exherbo;
2009
2010  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
2011    return ArchLinux;
2012
2013  return UnknownDistro;
2014}
2015
2016/// \brief Get our best guess at the multiarch triple for a target.
2017///
2018/// Debian-based systems are starting to use a multiarch setup where they use
2019/// a target-triple directory in the library and header search paths.
2020/// Unfortunately, this triple does not align with the vanilla target triple,
2021/// so we provide a rough mapping here.
2022static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2023                                      StringRef SysRoot) {
2024  // For most architectures, just use whatever we have rather than trying to be
2025  // clever.
2026  switch (TargetTriple.getArch()) {
2027  default:
2028    return TargetTriple.str();
2029
2030    // We use the existence of '/lib/<triple>' as a directory to detect some
2031    // common linux triples that don't quite match the Clang triple for both
2032    // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2033    // regardless of what the actual target triple is.
2034  case llvm::Triple::arm:
2035  case llvm::Triple::thumb:
2036    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2037      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2038        return "arm-linux-gnueabihf";
2039    } else {
2040      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2041        return "arm-linux-gnueabi";
2042    }
2043    return TargetTriple.str();
2044  case llvm::Triple::x86:
2045    if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2046      return "i386-linux-gnu";
2047    return TargetTriple.str();
2048  case llvm::Triple::x86_64:
2049    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2050      return "x86_64-linux-gnu";
2051    return TargetTriple.str();
2052  case llvm::Triple::mips:
2053    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2054      return "mips-linux-gnu";
2055    return TargetTriple.str();
2056  case llvm::Triple::mipsel:
2057    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2058      return "mipsel-linux-gnu";
2059    return TargetTriple.str();
2060  case llvm::Triple::ppc:
2061    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2062      return "powerpc-linux-gnu";
2063    return TargetTriple.str();
2064  case llvm::Triple::ppc64:
2065    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2066      return "powerpc64-linux-gnu";
2067    return TargetTriple.str();
2068  }
2069}
2070
2071static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2072  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2073}
2074
2075static bool isMipsArch(llvm::Triple::ArchType Arch) {
2076  return Arch == llvm::Triple::mips ||
2077         Arch == llvm::Triple::mipsel ||
2078         Arch == llvm::Triple::mips64 ||
2079         Arch == llvm::Triple::mips64el;
2080}
2081
2082static StringRef getMultilibDir(const llvm::Triple &Triple,
2083                                const ArgList &Args) {
2084  if (!isMipsArch(Triple.getArch()))
2085    return Triple.isArch32Bit() ? "lib32" : "lib64";
2086
2087  // lib32 directory has a special meaning on MIPS targets.
2088  // It contains N32 ABI binaries. Use this folder if produce
2089  // code for N32 ABI only.
2090  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
2091  if (A && (A->getValue(Args) == StringRef("n32")))
2092    return "lib32";
2093
2094  return Triple.isArch32Bit() ? "lib" : "lib64";
2095}
2096
2097Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2098  : Generic_ELF(D, Triple, Args) {
2099  llvm::Triple::ArchType Arch = Triple.getArch();
2100  const std::string &SysRoot = getDriver().SysRoot;
2101
2102  // OpenSuse stores the linker with the compiler, add that to the search
2103  // path.
2104  ToolChain::path_list &PPaths = getProgramPaths();
2105  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2106                         GCCInstallation.getTriple().str() + "/bin").str());
2107
2108  Linker = GetProgramPath("ld");
2109
2110  LinuxDistro Distro = DetectLinuxDistro(Arch);
2111
2112  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2113    ExtraOpts.push_back("-z");
2114    ExtraOpts.push_back("relro");
2115  }
2116
2117  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2118    ExtraOpts.push_back("-X");
2119
2120  const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2121
2122  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2123  // and the MIPS ABI require .dynsym to be sorted in different ways.
2124  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2125  // ABI requires a mapping between the GOT and the symbol table.
2126  // Android loader does not support .gnu.hash.
2127  if (!isMipsArch(Arch) && !IsAndroid) {
2128    if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2129        (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2130      ExtraOpts.push_back("--hash-style=gnu");
2131
2132    if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2133        Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2134      ExtraOpts.push_back("--hash-style=both");
2135  }
2136
2137  if (IsRedhat(Distro))
2138    ExtraOpts.push_back("--no-add-needed");
2139
2140  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2141      IsOpenSuse(Distro) ||
2142      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2143      (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2144    ExtraOpts.push_back("--build-id");
2145
2146  if (IsOpenSuse(Distro))
2147    ExtraOpts.push_back("--enable-new-dtags");
2148
2149  // The selection of paths to try here is designed to match the patterns which
2150  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2151  // This was determined by running GCC in a fake filesystem, creating all
2152  // possible permutations of these directories, and seeing which ones it added
2153  // to the link paths.
2154  path_list &Paths = getFilePaths();
2155
2156  const std::string Multilib = getMultilibDir(Triple, Args);
2157  const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2158
2159  // Add the multilib suffixed paths where they are available.
2160  if (GCCInstallation.isValid()) {
2161    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2162    const std::string &LibPath = GCCInstallation.getParentLibPath();
2163    addPathIfExists((GCCInstallation.getInstallPath() +
2164                     GCCInstallation.getMultiarchSuffix()),
2165                    Paths);
2166
2167    // If the GCC installation we found is inside of the sysroot, we want to
2168    // prefer libraries installed in the parent prefix of the GCC installation.
2169    // It is important to *not* use these paths when the GCC installation is
2170    // outside of the system root as that can pick up unintended libraries.
2171    // This usually happens when there is an external cross compiler on the
2172    // host system, and a more minimal sysroot available that is the target of
2173    // the cross.
2174    if (StringRef(LibPath).startswith(SysRoot)) {
2175      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2176                      Paths);
2177      addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2178      addPathIfExists(LibPath + "/../" + Multilib, Paths);
2179    }
2180    // On Android, libraries in the parent prefix of the GCC installation are
2181    // preferred to the ones under sysroot.
2182    if (IsAndroid) {
2183      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2184    }
2185  }
2186  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2187  addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2188  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2189  addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2190
2191  // Try walking via the GCC triple path in case of multiarch GCC
2192  // installations with strange symlinks.
2193  if (GCCInstallation.isValid())
2194    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2195                    "/../../" + Multilib, Paths);
2196
2197  // Add the non-multilib suffixed paths (if potentially different).
2198  if (GCCInstallation.isValid()) {
2199    const std::string &LibPath = GCCInstallation.getParentLibPath();
2200    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2201    if (!GCCInstallation.getMultiarchSuffix().empty())
2202      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2203
2204    if (StringRef(LibPath).startswith(SysRoot)) {
2205      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2206      addPathIfExists(LibPath, Paths);
2207    }
2208  }
2209  addPathIfExists(SysRoot + "/lib", Paths);
2210  addPathIfExists(SysRoot + "/usr/lib", Paths);
2211}
2212
2213bool Linux::HasNativeLLVMSupport() const {
2214  return true;
2215}
2216
2217Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
2218                        const ActionList &Inputs) const {
2219  Action::ActionClass Key;
2220  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2221    Key = Action::AnalyzeJobClass;
2222  else
2223    Key = JA.getKind();
2224
2225  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2226                                             options::OPT_no_integrated_as,
2227                                             IsIntegratedAssemblerDefault());
2228
2229  Tool *&T = Tools[Key];
2230  if (!T) {
2231    switch (Key) {
2232    case Action::AssembleJobClass:
2233      if (UseIntegratedAs)
2234        T = new tools::ClangAs(*this);
2235      else
2236        T = new tools::linuxtools::Assemble(*this);
2237      break;
2238    case Action::LinkJobClass:
2239      T = new tools::linuxtools::Link(*this); break;
2240    default:
2241      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2242    }
2243  }
2244
2245  return *T;
2246}
2247
2248void Linux::addClangTargetOptions(ArgStringList &CC1Args) const {
2249  const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2250  if (V >= Generic_GCC::GCCVersion::Parse("4.7.0"))
2251    CC1Args.push_back("-fuse-init-array");
2252}
2253
2254void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2255                                      ArgStringList &CC1Args) const {
2256  const Driver &D = getDriver();
2257
2258  if (DriverArgs.hasArg(options::OPT_nostdinc))
2259    return;
2260
2261  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2262    addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2263
2264  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2265    llvm::sys::Path P(D.ResourceDir);
2266    P.appendComponent("include");
2267    addSystemInclude(DriverArgs, CC1Args, P.str());
2268  }
2269
2270  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2271    return;
2272
2273  // Check for configure-time C include directories.
2274  StringRef CIncludeDirs(C_INCLUDE_DIRS);
2275  if (CIncludeDirs != "") {
2276    SmallVector<StringRef, 5> dirs;
2277    CIncludeDirs.split(dirs, ":");
2278    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2279         I != E; ++I) {
2280      StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2281      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2282    }
2283    return;
2284  }
2285
2286  // Lacking those, try to detect the correct set of system includes for the
2287  // target triple.
2288
2289  // Implement generic Debian multiarch support.
2290  const StringRef X86_64MultiarchIncludeDirs[] = {
2291    "/usr/include/x86_64-linux-gnu",
2292
2293    // FIXME: These are older forms of multiarch. It's not clear that they're
2294    // in use in any released version of Debian, so we should consider
2295    // removing them.
2296    "/usr/include/i686-linux-gnu/64",
2297    "/usr/include/i486-linux-gnu/64"
2298  };
2299  const StringRef X86MultiarchIncludeDirs[] = {
2300    "/usr/include/i386-linux-gnu",
2301
2302    // FIXME: These are older forms of multiarch. It's not clear that they're
2303    // in use in any released version of Debian, so we should consider
2304    // removing them.
2305    "/usr/include/x86_64-linux-gnu/32",
2306    "/usr/include/i686-linux-gnu",
2307    "/usr/include/i486-linux-gnu"
2308  };
2309  const StringRef ARMMultiarchIncludeDirs[] = {
2310    "/usr/include/arm-linux-gnueabi"
2311  };
2312  const StringRef ARMHFMultiarchIncludeDirs[] = {
2313    "/usr/include/arm-linux-gnueabihf"
2314  };
2315  const StringRef MIPSMultiarchIncludeDirs[] = {
2316    "/usr/include/mips-linux-gnu"
2317  };
2318  const StringRef MIPSELMultiarchIncludeDirs[] = {
2319    "/usr/include/mipsel-linux-gnu"
2320  };
2321  const StringRef PPCMultiarchIncludeDirs[] = {
2322    "/usr/include/powerpc-linux-gnu"
2323  };
2324  const StringRef PPC64MultiarchIncludeDirs[] = {
2325    "/usr/include/powerpc64-linux-gnu"
2326  };
2327  ArrayRef<StringRef> MultiarchIncludeDirs;
2328  if (getTriple().getArch() == llvm::Triple::x86_64) {
2329    MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2330  } else if (getTriple().getArch() == llvm::Triple::x86) {
2331    MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2332  } else if (getTriple().getArch() == llvm::Triple::arm) {
2333    if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2334      MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2335    else
2336      MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2337  } else if (getTriple().getArch() == llvm::Triple::mips) {
2338    MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2339  } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2340    MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2341  } else if (getTriple().getArch() == llvm::Triple::ppc) {
2342    MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2343  } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2344    MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2345  }
2346  for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2347                                     E = MultiarchIncludeDirs.end();
2348       I != E; ++I) {
2349    if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2350      addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2351      break;
2352    }
2353  }
2354
2355  if (getTriple().getOS() == llvm::Triple::RTEMS)
2356    return;
2357
2358  // Add an include of '/include' directly. This isn't provided by default by
2359  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2360  // add even when Clang is acting as-if it were a system compiler.
2361  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2362
2363  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2364}
2365
2366/// \brief Helper to add the thre variant paths for a libstdc++ installation.
2367/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2368                                                const ArgList &DriverArgs,
2369                                                ArgStringList &CC1Args) {
2370  if (!llvm::sys::fs::exists(Base))
2371    return false;
2372  addSystemInclude(DriverArgs, CC1Args, Base);
2373  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2374  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2375  return true;
2376}
2377
2378void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2379                                         ArgStringList &CC1Args) const {
2380  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2381      DriverArgs.hasArg(options::OPT_nostdincxx))
2382    return;
2383
2384  // Check if libc++ has been enabled and provide its include paths if so.
2385  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2386    // libc++ is always installed at a fixed path on Linux currently.
2387    addSystemInclude(DriverArgs, CC1Args,
2388                     getDriver().SysRoot + "/usr/include/c++/v1");
2389    return;
2390  }
2391
2392  // We need a detected GCC installation on Linux to provide libstdc++'s
2393  // headers. We handled the libc++ case above.
2394  if (!GCCInstallation.isValid())
2395    return;
2396
2397  // By default, look for the C++ headers in an include directory adjacent to
2398  // the lib directory of the GCC installation. Note that this is expect to be
2399  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2400  StringRef LibDir = GCCInstallation.getParentLibPath();
2401  StringRef InstallDir = GCCInstallation.getInstallPath();
2402  StringRef Version = GCCInstallation.getVersion().Text;
2403  StringRef TripleStr = GCCInstallation.getTriple().str();
2404
2405  const std::string IncludePathCandidates[] = {
2406    LibDir.str() + "/../include/c++/" + Version.str(),
2407    // Gentoo is weird and places its headers inside the GCC install, so if the
2408    // first attempt to find the headers fails, try this pattern.
2409    InstallDir.str() + "/include/g++-v4",
2410    // Android standalone toolchain has C++ headers in yet another place.
2411    LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2412    // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2413    // without a subdirectory corresponding to the gcc version.
2414    LibDir.str() + "/../include/c++",
2415  };
2416
2417  for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2418    if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2419                GCCInstallation.getMultiarchSuffix()),
2420            DriverArgs, CC1Args))
2421      break;
2422  }
2423}
2424
2425/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2426
2427DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2428  : Generic_ELF(D, Triple, Args) {
2429
2430  // Path mangling to find libexec
2431  getProgramPaths().push_back(getDriver().getInstalledDir());
2432  if (getDriver().getInstalledDir() != getDriver().Dir)
2433    getProgramPaths().push_back(getDriver().Dir);
2434
2435  getFilePaths().push_back(getDriver().Dir + "/../lib");
2436  getFilePaths().push_back("/usr/lib");
2437  getFilePaths().push_back("/usr/lib/gcc41");
2438}
2439
2440Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
2441                            const ActionList &Inputs) const {
2442  Action::ActionClass Key;
2443  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2444    Key = Action::AnalyzeJobClass;
2445  else
2446    Key = JA.getKind();
2447
2448  Tool *&T = Tools[Key];
2449  if (!T) {
2450    switch (Key) {
2451    case Action::AssembleJobClass:
2452      T = new tools::dragonfly::Assemble(*this); break;
2453    case Action::LinkJobClass:
2454      T = new tools::dragonfly::Link(*this); break;
2455    default:
2456      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2457    }
2458  }
2459
2460  return *T;
2461}
2462