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