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