ToolChains.cpp revision 4c9403c57e4a867c58903546af5826df56a83980
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#ifdef HAVE_CLANG_CONFIG_H
13# include "clang/Config/config.h"
14#endif
15
16#include "clang/Driver/Arg.h"
17#include "clang/Driver/ArgList.h"
18#include "clang/Driver/Compilation.h"
19#include "clang/Driver/Driver.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/HostInfo.h"
22#include "clang/Driver/ObjCRuntime.h"
23#include "clang/Driver/OptTable.h"
24#include "clang/Driver/Option.h"
25#include "clang/Driver/Options.h"
26#include "clang/Basic/Version.h"
27
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/Path.h"
36#include "llvm/Support/system_error.h"
37
38#include <cstdlib> // ::getenv
39
40#include "llvm/Config/config.h" // for CXX_INCLUDE_ROOT
41
42using namespace clang::driver;
43using namespace clang::driver::toolchains;
44using namespace clang;
45
46/// Darwin - Darwin tool chain for i386 and x86_64.
47
48Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
49  : ToolChain(Host, Triple), TargetInitialized(false),
50    ARCRuntimeForSimulator(ARCSimulator_None)
51{
52  // Compute the initial Darwin version based on the host.
53  bool HadExtra;
54  std::string OSName = Triple.getOSName();
55  if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
56                                 DarwinVersion[0], DarwinVersion[1],
57                                 DarwinVersion[2], HadExtra))
58    getDriver().Diag(diag::err_drv_invalid_darwin_version) << OSName;
59
60  llvm::raw_string_ostream(MacosxVersionMin)
61    << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
62    << DarwinVersion[1];
63}
64
65types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
66  types::ID Ty = types::lookupTypeForExtension(Ext);
67
68  // Darwin always preprocesses assembly files (unless -x is used explicitly).
69  if (Ty == types::TY_PP_Asm)
70    return types::TY_Asm;
71
72  return Ty;
73}
74
75bool Darwin::HasNativeLLVMSupport() const {
76  return true;
77}
78
79bool Darwin::hasARCRuntime() const {
80  // FIXME: Remove this once there is a proper way to detect an ARC runtime
81  // for the simulator.
82  switch (ARCRuntimeForSimulator) {
83  case ARCSimulator_None:
84    break;
85  case ARCSimulator_HasARCRuntime:
86    return true;
87  case ARCSimulator_NoARCRuntime:
88    return false;
89  }
90
91  if (isTargetIPhoneOS())
92    return !isIPhoneOSVersionLT(5);
93  else
94    return !isMacosxVersionLT(10, 7);
95}
96
97/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
98void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const {
99  if (runtime.getKind() != ObjCRuntime::NeXT)
100    return ToolChain::configureObjCRuntime(runtime);
101
102  runtime.HasARC = runtime.HasWeak = hasARCRuntime();
103
104  // So far, objc_terminate is only available in iOS 5.
105  // FIXME: do the simulator logic properly.
106  if (!ARCRuntimeForSimulator && isTargetIPhoneOS())
107    runtime.HasTerminate = !isIPhoneOSVersionLT(5);
108  else
109    runtime.HasTerminate = false;
110}
111
112/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
113bool Darwin::hasBlocksRuntime() const {
114  if (isTargetIPhoneOS())
115    return !isIPhoneOSVersionLT(3, 2);
116  else
117    return !isMacosxVersionLT(10, 6);
118}
119
120// FIXME: Can we tablegen this?
121static const char *GetArmArchForMArch(StringRef Value) {
122  if (Value == "armv6k")
123    return "armv6";
124
125  if (Value == "armv5tej")
126    return "armv5";
127
128  if (Value == "xscale")
129    return "xscale";
130
131  if (Value == "armv4t")
132    return "armv4t";
133
134  if (Value == "armv7" || Value == "armv7-a" || Value == "armv7-r" ||
135      Value == "armv7-m" || Value == "armv7a" || Value == "armv7r" ||
136      Value == "armv7m")
137    return "armv7";
138
139  return 0;
140}
141
142// FIXME: Can we tablegen this?
143static const char *GetArmArchForMCpu(StringRef Value) {
144  if (Value == "arm10tdmi" || Value == "arm1020t" || Value == "arm9e" ||
145      Value == "arm946e-s" || Value == "arm966e-s" ||
146      Value == "arm968e-s" || Value == "arm10e" ||
147      Value == "arm1020e" || Value == "arm1022e" || Value == "arm926ej-s" ||
148      Value == "arm1026ej-s")
149    return "armv5";
150
151  if (Value == "xscale")
152    return "xscale";
153
154  if (Value == "arm1136j-s" || Value == "arm1136jf-s" ||
155      Value == "arm1176jz-s" || Value == "arm1176jzf-s" ||
156      Value == "cortex-m0" )
157    return "armv6";
158
159  if (Value == "cortex-a8" || Value == "cortex-r4" || Value == "cortex-m3")
160    return "armv7";
161
162  return 0;
163}
164
165StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
166  switch (getTriple().getArch()) {
167  default:
168    return getArchName();
169
170  case llvm::Triple::thumb:
171  case llvm::Triple::arm: {
172    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
173      if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
174        return Arch;
175
176    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
177      if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
178        return Arch;
179
180    return "arm";
181  }
182  }
183}
184
185Darwin::~Darwin() {
186  // Free tool implementations.
187  for (llvm::DenseMap<unsigned, Tool*>::iterator
188         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
189    delete it->second;
190}
191
192std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
193                                                types::ID InputType) const {
194  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
195
196  // If the target isn't initialized (e.g., an unknown Darwin platform, return
197  // the default triple).
198  if (!isTargetInitialized())
199    return Triple.getTriple();
200
201  unsigned Version[3];
202  getTargetVersion(Version);
203
204  llvm::SmallString<16> Str;
205  llvm::raw_svector_ostream(Str)
206    << (isTargetIPhoneOS() ? "ios" : "macosx")
207    << Version[0] << "." << Version[1] << "." << Version[2];
208  Triple.setOSName(Str.str());
209
210  return Triple.getTriple();
211}
212
213Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
214                         const ActionList &Inputs) const {
215  Action::ActionClass Key;
216
217  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
218    // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
219    if (Inputs.size() == 1 &&
220        types::isCXX(Inputs[0]->getType()) &&
221        getTriple().getOS() == llvm::Triple::Darwin &&
222        getTriple().getArch() == llvm::Triple::x86 &&
223        (C.getArgs().getLastArg(options::OPT_fapple_kext) ||
224         C.getArgs().getLastArg(options::OPT_mkernel)))
225      Key = JA.getKind();
226    else
227      Key = Action::AnalyzeJobClass;
228  } else
229    Key = JA.getKind();
230
231  // FIXME: This doesn't belong here, but ideally we will support static soon
232  // anyway.
233  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
234                    C.getArgs().hasArg(options::OPT_static) ||
235                    C.getArgs().hasArg(options::OPT_fapple_kext));
236  bool IsIADefault = IsIntegratedAssemblerDefault() && !HasStatic;
237  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
238                                             options::OPT_no_integrated_as,
239                                             IsIADefault);
240
241  Tool *&T = Tools[Key];
242  if (!T) {
243    switch (Key) {
244    case Action::InputClass:
245    case Action::BindArchClass:
246      llvm_unreachable("Invalid tool kind.");
247    case Action::PreprocessJobClass:
248      T = new tools::darwin::Preprocess(*this); break;
249    case Action::AnalyzeJobClass:
250      T = new tools::Clang(*this); break;
251    case Action::PrecompileJobClass:
252    case Action::CompileJobClass:
253      T = new tools::darwin::Compile(*this); break;
254    case Action::AssembleJobClass: {
255      if (UseIntegratedAs)
256        T = new tools::ClangAs(*this);
257      else
258        T = new tools::darwin::Assemble(*this);
259      break;
260    }
261    case Action::LinkJobClass:
262      T = new tools::darwin::Link(*this); break;
263    case Action::LipoJobClass:
264      T = new tools::darwin::Lipo(*this); break;
265    case Action::DsymutilJobClass:
266      T = new tools::darwin::Dsymutil(*this); break;
267    case Action::VerifyJobClass:
268      T = new tools::darwin::VerifyDebug(*this); break;
269    }
270  }
271
272  return *T;
273}
274
275
276DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
277  : Darwin(Host, Triple)
278{
279  getProgramPaths().push_back(getDriver().getInstalledDir());
280  if (getDriver().getInstalledDir() != getDriver().Dir)
281    getProgramPaths().push_back(getDriver().Dir);
282
283  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
284  getProgramPaths().push_back(getDriver().getInstalledDir());
285  if (getDriver().getInstalledDir() != getDriver().Dir)
286    getProgramPaths().push_back(getDriver().Dir);
287
288  // For fallback, we need to know how to find the GCC cc1 executables, so we
289  // also add the GCC libexec paths. This is legacy code that can be removed
290  // once fallback is no longer useful.
291  AddGCCLibexecPath(DarwinVersion[0]);
292  AddGCCLibexecPath(DarwinVersion[0] - 2);
293  AddGCCLibexecPath(DarwinVersion[0] - 1);
294  AddGCCLibexecPath(DarwinVersion[0] + 1);
295  AddGCCLibexecPath(DarwinVersion[0] + 2);
296}
297
298void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) {
299  std::string ToolChainDir = "i686-apple-darwin";
300  ToolChainDir += llvm::utostr(darwinVersion);
301  ToolChainDir += "/4.2.1";
302
303  std::string Path = getDriver().Dir;
304  Path += "/../llvm-gcc-4.2/libexec/gcc/";
305  Path += ToolChainDir;
306  getProgramPaths().push_back(Path);
307
308  Path = "/usr/llvm-gcc-4.2/libexec/gcc/";
309  Path += ToolChainDir;
310  getProgramPaths().push_back(Path);
311}
312
313void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args,
314                                       ArgStringList &CmdArgs) const {
315  // The Clang toolchain uses explicit paths for internal libraries.
316
317  // Unfortunately, we still might depend on a few of the libraries that are
318  // only available in the gcc library directory (in particular
319  // libstdc++.dylib). For now, hardcode the path to the known install location.
320  llvm::sys::Path P(getDriver().Dir);
321  P.eraseComponent(); // .../usr/bin -> ../usr
322  P.appendComponent("lib");
323  P.appendComponent("gcc");
324  switch (getTriple().getArch()) {
325  default:
326    llvm_unreachable("Invalid Darwin arch!");
327  case llvm::Triple::x86:
328  case llvm::Triple::x86_64:
329    P.appendComponent("i686-apple-darwin10");
330    break;
331  case llvm::Triple::arm:
332  case llvm::Triple::thumb:
333    P.appendComponent("arm-apple-darwin10");
334    break;
335  case llvm::Triple::ppc:
336  case llvm::Triple::ppc64:
337    P.appendComponent("powerpc-apple-darwin10");
338    break;
339  }
340  P.appendComponent("4.2.1");
341
342  // Determine the arch specific GCC subdirectory.
343  const char *ArchSpecificDir = 0;
344  switch (getTriple().getArch()) {
345  default:
346    break;
347  case llvm::Triple::arm:
348  case llvm::Triple::thumb: {
349    std::string Triple = ComputeLLVMTriple(Args);
350    StringRef TripleStr = Triple;
351    if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5"))
352      ArchSpecificDir = "v5";
353    else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6"))
354      ArchSpecificDir = "v6";
355    else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7"))
356      ArchSpecificDir = "v7";
357    break;
358  }
359  case llvm::Triple::ppc64:
360    ArchSpecificDir = "ppc64";
361    break;
362  case llvm::Triple::x86_64:
363    ArchSpecificDir = "x86_64";
364    break;
365  }
366
367  if (ArchSpecificDir) {
368    P.appendComponent(ArchSpecificDir);
369    bool Exists;
370    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
371      CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
372    P.eraseComponent();
373  }
374
375  bool Exists;
376  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
377    CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
378}
379
380void DarwinClang::AddLinkARCArgs(const ArgList &Args,
381                                 ArgStringList &CmdArgs) const {
382
383  CmdArgs.push_back("-force_load");
384  llvm::sys::Path P(getDriver().ClangExecutable);
385  P.eraseComponent(); // 'clang'
386  P.eraseComponent(); // 'bin'
387  P.appendComponent("lib");
388  P.appendComponent("arc");
389  P.appendComponent("libarclite_");
390  std::string s = P.str();
391  // Mash in the platform.
392  if (isTargetIPhoneOS())
393    s += "iphoneos";
394  // FIXME: isTargetIphoneOSSimulator() is not returning true.
395  else if (ARCRuntimeForSimulator != ARCSimulator_None)
396    s += "iphonesimulator";
397  else
398    s += "macosx";
399  s += ".a";
400
401  CmdArgs.push_back(Args.MakeArgString(s));
402}
403
404void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
405                                    ArgStringList &CmdArgs,
406                                    const char *DarwinStaticLib) const {
407  llvm::sys::Path P(getDriver().ResourceDir);
408  P.appendComponent("lib");
409  P.appendComponent("darwin");
410  P.appendComponent(DarwinStaticLib);
411
412  // For now, allow missing resource libraries to support developers who may
413  // not have compiler-rt checked out or integrated into their build.
414  bool Exists;
415  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
416    CmdArgs.push_back(Args.MakeArgString(P.str()));
417}
418
419void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
420                                        ArgStringList &CmdArgs) const {
421  // Darwin doesn't support real static executables, don't link any runtime
422  // libraries with -static.
423  if (Args.hasArg(options::OPT_static))
424    return;
425
426  // Reject -static-libgcc for now, we can deal with this when and if someone
427  // cares. This is useful in situations where someone wants to statically link
428  // something like libstdc++, and needs its runtime support routines.
429  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
430    getDriver().Diag(diag::err_drv_unsupported_opt)
431      << A->getAsString(Args);
432    return;
433  }
434
435  // Otherwise link libSystem, then the dynamic runtime library, and finally any
436  // target specific static runtime library.
437  CmdArgs.push_back("-lSystem");
438
439  // Select the dynamic runtime library and the target specific static library.
440  if (isTargetIPhoneOS()) {
441    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
442    // it never went into the SDK.
443    if (!isTargetIOSSimulator())
444        CmdArgs.push_back("-lgcc_s.1");
445
446    // We currently always need a static runtime library for iOS.
447    AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
448  } else {
449    // The dynamic runtime library was merged with libSystem for 10.6 and
450    // beyond; only 10.4 and 10.5 need an additional runtime library.
451    if (isMacosxVersionLT(10, 5))
452      CmdArgs.push_back("-lgcc_s.10.4");
453    else if (isMacosxVersionLT(10, 6))
454      CmdArgs.push_back("-lgcc_s.10.5");
455
456    // For OS X, we thought we would only need a static runtime library when
457    // targeting 10.4, to provide versions of the static functions which were
458    // omitted from 10.4.dylib.
459    //
460    // Unfortunately, that turned out to not be true, because Darwin system
461    // headers can still use eprintf on i386, and it is not exported from
462    // libSystem. Therefore, we still must provide a runtime library just for
463    // the tiny tiny handful of projects that *might* use that symbol.
464    if (isMacosxVersionLT(10, 5)) {
465      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
466    } else {
467      if (getTriple().getArch() == llvm::Triple::x86)
468        AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
469      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
470    }
471  }
472}
473
474static inline StringRef SimulatorVersionDefineName() {
475  return "__IPHONE_OS_VERSION_MIN_REQUIRED";
476}
477
478/// \brief Parse the simulator version define:
479/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
480// and return the grouped values as integers, e.g:
481//   __IPHONE_OS_VERSION_MIN_REQUIRED=40201
482// will return Major=4, Minor=2, Micro=1.
483static bool GetVersionFromSimulatorDefine(StringRef define,
484                                          unsigned &Major, unsigned &Minor,
485                                          unsigned &Micro) {
486  assert(define.startswith(SimulatorVersionDefineName()));
487  StringRef name, version;
488  llvm::tie(name, version) = define.split('=');
489  if (version.empty())
490    return false;
491  std::string verstr = version.str();
492  char *end;
493  unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
494  if (*end != '\0')
495    return false;
496  Major = num / 10000;
497  num = num % 10000;
498  Minor = num / 100;
499  Micro = num % 100;
500  return true;
501}
502
503void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
504  const OptTable &Opts = getDriver().getOpts();
505
506  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
507  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
508  Arg *iOSSimVersion = Args.getLastArg(
509    options::OPT_mios_simulator_version_min_EQ);
510
511  // FIXME: HACK! When compiling for the simulator we don't get a
512  // '-miphoneos-version-min' to help us know whether there is an ARC runtime
513  // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED
514  // define passed in command-line.
515  if (!iOSVersion) {
516    for (arg_iterator it = Args.filtered_begin(options::OPT_D),
517           ie = Args.filtered_end(); it != ie; ++it) {
518      StringRef define = (*it)->getValue(Args);
519      if (define.startswith(SimulatorVersionDefineName())) {
520        unsigned Major = 0, Minor = 0, Micro = 0;
521        if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
522            Major < 10 && Minor < 100 && Micro < 100) {
523          ARCRuntimeForSimulator = Major < 5 ? ARCSimulator_NoARCRuntime
524                                             : ARCSimulator_HasARCRuntime;
525        }
526        break;
527      }
528    }
529  }
530
531  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
532    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
533          << OSXVersion->getAsString(Args)
534          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
535    iOSVersion = iOSSimVersion = 0;
536  } else if (iOSVersion && iOSSimVersion) {
537    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
538          << iOSVersion->getAsString(Args)
539          << iOSSimVersion->getAsString(Args);
540    iOSSimVersion = 0;
541  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
542    // If no deployment target was specified on the command line, check for
543    // environment defines.
544    StringRef OSXTarget;
545    StringRef iOSTarget;
546    StringRef iOSSimTarget;
547    if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
548      OSXTarget = env;
549    if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
550      iOSTarget = env;
551    if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
552      iOSSimTarget = env;
553
554    // If no '-miphoneos-version-min' specified on the command line and
555    // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
556    // based on isysroot.
557    if (iOSTarget.empty()) {
558      if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
559        StringRef first, second;
560        StringRef isysroot = A->getValue(Args);
561        llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
562        if (second != "")
563          iOSTarget = second.substr(0,3);
564      }
565    }
566
567    // If no OSX or iOS target has been specified and we're compiling for armv7,
568    // go ahead as assume we're targeting iOS.
569    if (OSXTarget.empty() && iOSTarget.empty())
570      if (getDarwinArchName(Args) == "armv7")
571        iOSTarget = "0.0";
572
573    // Handle conflicting deployment targets
574    //
575    // FIXME: Don't hardcode default here.
576
577    // Do not allow conflicts with the iOS simulator target.
578    if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
579      getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
580        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
581        << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
582            "IPHONEOS_DEPLOYMENT_TARGET");
583    }
584
585    // Allow conflicts among OSX and iOS for historical reasons, but choose the
586    // default platform.
587    if (!OSXTarget.empty() && !iOSTarget.empty()) {
588      if (getTriple().getArch() == llvm::Triple::arm ||
589          getTriple().getArch() == llvm::Triple::thumb)
590        OSXTarget = "";
591      else
592        iOSTarget = "";
593    }
594
595    if (!OSXTarget.empty()) {
596      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
597      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
598      Args.append(OSXVersion);
599    } else if (!iOSTarget.empty()) {
600      const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
601      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
602      Args.append(iOSVersion);
603    } else if (!iOSSimTarget.empty()) {
604      const Option *O = Opts.getOption(
605        options::OPT_mios_simulator_version_min_EQ);
606      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
607      Args.append(iOSSimVersion);
608    } else {
609      // Otherwise, assume we are targeting OS X.
610      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
611      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
612      Args.append(OSXVersion);
613    }
614  }
615
616  // Reject invalid architecture combinations.
617  if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
618                        getTriple().getArch() != llvm::Triple::x86_64)) {
619    getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
620      << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
621  }
622
623  // Set the tool chain target information.
624  unsigned Major, Minor, Micro;
625  bool HadExtra;
626  if (OSXVersion) {
627    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
628    if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
629                                   Micro, HadExtra) || HadExtra ||
630        Major != 10 || Minor >= 100 || Micro >= 100)
631      getDriver().Diag(diag::err_drv_invalid_version_number)
632        << OSXVersion->getAsString(Args);
633  } else {
634    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
635    assert(Version && "Unknown target platform!");
636    if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
637                                   Micro, HadExtra) || HadExtra ||
638        Major >= 10 || Minor >= 100 || Micro >= 100)
639      getDriver().Diag(diag::err_drv_invalid_version_number)
640        << Version->getAsString(Args);
641  }
642
643  bool IsIOSSim = bool(iOSSimVersion);
644
645  // In GCC, the simulator historically was treated as being OS X in some
646  // contexts, like determining the link logic, despite generally being called
647  // with an iOS deployment target. For compatibility, we detect the
648  // simulator as iOS + x86, and treat it differently in a few contexts.
649  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
650                     getTriple().getArch() == llvm::Triple::x86_64))
651    IsIOSSim = true;
652
653  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
654}
655
656void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
657                                      ArgStringList &CmdArgs) const {
658  CXXStdlibType Type = GetCXXStdlibType(Args);
659
660  switch (Type) {
661  case ToolChain::CST_Libcxx:
662    CmdArgs.push_back("-lc++");
663    break;
664
665  case ToolChain::CST_Libstdcxx: {
666    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
667    // it was previously found in the gcc lib dir. However, for all the Darwin
668    // platforms we care about it was -lstdc++.6, so we search for that
669    // explicitly if we can't see an obvious -lstdc++ candidate.
670
671    // Check in the sysroot first.
672    bool Exists;
673    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
674      llvm::sys::Path P(A->getValue(Args));
675      P.appendComponent("usr");
676      P.appendComponent("lib");
677      P.appendComponent("libstdc++.dylib");
678
679      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
680        P.eraseComponent();
681        P.appendComponent("libstdc++.6.dylib");
682        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
683          CmdArgs.push_back(Args.MakeArgString(P.str()));
684          return;
685        }
686      }
687    }
688
689    // Otherwise, look in the root.
690    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
691      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
692      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
693      return;
694    }
695
696    // Otherwise, let the linker search.
697    CmdArgs.push_back("-lstdc++");
698    break;
699  }
700  }
701}
702
703void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
704                                   ArgStringList &CmdArgs) const {
705
706  // For Darwin platforms, use the compiler-rt-based support library
707  // instead of the gcc-provided one (which is also incidentally
708  // only present in the gcc lib dir, which makes it hard to find).
709
710  llvm::sys::Path P(getDriver().ResourceDir);
711  P.appendComponent("lib");
712  P.appendComponent("darwin");
713  P.appendComponent("libclang_rt.cc_kext.a");
714
715  // For now, allow missing resource libraries to support developers who may
716  // not have compiler-rt checked out or integrated into their build.
717  bool Exists;
718  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
719    CmdArgs.push_back(Args.MakeArgString(P.str()));
720}
721
722DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
723                                      const char *BoundArch) const {
724  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
725  const OptTable &Opts = getDriver().getOpts();
726
727  // FIXME: We really want to get out of the tool chain level argument
728  // translation business, as it makes the driver functionality much
729  // more opaque. For now, we follow gcc closely solely for the
730  // purpose of easily achieving feature parity & testability. Once we
731  // have something that works, we should reevaluate each translation
732  // and try to push it down into tool specific logic.
733
734  for (ArgList::const_iterator it = Args.begin(),
735         ie = Args.end(); it != ie; ++it) {
736    Arg *A = *it;
737
738    if (A->getOption().matches(options::OPT_Xarch__)) {
739      // Skip this argument unless the architecture matches either the toolchain
740      // triple arch, or the arch being bound.
741      //
742      // FIXME: Canonicalize name.
743      StringRef XarchArch = A->getValue(Args, 0);
744      if (!(XarchArch == getArchName()  ||
745            (BoundArch && XarchArch == BoundArch)))
746        continue;
747
748      Arg *OriginalArg = A;
749      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
750      unsigned Prev = Index;
751      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
752
753      // If the argument parsing failed or more than one argument was
754      // consumed, the -Xarch_ argument's parameter tried to consume
755      // extra arguments. Emit an error and ignore.
756      //
757      // We also want to disallow any options which would alter the
758      // driver behavior; that isn't going to work in our model. We
759      // use isDriverOption() as an approximation, although things
760      // like -O4 are going to slip through.
761      if (!XarchArg || Index > Prev + 1) {
762        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
763          << A->getAsString(Args);
764        continue;
765      } else if (XarchArg->getOption().isDriverOption()) {
766        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
767          << A->getAsString(Args);
768        continue;
769      }
770
771      XarchArg->setBaseArg(A);
772      A = XarchArg;
773
774      DAL->AddSynthesizedArg(A);
775
776      // Linker input arguments require custom handling. The problem is that we
777      // have already constructed the phase actions, so we can not treat them as
778      // "input arguments".
779      if (A->getOption().isLinkerInput()) {
780        // Convert the argument into individual Zlinker_input_args.
781        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
782          DAL->AddSeparateArg(OriginalArg,
783                              Opts.getOption(options::OPT_Zlinker_input),
784                              A->getValue(Args, i));
785
786        }
787        continue;
788      }
789    }
790
791    // Sob. These is strictly gcc compatible for the time being. Apple
792    // gcc translates options twice, which means that self-expanding
793    // options add duplicates.
794    switch ((options::ID) A->getOption().getID()) {
795    default:
796      DAL->append(A);
797      break;
798
799    case options::OPT_mkernel:
800    case options::OPT_fapple_kext:
801      DAL->append(A);
802      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
803      break;
804
805    case options::OPT_dependency_file:
806      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
807                          A->getValue(Args));
808      break;
809
810    case options::OPT_gfull:
811      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
812      DAL->AddFlagArg(A,
813               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
814      break;
815
816    case options::OPT_gused:
817      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
818      DAL->AddFlagArg(A,
819             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
820      break;
821
822    case options::OPT_shared:
823      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
824      break;
825
826    case options::OPT_fconstant_cfstrings:
827      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
828      break;
829
830    case options::OPT_fno_constant_cfstrings:
831      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
832      break;
833
834    case options::OPT_Wnonportable_cfstrings:
835      DAL->AddFlagArg(A,
836                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
837      break;
838
839    case options::OPT_Wno_nonportable_cfstrings:
840      DAL->AddFlagArg(A,
841                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
842      break;
843
844    case options::OPT_fpascal_strings:
845      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
846      break;
847
848    case options::OPT_fno_pascal_strings:
849      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
850      break;
851    }
852  }
853
854  if (getTriple().getArch() == llvm::Triple::x86 ||
855      getTriple().getArch() == llvm::Triple::x86_64)
856    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
857      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
858
859  // Add the arch options based on the particular spelling of -arch, to match
860  // how the driver driver works.
861  if (BoundArch) {
862    StringRef Name = BoundArch;
863    const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
864    const Option *MArch = Opts.getOption(options::OPT_march_EQ);
865
866    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
867    // which defines the list of which architectures we accept.
868    if (Name == "ppc")
869      ;
870    else if (Name == "ppc601")
871      DAL->AddJoinedArg(0, MCpu, "601");
872    else if (Name == "ppc603")
873      DAL->AddJoinedArg(0, MCpu, "603");
874    else if (Name == "ppc604")
875      DAL->AddJoinedArg(0, MCpu, "604");
876    else if (Name == "ppc604e")
877      DAL->AddJoinedArg(0, MCpu, "604e");
878    else if (Name == "ppc750")
879      DAL->AddJoinedArg(0, MCpu, "750");
880    else if (Name == "ppc7400")
881      DAL->AddJoinedArg(0, MCpu, "7400");
882    else if (Name == "ppc7450")
883      DAL->AddJoinedArg(0, MCpu, "7450");
884    else if (Name == "ppc970")
885      DAL->AddJoinedArg(0, MCpu, "970");
886
887    else if (Name == "ppc64")
888      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
889
890    else if (Name == "i386")
891      ;
892    else if (Name == "i486")
893      DAL->AddJoinedArg(0, MArch, "i486");
894    else if (Name == "i586")
895      DAL->AddJoinedArg(0, MArch, "i586");
896    else if (Name == "i686")
897      DAL->AddJoinedArg(0, MArch, "i686");
898    else if (Name == "pentium")
899      DAL->AddJoinedArg(0, MArch, "pentium");
900    else if (Name == "pentium2")
901      DAL->AddJoinedArg(0, MArch, "pentium2");
902    else if (Name == "pentpro")
903      DAL->AddJoinedArg(0, MArch, "pentiumpro");
904    else if (Name == "pentIIm3")
905      DAL->AddJoinedArg(0, MArch, "pentium2");
906
907    else if (Name == "x86_64")
908      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
909
910    else if (Name == "arm")
911      DAL->AddJoinedArg(0, MArch, "armv4t");
912    else if (Name == "armv4t")
913      DAL->AddJoinedArg(0, MArch, "armv4t");
914    else if (Name == "armv5")
915      DAL->AddJoinedArg(0, MArch, "armv5tej");
916    else if (Name == "xscale")
917      DAL->AddJoinedArg(0, MArch, "xscale");
918    else if (Name == "armv6")
919      DAL->AddJoinedArg(0, MArch, "armv6k");
920    else if (Name == "armv7")
921      DAL->AddJoinedArg(0, MArch, "armv7a");
922
923    else
924      llvm_unreachable("invalid Darwin arch");
925  }
926
927  // Add an explicit version min argument for the deployment target. We do this
928  // after argument translation because -Xarch_ arguments may add a version min
929  // argument.
930  AddDeploymentTarget(*DAL);
931
932  return DAL;
933}
934
935bool Darwin::IsUnwindTablesDefault() const {
936  // FIXME: Gross; we should probably have some separate target
937  // definition, possibly even reusing the one in clang.
938  return getArchName() == "x86_64";
939}
940
941bool Darwin::UseDwarfDebugFlags() const {
942  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
943    return S[0] != '\0';
944  return false;
945}
946
947bool Darwin::UseSjLjExceptions() const {
948  // Darwin uses SjLj exceptions on ARM.
949  return (getTriple().getArch() == llvm::Triple::arm ||
950          getTriple().getArch() == llvm::Triple::thumb);
951}
952
953const char *Darwin::GetDefaultRelocationModel() const {
954  return "pic";
955}
956
957const char *Darwin::GetForcedPicModel() const {
958  if (getArchName() == "x86_64")
959    return "pic";
960  return 0;
961}
962
963bool Darwin::SupportsProfiling() const {
964  // Profiling instrumentation is only supported on x86.
965  return getArchName() == "i386" || getArchName() == "x86_64";
966}
967
968bool Darwin::SupportsObjCGC() const {
969  // Garbage collection is supported everywhere except on iPhone OS.
970  return !isTargetIPhoneOS();
971}
972
973std::string
974Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
975                                                types::ID InputType) const {
976  return ComputeLLVMTriple(Args, InputType);
977}
978
979/// Generic_GCC - A tool chain using the 'gcc' command to perform
980/// all subcommands; this relies on gcc translating the majority of
981/// command line options.
982
983Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
984  : ToolChain(Host, Triple) {
985  getProgramPaths().push_back(getDriver().getInstalledDir());
986  if (getDriver().getInstalledDir() != getDriver().Dir)
987    getProgramPaths().push_back(getDriver().Dir);
988}
989
990Generic_GCC::~Generic_GCC() {
991  // Free tool implementations.
992  for (llvm::DenseMap<unsigned, Tool*>::iterator
993         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
994    delete it->second;
995}
996
997Tool &Generic_GCC::SelectTool(const Compilation &C,
998                              const JobAction &JA,
999                              const ActionList &Inputs) const {
1000  Action::ActionClass Key;
1001  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1002    Key = Action::AnalyzeJobClass;
1003  else
1004    Key = JA.getKind();
1005
1006  Tool *&T = Tools[Key];
1007  if (!T) {
1008    switch (Key) {
1009    case Action::InputClass:
1010    case Action::BindArchClass:
1011      llvm_unreachable("Invalid tool kind.");
1012    case Action::PreprocessJobClass:
1013      T = new tools::gcc::Preprocess(*this); break;
1014    case Action::PrecompileJobClass:
1015      T = new tools::gcc::Precompile(*this); break;
1016    case Action::AnalyzeJobClass:
1017      T = new tools::Clang(*this); break;
1018    case Action::CompileJobClass:
1019      T = new tools::gcc::Compile(*this); break;
1020    case Action::AssembleJobClass:
1021      T = new tools::gcc::Assemble(*this); break;
1022    case Action::LinkJobClass:
1023      T = new tools::gcc::Link(*this); break;
1024
1025      // This is a bit ungeneric, but the only platform using a driver
1026      // driver is Darwin.
1027    case Action::LipoJobClass:
1028      T = new tools::darwin::Lipo(*this); break;
1029    case Action::DsymutilJobClass:
1030      T = new tools::darwin::Dsymutil(*this); break;
1031    case Action::VerifyJobClass:
1032      T = new tools::darwin::VerifyDebug(*this); break;
1033    }
1034  }
1035
1036  return *T;
1037}
1038
1039bool Generic_GCC::IsUnwindTablesDefault() const {
1040  // FIXME: Gross; we should probably have some separate target
1041  // definition, possibly even reusing the one in clang.
1042  return getArchName() == "x86_64";
1043}
1044
1045const char *Generic_GCC::GetDefaultRelocationModel() const {
1046  return "static";
1047}
1048
1049const char *Generic_GCC::GetForcedPicModel() const {
1050  return 0;
1051}
1052
1053/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1054/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1055/// Currently does not support anything else but compilation.
1056
1057TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple)
1058  : ToolChain(Host, Triple) {
1059  // Path mangling to find libexec
1060  std::string Path(getDriver().Dir);
1061
1062  Path += "/../libexec";
1063  getProgramPaths().push_back(Path);
1064}
1065
1066TCEToolChain::~TCEToolChain() {
1067  for (llvm::DenseMap<unsigned, Tool*>::iterator
1068           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1069      delete it->second;
1070}
1071
1072bool TCEToolChain::IsMathErrnoDefault() const {
1073  return true;
1074}
1075
1076bool TCEToolChain::IsUnwindTablesDefault() const {
1077  return false;
1078}
1079
1080const char *TCEToolChain::GetDefaultRelocationModel() const {
1081  return "static";
1082}
1083
1084const char *TCEToolChain::GetForcedPicModel() const {
1085  return 0;
1086}
1087
1088Tool &TCEToolChain::SelectTool(const Compilation &C,
1089                            const JobAction &JA,
1090                               const ActionList &Inputs) const {
1091  Action::ActionClass Key;
1092  Key = Action::AnalyzeJobClass;
1093
1094  Tool *&T = Tools[Key];
1095  if (!T) {
1096    switch (Key) {
1097    case Action::PreprocessJobClass:
1098      T = new tools::gcc::Preprocess(*this); break;
1099    case Action::AnalyzeJobClass:
1100      T = new tools::Clang(*this); break;
1101    default:
1102     llvm_unreachable("Unsupported action for TCE target.");
1103    }
1104  }
1105  return *T;
1106}
1107
1108/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1109
1110OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
1111  : Generic_ELF(Host, Triple) {
1112  getFilePaths().push_back(getDriver().Dir + "/../lib");
1113  getFilePaths().push_back("/usr/lib");
1114}
1115
1116Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1117                          const ActionList &Inputs) const {
1118  Action::ActionClass Key;
1119  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1120    Key = Action::AnalyzeJobClass;
1121  else
1122    Key = JA.getKind();
1123
1124  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1125                                             options::OPT_no_integrated_as,
1126                                             IsIntegratedAssemblerDefault());
1127
1128  Tool *&T = Tools[Key];
1129  if (!T) {
1130    switch (Key) {
1131    case Action::AssembleJobClass: {
1132      if (UseIntegratedAs)
1133        T = new tools::ClangAs(*this);
1134      else
1135        T = new tools::openbsd::Assemble(*this);
1136      break;
1137    }
1138    case Action::LinkJobClass:
1139      T = new tools::openbsd::Link(*this); break;
1140    default:
1141      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1142    }
1143  }
1144
1145  return *T;
1146}
1147
1148/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1149
1150FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
1151  : Generic_ELF(Host, Triple) {
1152
1153  // Determine if we are compiling 32-bit code on an x86_64 platform.
1154  bool Lib32 = false;
1155  if (Triple.getArch() == llvm::Triple::x86 &&
1156      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1157        llvm::Triple::x86_64)
1158    Lib32 = true;
1159
1160  if (Triple.getArch() == llvm::Triple::ppc &&
1161      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1162        llvm::Triple::ppc64)
1163    Lib32 = true;
1164
1165  if (Lib32) {
1166    getFilePaths().push_back("/usr/lib32");
1167  } else {
1168    getFilePaths().push_back("/usr/lib");
1169  }
1170}
1171
1172Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1173                          const ActionList &Inputs) const {
1174  Action::ActionClass Key;
1175  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1176    Key = Action::AnalyzeJobClass;
1177  else
1178    Key = JA.getKind();
1179
1180  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1181                                             options::OPT_no_integrated_as,
1182                                             IsIntegratedAssemblerDefault());
1183
1184  Tool *&T = Tools[Key];
1185  if (!T) {
1186    switch (Key) {
1187    case Action::AssembleJobClass:
1188      if (UseIntegratedAs)
1189        T = new tools::ClangAs(*this);
1190      else
1191        T = new tools::freebsd::Assemble(*this);
1192      break;
1193    case Action::LinkJobClass:
1194      T = new tools::freebsd::Link(*this); break;
1195    default:
1196      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1197    }
1198  }
1199
1200  return *T;
1201}
1202
1203/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1204
1205NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
1206               const llvm::Triple& ToolTriple)
1207  : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) {
1208
1209  // Determine if we are compiling 32-bit code on an x86_64 platform.
1210  bool Lib32 = false;
1211  if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
1212      Triple.getArch() == llvm::Triple::x86)
1213    Lib32 = true;
1214
1215  if (getDriver().UseStdLib) {
1216    if (Lib32)
1217      getFilePaths().push_back("=/usr/lib/i386");
1218    else
1219      getFilePaths().push_back("=/usr/lib");
1220  }
1221}
1222
1223Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1224                         const ActionList &Inputs) const {
1225  Action::ActionClass Key;
1226  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1227    Key = Action::AnalyzeJobClass;
1228  else
1229    Key = JA.getKind();
1230
1231  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1232                                             options::OPT_no_integrated_as,
1233                                             IsIntegratedAssemblerDefault());
1234
1235  Tool *&T = Tools[Key];
1236  if (!T) {
1237    switch (Key) {
1238    case Action::AssembleJobClass:
1239      if (UseIntegratedAs)
1240        T = new tools::ClangAs(*this);
1241      else
1242        T = new tools::netbsd::Assemble(*this, ToolTriple);
1243      break;
1244    case Action::LinkJobClass:
1245      T = new tools::netbsd::Link(*this, ToolTriple);
1246      break;
1247    default:
1248      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1249    }
1250  }
1251
1252  return *T;
1253}
1254
1255/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1256
1257Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1258  : Generic_GCC(Host, Triple) {
1259  getFilePaths().push_back(getDriver().Dir + "/../lib");
1260  getFilePaths().push_back("/usr/lib");
1261  getFilePaths().push_back("/usr/gnu/lib");
1262  getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
1263}
1264
1265Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1266                        const ActionList &Inputs) const {
1267  Action::ActionClass Key;
1268  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1269    Key = Action::AnalyzeJobClass;
1270  else
1271    Key = JA.getKind();
1272
1273  Tool *&T = Tools[Key];
1274  if (!T) {
1275    switch (Key) {
1276    case Action::AssembleJobClass:
1277      T = new tools::minix::Assemble(*this); break;
1278    case Action::LinkJobClass:
1279      T = new tools::minix::Link(*this); break;
1280    default:
1281      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1282    }
1283  }
1284
1285  return *T;
1286}
1287
1288/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1289
1290AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1291  : Generic_GCC(Host, Triple) {
1292
1293  getProgramPaths().push_back(getDriver().getInstalledDir());
1294  if (getDriver().getInstalledDir() != getDriver().Dir)
1295    getProgramPaths().push_back(getDriver().Dir);
1296
1297  getFilePaths().push_back(getDriver().Dir + "/../lib");
1298  getFilePaths().push_back("/usr/lib");
1299  getFilePaths().push_back("/usr/sfw/lib");
1300  getFilePaths().push_back("/opt/gcc4/lib");
1301  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1302
1303}
1304
1305Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1306                           const ActionList &Inputs) const {
1307  Action::ActionClass Key;
1308  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1309    Key = Action::AnalyzeJobClass;
1310  else
1311    Key = JA.getKind();
1312
1313  Tool *&T = Tools[Key];
1314  if (!T) {
1315    switch (Key) {
1316    case Action::AssembleJobClass:
1317      T = new tools::auroraux::Assemble(*this); break;
1318    case Action::LinkJobClass:
1319      T = new tools::auroraux::Link(*this); break;
1320    default:
1321      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1322    }
1323  }
1324
1325  return *T;
1326}
1327
1328
1329/// Linux toolchain (very bare-bones at the moment).
1330
1331enum LinuxDistro {
1332  ArchLinux,
1333  DebianLenny,
1334  DebianSqueeze,
1335  DebianWheezy,
1336  Exherbo,
1337  RHEL4,
1338  RHEL5,
1339  RHEL6,
1340  Fedora13,
1341  Fedora14,
1342  Fedora15,
1343  FedoraRawhide,
1344  OpenSuse11_3,
1345  OpenSuse11_4,
1346  OpenSuse12_1,
1347  UbuntuHardy,
1348  UbuntuIntrepid,
1349  UbuntuJaunty,
1350  UbuntuKarmic,
1351  UbuntuLucid,
1352  UbuntuMaverick,
1353  UbuntuNatty,
1354  UbuntuOneiric,
1355  UnknownDistro
1356};
1357
1358static bool IsRedhat(enum LinuxDistro Distro) {
1359  return Distro == Fedora13 || Distro == Fedora14 ||
1360         Distro == Fedora15 || Distro == FedoraRawhide ||
1361         Distro == RHEL4 || Distro == RHEL5 || Distro == RHEL6;
1362}
1363
1364static bool IsOpenSuse(enum LinuxDistro Distro) {
1365  return Distro == OpenSuse11_3 || Distro == OpenSuse11_4 ||
1366         Distro == OpenSuse12_1;
1367}
1368
1369static bool IsDebian(enum LinuxDistro Distro) {
1370  return Distro == DebianLenny || Distro == DebianSqueeze ||
1371         Distro == DebianWheezy;
1372}
1373
1374static bool IsUbuntu(enum LinuxDistro Distro) {
1375  return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1376         Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1377         Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1378         Distro == UbuntuNatty  || Distro == UbuntuOneiric;
1379}
1380
1381// FIXME: This should be deleted. We should assume a multilib environment, and
1382// fallback gracefully if any parts of it are absent.
1383static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) {
1384  if (Arch == llvm::Triple::x86_64) {
1385    bool Exists;
1386    if (Distro == Exherbo &&
1387        (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists))
1388      return false;
1389  }
1390
1391  return true;
1392}
1393
1394static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1395  llvm::OwningPtr<llvm::MemoryBuffer> File;
1396  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1397    StringRef Data = File.get()->getBuffer();
1398    SmallVector<StringRef, 8> Lines;
1399    Data.split(Lines, "\n");
1400    for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1401      if (Lines[i] == "DISTRIB_CODENAME=hardy")
1402        return UbuntuHardy;
1403      else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1404        return UbuntuIntrepid;
1405      else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1406        return UbuntuJaunty;
1407      else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1408        return UbuntuKarmic;
1409      else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1410        return UbuntuLucid;
1411      else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1412        return UbuntuMaverick;
1413      else if (Lines[i] == "DISTRIB_CODENAME=natty")
1414        return UbuntuNatty;
1415      else if (Lines[i] == "DISTRIB_CODENAME=oneiric")
1416        return UbuntuOneiric;
1417    }
1418    return UnknownDistro;
1419  }
1420
1421  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1422    StringRef Data = File.get()->getBuffer();
1423    if (Data.startswith("Fedora release 15"))
1424      return Fedora15;
1425    else if (Data.startswith("Fedora release 14"))
1426      return Fedora14;
1427    else if (Data.startswith("Fedora release 13"))
1428      return Fedora13;
1429    else if (Data.startswith("Fedora release") &&
1430             Data.find("Rawhide") != StringRef::npos)
1431      return FedoraRawhide;
1432    else if (Data.startswith("Red Hat Enterprise Linux") &&
1433             Data.find("release 6") != StringRef::npos)
1434      return RHEL6;
1435    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1436	      Data.startswith("CentOS")) &&
1437             Data.find("release 5") != StringRef::npos)
1438      return RHEL5;
1439    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1440	      Data.startswith("CentOS")) &&
1441             Data.find("release 4") != StringRef::npos)
1442      return RHEL4;
1443    return UnknownDistro;
1444  }
1445
1446  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1447    StringRef Data = File.get()->getBuffer();
1448    if (Data[0] == '5')
1449      return DebianLenny;
1450    else if (Data.startswith("squeeze/sid"))
1451      return DebianSqueeze;
1452    else if (Data.startswith("wheezy/sid"))
1453      return DebianWheezy;
1454    return UnknownDistro;
1455  }
1456
1457  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1458    StringRef Data = File.get()->getBuffer();
1459    if (Data.startswith("openSUSE 11.3"))
1460      return OpenSuse11_3;
1461    else if (Data.startswith("openSUSE 11.4"))
1462      return OpenSuse11_4;
1463    else if (Data.startswith("openSUSE 12.1"))
1464      return OpenSuse12_1;
1465    return UnknownDistro;
1466  }
1467
1468  bool Exists;
1469  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1470    return Exherbo;
1471
1472  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1473    return ArchLinux;
1474
1475  return UnknownDistro;
1476}
1477
1478/// \brief Trivial helper function to simplify code checking path existence.
1479static bool PathExists(StringRef Path) {
1480  bool Exists;
1481  if (!llvm::sys::fs::exists(Path, Exists))
1482    return Exists;
1483  return false;
1484}
1485
1486namespace {
1487/// \brief This is a class to find a viable GCC installation for Clang to use.
1488///
1489/// This class tries to find a GCC installation on the system, and report
1490/// information about it. It starts from the host information provided to the
1491/// Driver, and has logic for fuzzing that where appropriate.
1492class GCCInstallationDetector {
1493  /// \brief Struct to store and manipulate GCC versions.
1494  ///
1495  /// We rely on assumptions about the form and structure of GCC version
1496  /// numbers: they consist of at most three '.'-separated components, and each
1497  /// component is a non-negative integer.
1498  struct GCCVersion {
1499    unsigned Major, Minor, Patch;
1500
1501    static GCCVersion Parse(StringRef VersionText) {
1502      const GCCVersion BadVersion = {};
1503      std::pair<StringRef, StringRef> First = VersionText.split('.');
1504      std::pair<StringRef, StringRef> Second = First.second.split('.');
1505
1506      GCCVersion GoodVersion = {};
1507      if (First.first.getAsInteger(10, GoodVersion.Major))
1508        return BadVersion;
1509      if (Second.first.getAsInteger(10, GoodVersion.Minor))
1510        return BadVersion;
1511      if (!Second.first.empty())
1512        if (Second.first.getAsInteger(10, GoodVersion.Patch))
1513          return BadVersion;
1514      return GoodVersion;
1515    }
1516
1517    bool operator<(const GCCVersion &RHS) const {
1518      if (Major < RHS.Major) return true;
1519      if (Major > RHS.Major) return false;
1520      if (Minor < RHS.Minor) return true;
1521      if (Minor > RHS.Minor) return false;
1522      return Patch < RHS.Patch;
1523    }
1524    bool operator>(const GCCVersion &RHS) const { return RHS < *this; }
1525    bool operator<=(const GCCVersion &RHS) const { return !(*this > RHS); }
1526    bool operator>=(const GCCVersion &RHS) const { return !(*this < RHS); }
1527  };
1528
1529  bool IsValid;
1530  std::string GccTriple;
1531
1532  // FIXME: These might be better as path objects.
1533  std::string GccInstallPath;
1534  std::string GccParentLibPath;
1535
1536  llvm::SmallString<128> CxxIncludeRoot;
1537
1538public:
1539  /// \brief Construct a GCCInstallationDetector from the driver.
1540  ///
1541  /// This performs all of the autodetection and sets up the various paths.
1542  /// Once constructed, a GCCInstallation is esentially immutable.
1543  GCCInstallationDetector(const Driver &D)
1544    : IsValid(false),
1545      GccTriple(D.DefaultHostTriple),
1546      CxxIncludeRoot(CXX_INCLUDE_ROOT) {
1547    // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but
1548    // avoids adding yet another option to configure/cmake.
1549    // It would probably be cleaner to break it in two variables
1550    // CXX_GCC_ROOT with just /foo/bar
1551    // CXX_GCC_VER with 4.5.2
1552    // Then we would have
1553    // CXX_INCLUDE_ROOT = CXX_GCC_ROOT/include/c++/CXX_GCC_VER
1554    // and this function would return
1555    // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER
1556    if (CxxIncludeRoot != "") {
1557      // This is of the form /foo/bar/include/c++/4.5.2/
1558      if (CxxIncludeRoot.back() == '/')
1559        llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the /
1560      StringRef Version = llvm::sys::path::filename(CxxIncludeRoot);
1561      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version
1562      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++
1563      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include
1564      GccInstallPath = CxxIncludeRoot.str();
1565      GccInstallPath.append("/lib/gcc/");
1566      GccInstallPath.append(CXX_INCLUDE_ARCH);
1567      GccInstallPath.append("/");
1568      GccInstallPath.append(Version);
1569      GccParentLibPath = GccInstallPath + "/../../../..";
1570      IsValid = true;
1571      return;
1572    }
1573
1574    llvm::Triple::ArchType HostArch = llvm::Triple(GccTriple).getArch();
1575    // The library directories which may contain GCC installations.
1576    SmallVector<StringRef, 4> CandidateLibDirs;
1577    // The compatible GCC triples for this particular architecture.
1578    SmallVector<StringRef, 10> CandidateTriples;
1579    CollectLibDirsAndTriples(HostArch, CandidateLibDirs, CandidateTriples);
1580
1581    // Always include the default host triple as the final fallback if no
1582    // specific triple is detected.
1583    CandidateTriples.push_back(D.DefaultHostTriple);
1584
1585    // Compute the set of prefixes for our search.
1586    SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1587                                         D.PrefixDirs.end());
1588    Prefixes.push_back(D.SysRoot);
1589    Prefixes.push_back(D.SysRoot + "/usr");
1590
1591    // Loop over the various components which exist and select the best GCC
1592    // installation available. GCC installs are ranked by version number.
1593    static const GCCVersion MinVersion = { 4, 1, 1 };
1594    GCCVersion BestVersion = {};
1595    for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1596      if (!PathExists(Prefixes[i]))
1597        continue;
1598      for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1599        const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1600        if (!PathExists(LibDir))
1601          continue;
1602        for (unsigned k = 0, ke = CandidateTriples.size(); k < ke; ++k) {
1603          StringRef CandidateTriple = CandidateTriples[k];
1604          const std::string TripleDir = LibDir + "/" + CandidateTriple.str();
1605          if (!PathExists(TripleDir))
1606            continue;
1607
1608          // There are various different suffixes on the triple directory we
1609          // check for. We also record what is necessary to walk from each back
1610          // up to the lib directory.
1611          const std::string Suffixes[] = { "", "/gcc/" + CandidateTriple.str(),
1612                                           "/gcc/i686-linux-gnu" };
1613          const std::string InstallSuffixes[] = { "/../../..", "/../../../..",
1614                                                  "/../../../.." };
1615          const unsigned NumSuffixes = (llvm::array_lengthof(Suffixes) -
1616                                        (CandidateTriple != "i386-linux-gnu"));
1617          for (unsigned l = 0; l < NumSuffixes; ++l) {
1618            StringRef Suffix = Suffixes[l];
1619            llvm::error_code EC;
1620            for (llvm::sys::fs::directory_iterator LI(TripleDir + Suffix, EC),
1621                                                   LE;
1622                 !EC && LI != LE; LI = LI.increment(EC)) {
1623              StringRef VersionText = llvm::sys::path::filename(LI->path());
1624              GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1625              if (CandidateVersion < MinVersion)
1626                continue;
1627              if (CandidateVersion <= BestVersion)
1628                continue;
1629              if (!PathExists(LI->path() + "/crtbegin.o"))
1630                continue;
1631
1632              BestVersion = CandidateVersion;
1633              GccTriple = CandidateTriple.str();
1634              // FIXME: We hack together the directory name here instead of
1635              // using LI to ensure stable path separators across Windows and
1636              // Linux.
1637              GccInstallPath = (TripleDir + Suffixes[l] + "/" +
1638                                VersionText.str());
1639              GccParentLibPath = GccInstallPath + InstallSuffixes[l];
1640              IsValid = true;
1641            }
1642          }
1643        }
1644      }
1645    }
1646  }
1647
1648  /// \brief Check whether we detected a valid GCC install.
1649  bool isValid() const { return IsValid; }
1650
1651  /// \brief Get the GCC triple for the detected install.
1652  const std::string &getTriple() const { return GccTriple; }
1653
1654  /// \brief Get the detected GCC installation path.
1655  const std::string &getInstallPath() const { return GccInstallPath; }
1656
1657  /// \brief Get the detected GCC parent lib path.
1658  const std::string &getParentLibPath() const { return GccParentLibPath; }
1659
1660private:
1661  static void CollectLibDirsAndTriples(llvm::Triple::ArchType HostArch,
1662                                       SmallVectorImpl<StringRef> &LibDirs,
1663                                       SmallVectorImpl<StringRef> &Triples) {
1664    if (HostArch == llvm::Triple::arm || HostArch == llvm::Triple::thumb) {
1665      static const char *const ARMLibDirs[] = { "/lib/gcc" };
1666      static const char *const ARMTriples[] = { "arm-linux-gnueabi" };
1667      LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1668      Triples.append(ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1669    } else if (HostArch == llvm::Triple::x86_64) {
1670      static const char *const X86_64LibDirs[] = {
1671        "/lib64/gcc", "/lib/gcc", "/lib64", "/lib"
1672      };
1673      static const char *const X86_64Triples[] = {
1674        "x86_64-linux-gnu",
1675        "x86_64-unknown-linux-gnu",
1676        "x86_64-pc-linux-gnu",
1677        "x86_64-redhat-linux6E",
1678        "x86_64-redhat-linux",
1679        "x86_64-suse-linux",
1680        "x86_64-manbo-linux-gnu",
1681        "x86_64-linux-gnu",
1682        "x86_64-slackware-linux"
1683      };
1684      LibDirs.append(X86_64LibDirs,
1685                     X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1686      Triples.append(X86_64Triples,
1687                     X86_64Triples + llvm::array_lengthof(X86_64Triples));
1688    } else if (HostArch == llvm::Triple::x86) {
1689      static const char *const X86LibDirs[] = {
1690        "/lib32/gcc", "/lib/gcc", "/lib32", "/lib"
1691      };
1692      static const char *const X86Triples[] = {
1693        "i686-linux-gnu",
1694        "i386-linux-gnu",
1695        "i686-pc-linux-gnu",
1696        "i486-linux-gnu",
1697        "i686-redhat-linux",
1698        "i586-suse-linux",
1699        "i486-slackware-linux"
1700      };
1701      LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1702      Triples.append(X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1703    } else if (HostArch == llvm::Triple::ppc) {
1704      static const char *const PPCLibDirs[] = {
1705        "/lib32/gcc", "/lib/gcc", "/lib32", "/lib"
1706      };
1707      static const char *const PPCTriples[] = {
1708        "powerpc-linux-gnu",
1709        "powerpc-unknown-linux-gnu"
1710      };
1711      LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1712      Triples.append(PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1713    } else if (HostArch == llvm::Triple::ppc64) {
1714      static const char *const PPC64LibDirs[] = {
1715        "/lib64/gcc", "/lib/gcc", "/lib64", "/lib"
1716      };
1717      static const char *const PPC64Triples[] = {
1718        "powerpc64-unknown-linux-gnu"
1719      };
1720      LibDirs.append(PPC64LibDirs,
1721                     PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1722      Triples.append(PPC64Triples,
1723                     PPC64Triples + llvm::array_lengthof(PPC64Triples));
1724    }
1725  }
1726};
1727}
1728
1729static void addPathIfExists(const std::string &Path,
1730                            ToolChain::path_list &Paths) {
1731  if (PathExists(Path)) Paths.push_back(Path);
1732}
1733
1734Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1735  : Generic_ELF(Host, Triple) {
1736  llvm::Triple::ArchType Arch =
1737    llvm::Triple(getDriver().DefaultHostTriple).getArch();
1738  const std::string &SysRoot = getDriver().SysRoot;
1739  GCCInstallationDetector GCCInstallation(getDriver());
1740
1741  // OpenSuse stores the linker with the compiler, add that to the search
1742  // path.
1743  ToolChain::path_list &PPaths = getProgramPaths();
1744  PPaths.push_back(GCCInstallation.getParentLibPath() + "/../" +
1745                   GCCInstallation.getTriple() + "/bin");
1746
1747  Linker = GetProgramPath("ld");
1748
1749  LinuxDistro Distro = DetectLinuxDistro(Arch);
1750
1751  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
1752    ExtraOpts.push_back("-z");
1753    ExtraOpts.push_back("relro");
1754  }
1755
1756  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1757    ExtraOpts.push_back("-X");
1758
1759  if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro == UbuntuMaverick ||
1760      Distro == UbuntuNatty || Distro == UbuntuOneiric)
1761    ExtraOpts.push_back("--hash-style=gnu");
1762
1763  if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
1764      Distro == UbuntuJaunty || Distro == UbuntuKarmic)
1765    ExtraOpts.push_back("--hash-style=both");
1766
1767  if (IsRedhat(Distro))
1768    ExtraOpts.push_back("--no-add-needed");
1769
1770  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
1771      IsOpenSuse(Distro) ||
1772      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
1773      Distro == UbuntuLucid ||
1774      Distro == UbuntuMaverick || Distro == UbuntuKarmic ||
1775      Distro == UbuntuNatty || Distro == UbuntuOneiric)
1776    ExtraOpts.push_back("--build-id");
1777
1778  if (IsOpenSuse(Distro))
1779    ExtraOpts.push_back("--enable-new-dtags");
1780
1781  // The selection of paths to try here is designed to match the patterns which
1782  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
1783  // This was determined by running GCC in a fake filesystem, creating all
1784  // possible permutations of these directories, and seeing which ones it added
1785  // to the link paths.
1786  path_list &Paths = getFilePaths();
1787  const bool Is32Bits = (getArch() == llvm::Triple::x86 ||
1788                         getArch() == llvm::Triple::ppc);
1789
1790  const std::string Suffix32 = Arch == llvm::Triple::x86_64 ? "/32" : "";
1791  const std::string Suffix64 = Arch == llvm::Triple::x86_64 ? "" : "/64";
1792  const std::string Suffix = Is32Bits ? Suffix32 : Suffix64;
1793  const std::string Multilib = Is32Bits ? "lib32" : "lib64";
1794
1795  // FIXME: Because we add paths only when they exist on the system, I think we
1796  // should remove the concept of 'HasMultilib'. It's more likely to break the
1797  // behavior than to preserve any useful invariant on the system.
1798  if (HasMultilib(Arch, Distro)) {
1799    // Add the multilib suffixed paths.
1800    if (GCCInstallation.isValid()) {
1801      const std::string &LibPath = GCCInstallation.getParentLibPath();
1802      const std::string &GccTriple = GCCInstallation.getTriple();
1803      // FIXME: This OpenSuse-specific path shouldn't be needed any more, but
1804      // I don't want to remove it without finding someone to test.
1805      if (IsOpenSuse(Distro) && Is32Bits)
1806        Paths.push_back(LibPath + "/../" + GccTriple + "/lib/../lib");
1807
1808      addPathIfExists(GCCInstallation.getInstallPath() + Suffix, Paths);
1809      addPathIfExists(LibPath + "/../" + GccTriple + "/lib/../" + Multilib,
1810                      Paths);
1811      addPathIfExists(LibPath + "/../" + Multilib, Paths);
1812    }
1813    addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
1814    addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
1815  }
1816
1817  // Add the non-multiplib suffixed paths (if potentially different).
1818  if (GCCInstallation.isValid()) {
1819    const std::string &LibPath = GCCInstallation.getParentLibPath();
1820    const std::string &GccTriple = GCCInstallation.getTriple();
1821    if (!Suffix.empty() || !HasMultilib(Arch, Distro))
1822      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
1823    addPathIfExists(LibPath + "/../" + GccTriple + "/lib", Paths);
1824    addPathIfExists(LibPath, Paths);
1825  }
1826  addPathIfExists(SysRoot + "/lib", Paths);
1827  addPathIfExists(SysRoot + "/usr/lib", Paths);
1828
1829  if (GCCInstallation.isValid() && Arch == getArch() && IsUbuntu(Distro))
1830    Paths.push_back(SysRoot + "/usr/lib/" + GCCInstallation.getTriple());
1831}
1832
1833bool Linux::HasNativeLLVMSupport() const {
1834  return true;
1835}
1836
1837Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
1838                        const ActionList &Inputs) const {
1839  Action::ActionClass Key;
1840  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1841    Key = Action::AnalyzeJobClass;
1842  else
1843    Key = JA.getKind();
1844
1845  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1846                                             options::OPT_no_integrated_as,
1847                                             IsIntegratedAssemblerDefault());
1848
1849  Tool *&T = Tools[Key];
1850  if (!T) {
1851    switch (Key) {
1852    case Action::AssembleJobClass:
1853      if (UseIntegratedAs)
1854        T = new tools::ClangAs(*this);
1855      else
1856        T = new tools::linuxtools::Assemble(*this);
1857      break;
1858    case Action::LinkJobClass:
1859      T = new tools::linuxtools::Link(*this); break;
1860    default:
1861      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1862    }
1863  }
1864
1865  return *T;
1866}
1867
1868/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
1869
1870DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
1871  : Generic_ELF(Host, Triple) {
1872
1873  // Path mangling to find libexec
1874  getProgramPaths().push_back(getDriver().getInstalledDir());
1875  if (getDriver().getInstalledDir() != getDriver().Dir)
1876    getProgramPaths().push_back(getDriver().Dir);
1877
1878  getFilePaths().push_back(getDriver().Dir + "/../lib");
1879  getFilePaths().push_back("/usr/lib");
1880  getFilePaths().push_back("/usr/lib/gcc41");
1881}
1882
1883Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
1884                            const ActionList &Inputs) const {
1885  Action::ActionClass Key;
1886  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1887    Key = Action::AnalyzeJobClass;
1888  else
1889    Key = JA.getKind();
1890
1891  Tool *&T = Tools[Key];
1892  if (!T) {
1893    switch (Key) {
1894    case Action::AssembleJobClass:
1895      T = new tools::dragonfly::Assemble(*this); break;
1896    case Action::LinkJobClass:
1897      T = new tools::dragonfly::Link(*this); break;
1898    default:
1899      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1900    }
1901  }
1902
1903  return *T;
1904}
1905
1906Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
1907  : ToolChain(Host, Triple) {
1908}
1909
1910Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
1911                          const ActionList &Inputs) const {
1912  Action::ActionClass Key;
1913  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1914    Key = Action::AnalyzeJobClass;
1915  else
1916    Key = JA.getKind();
1917
1918  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1919                                             options::OPT_no_integrated_as,
1920                                             IsIntegratedAssemblerDefault());
1921
1922  Tool *&T = Tools[Key];
1923  if (!T) {
1924    switch (Key) {
1925    case Action::InputClass:
1926    case Action::BindArchClass:
1927    case Action::LipoJobClass:
1928    case Action::DsymutilJobClass:
1929    case Action::VerifyJobClass:
1930      llvm_unreachable("Invalid tool kind.");
1931    case Action::PreprocessJobClass:
1932    case Action::PrecompileJobClass:
1933    case Action::AnalyzeJobClass:
1934    case Action::CompileJobClass:
1935      T = new tools::Clang(*this); break;
1936    case Action::AssembleJobClass:
1937      if (!UseIntegratedAs && getTriple().getEnvironment() == llvm::Triple::MachO)
1938        T = new tools::darwin::Assemble(*this);
1939      else
1940        T = new tools::ClangAs(*this);
1941      break;
1942    case Action::LinkJobClass:
1943      T = new tools::visualstudio::Link(*this); break;
1944    }
1945  }
1946
1947  return *T;
1948}
1949
1950bool Windows::IsIntegratedAssemblerDefault() const {
1951  return true;
1952}
1953
1954bool Windows::IsUnwindTablesDefault() const {
1955  // FIXME: Gross; we should probably have some separate target
1956  // definition, possibly even reusing the one in clang.
1957  return getArchName() == "x86_64";
1958}
1959
1960const char *Windows::GetDefaultRelocationModel() const {
1961  return "static";
1962}
1963
1964const char *Windows::GetForcedPicModel() const {
1965  if (getArchName() == "x86_64")
1966    return "pic";
1967  return 0;
1968}
1969