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