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