ToolChains.cpp revision 9d609f2b0dd604879f8b284ded1f14ba300e8070
1//===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ToolChains.h"
11
12#include "clang/Driver/Arg.h"
13#include "clang/Driver/ArgList.h"
14#include "clang/Driver/Compilation.h"
15#include "clang/Driver/Driver.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/HostInfo.h"
18#include "clang/Driver/OptTable.h"
19#include "clang/Driver/Option.h"
20#include "clang/Driver/Options.h"
21#include "clang/Basic/Version.h"
22
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/system_error.h"
31
32#include <cstdlib> // ::getenv
33
34using namespace clang::driver;
35using namespace clang::driver::toolchains;
36
37/// Darwin - Darwin tool chain for i386 and x86_64.
38
39Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
40  : ToolChain(Host, Triple), TargetInitialized(false)
41{
42  // Compute the initial Darwin version based on the host.
43  bool HadExtra;
44  std::string OSName = Triple.getOSName();
45  if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
46                                 DarwinVersion[0], DarwinVersion[1],
47                                 DarwinVersion[2], HadExtra))
48    getDriver().Diag(clang::diag::err_drv_invalid_darwin_version) << OSName;
49
50  llvm::raw_string_ostream(MacosxVersionMin)
51    << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
52    << DarwinVersion[1];
53}
54
55types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
56  types::ID Ty = types::lookupTypeForExtension(Ext);
57
58  // Darwin always preprocesses assembly files (unless -x is used explicitly).
59  if (Ty == types::TY_PP_Asm)
60    return types::TY_Asm;
61
62  return Ty;
63}
64
65bool Darwin::HasNativeLLVMSupport() const {
66  return true;
67}
68
69// FIXME: Can we tablegen this?
70static const char *GetArmArchForMArch(llvm::StringRef Value) {
71  if (Value == "armv6k")
72    return "armv6";
73
74  if (Value == "armv5tej")
75    return "armv5";
76
77  if (Value == "xscale")
78    return "xscale";
79
80  if (Value == "armv4t")
81    return "armv4t";
82
83  if (Value == "armv7" || Value == "armv7-a" || Value == "armv7-r" ||
84      Value == "armv7-m" || Value == "armv7a" || Value == "armv7r" ||
85      Value == "armv7m")
86    return "armv7";
87
88  return 0;
89}
90
91// FIXME: Can we tablegen this?
92static const char *GetArmArchForMCpu(llvm::StringRef Value) {
93  if (Value == "arm10tdmi" || Value == "arm1020t" || Value == "arm9e" ||
94      Value == "arm946e-s" || Value == "arm966e-s" ||
95      Value == "arm968e-s" || Value == "arm10e" ||
96      Value == "arm1020e" || Value == "arm1022e" || Value == "arm926ej-s" ||
97      Value == "arm1026ej-s")
98    return "armv5";
99
100  if (Value == "xscale")
101    return "xscale";
102
103  if (Value == "arm1136j-s" || Value == "arm1136jf-s" ||
104      Value == "arm1176jz-s" || Value == "arm1176jzf-s" ||
105      Value == "cortex-m0" )
106    return "armv6";
107
108  if (Value == "cortex-a8" || Value == "cortex-r4" || Value == "cortex-m3")
109    return "armv7";
110
111  return 0;
112}
113
114llvm::StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
115  switch (getTriple().getArch()) {
116  default:
117    return getArchName();
118
119  case llvm::Triple::thumb:
120  case llvm::Triple::arm: {
121    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
122      if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
123        return Arch;
124
125    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
126      if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
127        return Arch;
128
129    return "arm";
130  }
131  }
132}
133
134Darwin::~Darwin() {
135  // Free tool implementations.
136  for (llvm::DenseMap<unsigned, Tool*>::iterator
137         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
138    delete it->second;
139}
140
141std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args) const {
142  llvm::Triple Triple(ComputeLLVMTriple(Args));
143
144  // If the target isn't initialized (e.g., an unknown Darwin platform, return
145  // the default triple).
146  if (!isTargetInitialized())
147    return Triple.getTriple();
148
149  unsigned Version[3];
150  getTargetVersion(Version);
151
152  llvm::SmallString<16> Str;
153  llvm::raw_svector_ostream(Str)
154    << (isTargetIPhoneOS() ? "ios" : "macosx")
155    << Version[0] << "." << Version[1] << "." << Version[2];
156  Triple.setOSName(Str.str());
157
158  return Triple.getTriple();
159}
160
161Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
162                         const ActionList &Inputs) const {
163  Action::ActionClass Key;
164
165  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
166    // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
167    if (Inputs.size() == 1 &&
168        types::isCXX(Inputs[0]->getType()) &&
169        getTriple().getOS() == llvm::Triple::Darwin &&
170        getTriple().getArch() == llvm::Triple::x86 &&
171        C.getArgs().getLastArg(options::OPT_fapple_kext))
172      Key = JA.getKind();
173    else
174      Key = Action::AnalyzeJobClass;
175  } else
176    Key = JA.getKind();
177
178  // FIXME: This doesn't belong here, but ideally we will support static soon
179  // anyway.
180  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
181                    C.getArgs().hasArg(options::OPT_static) ||
182                    C.getArgs().hasArg(options::OPT_fapple_kext));
183  bool IsIADefault = IsIntegratedAssemblerDefault() && !HasStatic;
184  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
185                                             options::OPT_no_integrated_as,
186                                             IsIADefault);
187
188  Tool *&T = Tools[Key];
189  if (!T) {
190    switch (Key) {
191    case Action::InputClass:
192    case Action::BindArchClass:
193      assert(0 && "Invalid tool kind.");
194    case Action::PreprocessJobClass:
195      T = new tools::darwin::Preprocess(*this); break;
196    case Action::AnalyzeJobClass:
197      T = new tools::Clang(*this); break;
198    case Action::PrecompileJobClass:
199    case Action::CompileJobClass:
200      T = new tools::darwin::Compile(*this); break;
201    case Action::AssembleJobClass: {
202      if (UseIntegratedAs)
203        T = new tools::ClangAs(*this);
204      else
205        T = new tools::darwin::Assemble(*this);
206      break;
207    }
208    case Action::LinkJobClass:
209      T = new tools::darwin::Link(*this); break;
210    case Action::LipoJobClass:
211      T = new tools::darwin::Lipo(*this); break;
212    case Action::DsymutilJobClass:
213      T = new tools::darwin::Dsymutil(*this); break;
214    }
215  }
216
217  return *T;
218}
219
220
221DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
222  : Darwin(Host, Triple)
223{
224  std::string UsrPrefix = "llvm-gcc-4.2/";
225
226  getProgramPaths().push_back(getDriver().getInstalledDir());
227  if (getDriver().getInstalledDir() != getDriver().Dir)
228    getProgramPaths().push_back(getDriver().Dir);
229
230  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
231  getProgramPaths().push_back(getDriver().getInstalledDir());
232  if (getDriver().getInstalledDir() != getDriver().Dir)
233    getProgramPaths().push_back(getDriver().Dir);
234
235  // For fallback, we need to know how to find the GCC cc1 executables, so we
236  // also add the GCC libexec paths. This is legacy code that can be removed
237  // once fallback is no longer useful.
238  std::string ToolChainDir = "i686-apple-darwin";
239  ToolChainDir += llvm::utostr(DarwinVersion[0]);
240  ToolChainDir += "/4.2.1";
241
242  std::string Path = getDriver().Dir;
243  Path += "/../" + UsrPrefix + "libexec/gcc/";
244  Path += ToolChainDir;
245  getProgramPaths().push_back(Path);
246
247  Path = "/usr/" + UsrPrefix + "libexec/gcc/";
248  Path += ToolChainDir;
249  getProgramPaths().push_back(Path);
250}
251
252void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args,
253                                       ArgStringList &CmdArgs) const {
254  // The Clang toolchain uses explicit paths for internal libraries.
255
256  // Unfortunately, we still might depend on a few of the libraries that are
257  // only available in the gcc library directory (in particular
258  // libstdc++.dylib). For now, hardcode the path to the known install location.
259  llvm::sys::Path P(getDriver().Dir);
260  P.eraseComponent(); // .../usr/bin -> ../usr
261  P.appendComponent("lib");
262  P.appendComponent("gcc");
263  switch (getTriple().getArch()) {
264  default:
265    assert(0 && "Invalid Darwin arch!");
266  case llvm::Triple::x86:
267  case llvm::Triple::x86_64:
268    P.appendComponent("i686-apple-darwin10");
269    break;
270  case llvm::Triple::arm:
271  case llvm::Triple::thumb:
272    P.appendComponent("arm-apple-darwin10");
273    break;
274  case llvm::Triple::ppc:
275  case llvm::Triple::ppc64:
276    P.appendComponent("powerpc-apple-darwin10");
277    break;
278  }
279  P.appendComponent("4.2.1");
280
281  // Determine the arch specific GCC subdirectory.
282  const char *ArchSpecificDir = 0;
283  switch (getTriple().getArch()) {
284  default:
285    break;
286  case llvm::Triple::arm:
287  case llvm::Triple::thumb: {
288    std::string Triple = ComputeLLVMTriple(Args);
289    llvm::StringRef TripleStr = Triple;
290    if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5"))
291      ArchSpecificDir = "v5";
292    else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6"))
293      ArchSpecificDir = "v6";
294    else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7"))
295      ArchSpecificDir = "v7";
296    break;
297  }
298  case llvm::Triple::ppc64:
299    ArchSpecificDir = "ppc64";
300    break;
301  case llvm::Triple::x86_64:
302    ArchSpecificDir = "x86_64";
303    break;
304  }
305
306  if (ArchSpecificDir) {
307    P.appendComponent(ArchSpecificDir);
308    bool Exists;
309    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
310      CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
311    P.eraseComponent();
312  }
313
314  bool Exists;
315  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
316    CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
317}
318
319void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
320                                        ArgStringList &CmdArgs) const {
321  // Darwin doesn't support real static executables, don't link any runtime
322  // libraries with -static.
323  if (Args.hasArg(options::OPT_static))
324    return;
325
326  // Reject -static-libgcc for now, we can deal with this when and if someone
327  // cares. This is useful in situations where someone wants to statically link
328  // something like libstdc++, and needs its runtime support routines.
329  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
330    getDriver().Diag(clang::diag::err_drv_unsupported_opt)
331      << A->getAsString(Args);
332    return;
333  }
334
335  // Otherwise link libSystem, then the dynamic runtime library, and finally any
336  // target specific static runtime library.
337  CmdArgs.push_back("-lSystem");
338
339  // Select the dynamic runtime library and the target specific static library.
340  const char *DarwinStaticLib = 0;
341  if (isTargetIPhoneOS()) {
342    CmdArgs.push_back("-lgcc_s.1");
343
344    // We currently always need a static runtime library for iOS.
345    DarwinStaticLib = "libclang_rt.ios.a";
346  } else {
347    // The dynamic runtime library was merged with libSystem for 10.6 and
348    // beyond; only 10.4 and 10.5 need an additional runtime library.
349    if (isMacosxVersionLT(10, 5))
350      CmdArgs.push_back("-lgcc_s.10.4");
351    else if (isMacosxVersionLT(10, 6))
352      CmdArgs.push_back("-lgcc_s.10.5");
353
354    // For OS X, we thought we would only need a static runtime library when
355    // targeting 10.4, to provide versions of the static functions which were
356    // omitted from 10.4.dylib.
357    //
358    // Unfortunately, that turned out to not be true, because Darwin system
359    // headers can still use eprintf on i386, and it is not exported from
360    // libSystem. Therefore, we still must provide a runtime library just for
361    // the tiny tiny handful of projects that *might* use that symbol.
362    if (isMacosxVersionLT(10, 5)) {
363      DarwinStaticLib = "libclang_rt.10.4.a";
364    } else {
365      if (getTriple().getArch() == llvm::Triple::x86)
366        DarwinStaticLib = "libclang_rt.eprintf.a";
367    }
368  }
369
370  /// Add the target specific static library, if needed.
371  if (DarwinStaticLib) {
372    llvm::sys::Path P(getDriver().ResourceDir);
373    P.appendComponent("lib");
374    P.appendComponent("darwin");
375    P.appendComponent(DarwinStaticLib);
376
377    // For now, allow missing resource libraries to support developers who may
378    // not have compiler-rt checked out or integrated into their build.
379    bool Exists;
380    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
381      CmdArgs.push_back(Args.MakeArgString(P.str()));
382  }
383}
384
385void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
386  const OptTable &Opts = getDriver().getOpts();
387
388  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
389  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
390  Arg *iOSSimVersion = Args.getLastArg(
391    options::OPT_mios_simulator_version_min_EQ);
392  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
393    getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
394          << OSXVersion->getAsString(Args)
395          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
396    iOSVersion = iOSSimVersion = 0;
397  } else if (iOSVersion && iOSSimVersion) {
398    getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
399          << iOSVersion->getAsString(Args)
400          << iOSSimVersion->getAsString(Args);
401    iOSSimVersion = 0;
402  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
403    // If not deployment target was specified on the command line, check for
404    // environment defines.
405    const char *OSXTarget = ::getenv("MACOSX_DEPLOYMENT_TARGET");
406    const char *iOSTarget = ::getenv("IPHONEOS_DEPLOYMENT_TARGET");
407    const char *iOSSimTarget = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET");
408
409    // Ignore empty strings.
410    if (OSXTarget && OSXTarget[0] == '\0')
411      OSXTarget = 0;
412    if (iOSTarget && iOSTarget[0] == '\0')
413      iOSTarget = 0;
414    if (iOSSimTarget && iOSSimTarget[0] == '\0')
415      iOSSimTarget = 0;
416
417    // Handle conflicting deployment targets
418    //
419    // FIXME: Don't hardcode default here.
420
421    // Do not allow conflicts with the iOS simulator target.
422    if (iOSSimTarget && (OSXTarget || iOSTarget)) {
423      getDriver().Diag(clang::diag::err_drv_conflicting_deployment_targets)
424        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
425        << (OSXTarget ? "MACOSX_DEPLOYMENT_TARGET" :
426            "IPHONEOS_DEPLOYMENT_TARGET");
427    }
428
429    // Allow conflicts among OSX and iOS for historical reasons, but choose the
430    // default platform.
431    if (OSXTarget && iOSTarget) {
432      if (getTriple().getArch() == llvm::Triple::arm ||
433          getTriple().getArch() == llvm::Triple::thumb)
434        OSXTarget = 0;
435      else
436        iOSTarget = 0;
437    }
438
439    if (OSXTarget) {
440      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
441      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
442      Args.append(OSXVersion);
443    } else if (iOSTarget) {
444      const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
445      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
446      Args.append(iOSVersion);
447    } else if (iOSSimTarget) {
448      const Option *O = Opts.getOption(
449        options::OPT_mios_simulator_version_min_EQ);
450      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
451      Args.append(iOSSimVersion);
452    } else {
453      // Otherwise, assume we are targeting OS X.
454      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
455      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
456      Args.append(OSXVersion);
457    }
458  }
459
460  // Set the tool chain target information.
461  unsigned Major, Minor, Micro;
462  bool HadExtra;
463  if (OSXVersion) {
464    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
465    if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
466                                   Micro, HadExtra) || HadExtra ||
467        Major != 10 || Minor >= 100 || Micro >= 100)
468      getDriver().Diag(clang::diag::err_drv_invalid_version_number)
469        << OSXVersion->getAsString(Args);
470  } else {
471    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
472    assert(Version && "Unknown target platform!");
473    if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
474                                   Micro, HadExtra) || HadExtra ||
475        Major >= 10 || Minor >= 100 || Micro >= 100)
476      getDriver().Diag(clang::diag::err_drv_invalid_version_number)
477        << Version->getAsString(Args);
478  }
479
480  setTarget(/*isIPhoneOS=*/ !OSXVersion, Major, Minor, Micro);
481}
482
483void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
484                                      ArgStringList &CmdArgs) const {
485  CXXStdlibType Type = GetCXXStdlibType(Args);
486
487  switch (Type) {
488  case ToolChain::CST_Libcxx:
489    CmdArgs.push_back("-lc++");
490    break;
491
492  case ToolChain::CST_Libstdcxx: {
493    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
494    // it was previously found in the gcc lib dir. However, for all the Darwin
495    // platforms we care about it was -lstdc++.6, so we search for that
496    // explicitly if we can't see an obvious -lstdc++ candidate.
497
498    // Check in the sysroot first.
499    bool Exists;
500    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
501      llvm::sys::Path P(A->getValue(Args));
502      P.appendComponent("usr");
503      P.appendComponent("lib");
504      P.appendComponent("libstdc++.dylib");
505
506      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
507        P.eraseComponent();
508        P.appendComponent("libstdc++.6.dylib");
509        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
510          CmdArgs.push_back(Args.MakeArgString(P.str()));
511          return;
512        }
513      }
514    }
515
516    // Otherwise, look in the root.
517    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
518      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
519      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
520      return;
521    }
522
523    // Otherwise, let the linker search.
524    CmdArgs.push_back("-lstdc++");
525    break;
526  }
527  }
528}
529
530void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
531                                   ArgStringList &CmdArgs) const {
532
533  // For Darwin platforms, use the compiler-rt-based support library
534  // instead of the gcc-provided one (which is also incidentally
535  // only present in the gcc lib dir, which makes it hard to find).
536
537  llvm::sys::Path P(getDriver().ResourceDir);
538  P.appendComponent("lib");
539  P.appendComponent("darwin");
540  P.appendComponent("libclang_rt.cc_kext.a");
541
542  // For now, allow missing resource libraries to support developers who may
543  // not have compiler-rt checked out or integrated into their build.
544  bool Exists;
545  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
546    CmdArgs.push_back(Args.MakeArgString(P.str()));
547}
548
549DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
550                                      const char *BoundArch) const {
551  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
552  const OptTable &Opts = getDriver().getOpts();
553
554  // FIXME: We really want to get out of the tool chain level argument
555  // translation business, as it makes the driver functionality much
556  // more opaque. For now, we follow gcc closely solely for the
557  // purpose of easily achieving feature parity & testability. Once we
558  // have something that works, we should reevaluate each translation
559  // and try to push it down into tool specific logic.
560
561  for (ArgList::const_iterator it = Args.begin(),
562         ie = Args.end(); it != ie; ++it) {
563    Arg *A = *it;
564
565    if (A->getOption().matches(options::OPT_Xarch__)) {
566      // FIXME: Canonicalize name.
567      if (getArchName() != A->getValue(Args, 0))
568        continue;
569
570      Arg *OriginalArg = A;
571      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
572      unsigned Prev = Index;
573      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
574
575      // If the argument parsing failed or more than one argument was
576      // consumed, the -Xarch_ argument's parameter tried to consume
577      // extra arguments. Emit an error and ignore.
578      //
579      // We also want to disallow any options which would alter the
580      // driver behavior; that isn't going to work in our model. We
581      // use isDriverOption() as an approximation, although things
582      // like -O4 are going to slip through.
583      if (!XarchArg || Index > Prev + 1) {
584        getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_with_args)
585          << A->getAsString(Args);
586        continue;
587      } else if (XarchArg->getOption().isDriverOption()) {
588        getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_isdriver)
589          << A->getAsString(Args);
590        continue;
591      }
592
593      XarchArg->setBaseArg(A);
594      A = XarchArg;
595
596      DAL->AddSynthesizedArg(A);
597
598      // Linker input arguments require custom handling. The problem is that we
599      // have already constructed the phase actions, so we can not treat them as
600      // "input arguments".
601      if (A->getOption().isLinkerInput()) {
602        // Convert the argument into individual Zlinker_input_args.
603        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
604          DAL->AddSeparateArg(OriginalArg,
605                              Opts.getOption(options::OPT_Zlinker_input),
606                              A->getValue(Args, i));
607
608        }
609        continue;
610      }
611    }
612
613    // Sob. These is strictly gcc compatible for the time being. Apple
614    // gcc translates options twice, which means that self-expanding
615    // options add duplicates.
616    switch ((options::ID) A->getOption().getID()) {
617    default:
618      DAL->append(A);
619      break;
620
621    case options::OPT_mkernel:
622    case options::OPT_fapple_kext:
623      DAL->append(A);
624      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
625      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
626      break;
627
628    case options::OPT_dependency_file:
629      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
630                          A->getValue(Args));
631      break;
632
633    case options::OPT_gfull:
634      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
635      DAL->AddFlagArg(A,
636               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
637      break;
638
639    case options::OPT_gused:
640      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
641      DAL->AddFlagArg(A,
642             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
643      break;
644
645    case options::OPT_fterminated_vtables:
646    case options::OPT_findirect_virtual_calls:
647      DAL->AddFlagArg(A, Opts.getOption(options::OPT_fapple_kext));
648      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
649      break;
650
651    case options::OPT_shared:
652      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
653      break;
654
655    case options::OPT_fconstant_cfstrings:
656      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
657      break;
658
659    case options::OPT_fno_constant_cfstrings:
660      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
661      break;
662
663    case options::OPT_Wnonportable_cfstrings:
664      DAL->AddFlagArg(A,
665                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
666      break;
667
668    case options::OPT_Wno_nonportable_cfstrings:
669      DAL->AddFlagArg(A,
670                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
671      break;
672
673    case options::OPT_fpascal_strings:
674      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
675      break;
676
677    case options::OPT_fno_pascal_strings:
678      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
679      break;
680    }
681  }
682
683  if (getTriple().getArch() == llvm::Triple::x86 ||
684      getTriple().getArch() == llvm::Triple::x86_64)
685    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
686      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
687
688  // Add the arch options based on the particular spelling of -arch, to match
689  // how the driver driver works.
690  if (BoundArch) {
691    llvm::StringRef Name = BoundArch;
692    const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
693    const Option *MArch = Opts.getOption(options::OPT_march_EQ);
694
695    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
696    // which defines the list of which architectures we accept.
697    if (Name == "ppc")
698      ;
699    else if (Name == "ppc601")
700      DAL->AddJoinedArg(0, MCpu, "601");
701    else if (Name == "ppc603")
702      DAL->AddJoinedArg(0, MCpu, "603");
703    else if (Name == "ppc604")
704      DAL->AddJoinedArg(0, MCpu, "604");
705    else if (Name == "ppc604e")
706      DAL->AddJoinedArg(0, MCpu, "604e");
707    else if (Name == "ppc750")
708      DAL->AddJoinedArg(0, MCpu, "750");
709    else if (Name == "ppc7400")
710      DAL->AddJoinedArg(0, MCpu, "7400");
711    else if (Name == "ppc7450")
712      DAL->AddJoinedArg(0, MCpu, "7450");
713    else if (Name == "ppc970")
714      DAL->AddJoinedArg(0, MCpu, "970");
715
716    else if (Name == "ppc64")
717      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
718
719    else if (Name == "i386")
720      ;
721    else if (Name == "i486")
722      DAL->AddJoinedArg(0, MArch, "i486");
723    else if (Name == "i586")
724      DAL->AddJoinedArg(0, MArch, "i586");
725    else if (Name == "i686")
726      DAL->AddJoinedArg(0, MArch, "i686");
727    else if (Name == "pentium")
728      DAL->AddJoinedArg(0, MArch, "pentium");
729    else if (Name == "pentium2")
730      DAL->AddJoinedArg(0, MArch, "pentium2");
731    else if (Name == "pentpro")
732      DAL->AddJoinedArg(0, MArch, "pentiumpro");
733    else if (Name == "pentIIm3")
734      DAL->AddJoinedArg(0, MArch, "pentium2");
735
736    else if (Name == "x86_64")
737      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
738
739    else if (Name == "arm")
740      DAL->AddJoinedArg(0, MArch, "armv4t");
741    else if (Name == "armv4t")
742      DAL->AddJoinedArg(0, MArch, "armv4t");
743    else if (Name == "armv5")
744      DAL->AddJoinedArg(0, MArch, "armv5tej");
745    else if (Name == "xscale")
746      DAL->AddJoinedArg(0, MArch, "xscale");
747    else if (Name == "armv6")
748      DAL->AddJoinedArg(0, MArch, "armv6k");
749    else if (Name == "armv7")
750      DAL->AddJoinedArg(0, MArch, "armv7a");
751
752    else
753      llvm_unreachable("invalid Darwin arch");
754  }
755
756  // Add an explicit version min argument for the deployment target. We do this
757  // after argument translation because -Xarch_ arguments may add a version min
758  // argument.
759  AddDeploymentTarget(*DAL);
760
761  return DAL;
762}
763
764bool Darwin::IsUnwindTablesDefault() const {
765  // FIXME: Gross; we should probably have some separate target
766  // definition, possibly even reusing the one in clang.
767  return getArchName() == "x86_64";
768}
769
770bool Darwin::UseDwarfDebugFlags() const {
771  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
772    return S[0] != '\0';
773  return false;
774}
775
776bool Darwin::UseSjLjExceptions() const {
777  // Darwin uses SjLj exceptions on ARM.
778  return (getTriple().getArch() == llvm::Triple::arm ||
779          getTriple().getArch() == llvm::Triple::thumb);
780}
781
782const char *Darwin::GetDefaultRelocationModel() const {
783  return "pic";
784}
785
786const char *Darwin::GetForcedPicModel() const {
787  if (getArchName() == "x86_64")
788    return "pic";
789  return 0;
790}
791
792bool Darwin::SupportsProfiling() const {
793  // Profiling instrumentation is only supported on x86.
794  return getArchName() == "i386" || getArchName() == "x86_64";
795}
796
797bool Darwin::SupportsObjCGC() const {
798  // Garbage collection is supported everywhere except on iPhone OS.
799  return !isTargetIPhoneOS();
800}
801
802std::string
803Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args) const {
804  return ComputeLLVMTriple(Args);
805}
806
807/// Generic_GCC - A tool chain using the 'gcc' command to perform
808/// all subcommands; this relies on gcc translating the majority of
809/// command line options.
810
811Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
812  : ToolChain(Host, Triple) {
813  getProgramPaths().push_back(getDriver().getInstalledDir());
814  if (getDriver().getInstalledDir() != getDriver().Dir)
815    getProgramPaths().push_back(getDriver().Dir);
816}
817
818Generic_GCC::~Generic_GCC() {
819  // Free tool implementations.
820  for (llvm::DenseMap<unsigned, Tool*>::iterator
821         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
822    delete it->second;
823}
824
825Tool &Generic_GCC::SelectTool(const Compilation &C,
826                              const JobAction &JA,
827                              const ActionList &Inputs) const {
828  Action::ActionClass Key;
829  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
830    Key = Action::AnalyzeJobClass;
831  else
832    Key = JA.getKind();
833
834  Tool *&T = Tools[Key];
835  if (!T) {
836    switch (Key) {
837    case Action::InputClass:
838    case Action::BindArchClass:
839      assert(0 && "Invalid tool kind.");
840    case Action::PreprocessJobClass:
841      T = new tools::gcc::Preprocess(*this); break;
842    case Action::PrecompileJobClass:
843      T = new tools::gcc::Precompile(*this); break;
844    case Action::AnalyzeJobClass:
845      T = new tools::Clang(*this); break;
846    case Action::CompileJobClass:
847      T = new tools::gcc::Compile(*this); break;
848    case Action::AssembleJobClass:
849      T = new tools::gcc::Assemble(*this); break;
850    case Action::LinkJobClass:
851      T = new tools::gcc::Link(*this); break;
852
853      // This is a bit ungeneric, but the only platform using a driver
854      // driver is Darwin.
855    case Action::LipoJobClass:
856      T = new tools::darwin::Lipo(*this); break;
857    case Action::DsymutilJobClass:
858      T = new tools::darwin::Dsymutil(*this); break;
859    }
860  }
861
862  return *T;
863}
864
865bool Generic_GCC::IsUnwindTablesDefault() const {
866  // FIXME: Gross; we should probably have some separate target
867  // definition, possibly even reusing the one in clang.
868  return getArchName() == "x86_64";
869}
870
871const char *Generic_GCC::GetDefaultRelocationModel() const {
872  return "static";
873}
874
875const char *Generic_GCC::GetForcedPicModel() const {
876  return 0;
877}
878
879/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
880/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
881/// Currently does not support anything else but compilation.
882
883TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple)
884  : ToolChain(Host, Triple) {
885  // Path mangling to find libexec
886  std::string Path(getDriver().Dir);
887
888  Path += "/../libexec";
889  getProgramPaths().push_back(Path);
890}
891
892TCEToolChain::~TCEToolChain() {
893  for (llvm::DenseMap<unsigned, Tool*>::iterator
894           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
895      delete it->second;
896}
897
898bool TCEToolChain::IsMathErrnoDefault() const {
899  return true;
900}
901
902bool TCEToolChain::IsUnwindTablesDefault() const {
903  return false;
904}
905
906const char *TCEToolChain::GetDefaultRelocationModel() const {
907  return "static";
908}
909
910const char *TCEToolChain::GetForcedPicModel() const {
911  return 0;
912}
913
914Tool &TCEToolChain::SelectTool(const Compilation &C,
915                            const JobAction &JA,
916                               const ActionList &Inputs) const {
917  Action::ActionClass Key;
918  Key = Action::AnalyzeJobClass;
919
920  Tool *&T = Tools[Key];
921  if (!T) {
922    switch (Key) {
923    case Action::PreprocessJobClass:
924      T = new tools::gcc::Preprocess(*this); break;
925    case Action::AnalyzeJobClass:
926      T = new tools::Clang(*this); break;
927    default:
928     assert(false && "Unsupported action for TCE target.");
929    }
930  }
931  return *T;
932}
933
934/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
935
936OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
937  : Generic_ELF(Host, Triple) {
938  getFilePaths().push_back(getDriver().Dir + "/../lib");
939  getFilePaths().push_back("/usr/lib");
940}
941
942Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
943                          const ActionList &Inputs) const {
944  Action::ActionClass Key;
945  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
946    Key = Action::AnalyzeJobClass;
947  else
948    Key = JA.getKind();
949
950  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
951                                             options::OPT_no_integrated_as,
952                                             IsIntegratedAssemblerDefault());
953
954  Tool *&T = Tools[Key];
955  if (!T) {
956    switch (Key) {
957    case Action::AssembleJobClass: {
958      if (UseIntegratedAs)
959        T = new tools::ClangAs(*this);
960      else
961        T = new tools::openbsd::Assemble(*this);
962      break;
963    }
964    case Action::LinkJobClass:
965      T = new tools::openbsd::Link(*this); break;
966    default:
967      T = &Generic_GCC::SelectTool(C, JA, Inputs);
968    }
969  }
970
971  return *T;
972}
973
974/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
975
976FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
977  : Generic_ELF(Host, Triple) {
978
979  // Determine if we are compiling 32-bit code on an x86_64 platform.
980  bool Lib32 = false;
981  if (Triple.getArch() == llvm::Triple::x86 &&
982      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
983        llvm::Triple::x86_64)
984    Lib32 = true;
985
986  if (Lib32) {
987    getFilePaths().push_back("/usr/lib32");
988  } else {
989    getFilePaths().push_back("/usr/lib");
990  }
991}
992
993Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
994                          const ActionList &Inputs) const {
995  Action::ActionClass Key;
996  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
997    Key = Action::AnalyzeJobClass;
998  else
999    Key = JA.getKind();
1000
1001  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1002                                             options::OPT_no_integrated_as,
1003                                             IsIntegratedAssemblerDefault());
1004
1005  Tool *&T = Tools[Key];
1006  if (!T) {
1007    switch (Key) {
1008    case Action::AssembleJobClass:
1009      if (UseIntegratedAs)
1010        T = new tools::ClangAs(*this);
1011      else
1012        T = new tools::freebsd::Assemble(*this);
1013      break;
1014    case Action::LinkJobClass:
1015      T = new tools::freebsd::Link(*this); break;
1016    default:
1017      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1018    }
1019  }
1020
1021  return *T;
1022}
1023
1024/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1025
1026NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple)
1027  : Generic_ELF(Host, Triple) {
1028
1029  // Determine if we are compiling 32-bit code on an x86_64 platform.
1030  bool Lib32 = false;
1031  if (Triple.getArch() == llvm::Triple::x86 &&
1032      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1033        llvm::Triple::x86_64)
1034    Lib32 = true;
1035
1036  if (getDriver().UseStdLib) {
1037    if (Lib32)
1038      getFilePaths().push_back("=/usr/lib/i386");
1039    else
1040      getFilePaths().push_back("=/usr/lib");
1041  }
1042}
1043
1044Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1045                         const ActionList &Inputs) const {
1046  Action::ActionClass Key;
1047  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1048    Key = Action::AnalyzeJobClass;
1049  else
1050    Key = JA.getKind();
1051
1052  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1053                                             options::OPT_no_integrated_as,
1054                                             IsIntegratedAssemblerDefault());
1055
1056  Tool *&T = Tools[Key];
1057  if (!T) {
1058    switch (Key) {
1059    case Action::AssembleJobClass:
1060      if (UseIntegratedAs)
1061        T = new tools::ClangAs(*this);
1062      else
1063        T = new tools::netbsd::Assemble(*this);
1064      break;
1065    case Action::LinkJobClass:
1066      T = new tools::netbsd::Link(*this); break;
1067    default:
1068      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1069    }
1070  }
1071
1072  return *T;
1073}
1074
1075/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1076
1077Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1078  : Generic_GCC(Host, Triple) {
1079  getFilePaths().push_back(getDriver().Dir + "/../lib");
1080  getFilePaths().push_back("/usr/lib");
1081  getFilePaths().push_back("/usr/gnu/lib");
1082  getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
1083}
1084
1085Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1086                        const ActionList &Inputs) const {
1087  Action::ActionClass Key;
1088  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1089    Key = Action::AnalyzeJobClass;
1090  else
1091    Key = JA.getKind();
1092
1093  Tool *&T = Tools[Key];
1094  if (!T) {
1095    switch (Key) {
1096    case Action::AssembleJobClass:
1097      T = new tools::minix::Assemble(*this); break;
1098    case Action::LinkJobClass:
1099      T = new tools::minix::Link(*this); break;
1100    default:
1101      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1102    }
1103  }
1104
1105  return *T;
1106}
1107
1108/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1109
1110AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1111  : Generic_GCC(Host, Triple) {
1112
1113  getProgramPaths().push_back(getDriver().getInstalledDir());
1114  if (getDriver().getInstalledDir() != getDriver().Dir)
1115    getProgramPaths().push_back(getDriver().Dir);
1116
1117  getFilePaths().push_back(getDriver().Dir + "/../lib");
1118  getFilePaths().push_back("/usr/lib");
1119  getFilePaths().push_back("/usr/sfw/lib");
1120  getFilePaths().push_back("/opt/gcc4/lib");
1121  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1122
1123}
1124
1125Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1126                           const ActionList &Inputs) const {
1127  Action::ActionClass Key;
1128  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1129    Key = Action::AnalyzeJobClass;
1130  else
1131    Key = JA.getKind();
1132
1133  Tool *&T = Tools[Key];
1134  if (!T) {
1135    switch (Key) {
1136    case Action::AssembleJobClass:
1137      T = new tools::auroraux::Assemble(*this); break;
1138    case Action::LinkJobClass:
1139      T = new tools::auroraux::Link(*this); break;
1140    default:
1141      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1142    }
1143  }
1144
1145  return *T;
1146}
1147
1148
1149/// Linux toolchain (very bare-bones at the moment).
1150
1151enum LinuxDistro {
1152  ArchLinux,
1153  DebianLenny,
1154  DebianSqueeze,
1155  Exherbo,
1156  Fedora13,
1157  Fedora14,
1158  Fedora15,
1159  FedoraRawhide,
1160  OpenSuse11_3,
1161  UbuntuHardy,
1162  UbuntuIntrepid,
1163  UbuntuJaunty,
1164  UbuntuKarmic,
1165  UbuntuLucid,
1166  UbuntuMaverick,
1167  UbuntuNatty,
1168  UnknownDistro
1169};
1170
1171static bool IsFedora(enum LinuxDistro Distro) {
1172  return Distro == Fedora13 || Distro == Fedora14 ||
1173         Distro == Fedora15 || Distro == FedoraRawhide;
1174}
1175
1176static bool IsOpenSuse(enum LinuxDistro Distro) {
1177  return Distro == OpenSuse11_3;
1178}
1179
1180static bool IsDebian(enum LinuxDistro Distro) {
1181  return Distro == DebianLenny || Distro == DebianSqueeze;
1182}
1183
1184static bool IsUbuntu(enum LinuxDistro Distro) {
1185  return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1186         Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1187         Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1188         Distro == UbuntuNatty;
1189}
1190
1191static bool IsDebianBased(enum LinuxDistro Distro) {
1192  return IsDebian(Distro) || IsUbuntu(Distro);
1193}
1194
1195static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) {
1196  if (Arch == llvm::Triple::x86_64) {
1197    bool Exists;
1198    if (Distro == Exherbo &&
1199        (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists))
1200      return false;
1201
1202    return true;
1203  }
1204  if (Arch == llvm::Triple::ppc64)
1205    return true;
1206  if ((Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc) && IsDebianBased(Distro))
1207    return true;
1208  return false;
1209}
1210
1211static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1212  llvm::OwningPtr<llvm::MemoryBuffer> File;
1213  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1214    llvm::StringRef Data = File.get()->getBuffer();
1215    llvm::SmallVector<llvm::StringRef, 8> Lines;
1216    Data.split(Lines, "\n");
1217    for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1218      if (Lines[i] == "DISTRIB_CODENAME=hardy")
1219        return UbuntuHardy;
1220      else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1221        return UbuntuIntrepid;
1222      else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1223        return UbuntuJaunty;
1224      else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1225        return UbuntuKarmic;
1226      else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1227        return UbuntuLucid;
1228      else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1229        return UbuntuMaverick;
1230      else if (Lines[i] == "DISTRIB_CODENAME=natty")
1231        return UbuntuNatty;
1232    }
1233    return UnknownDistro;
1234  }
1235
1236  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1237    llvm::StringRef Data = File.get()->getBuffer();
1238    if (Data.startswith("Fedora release 15"))
1239      return Fedora15;
1240    else if (Data.startswith("Fedora release 14"))
1241      return Fedora14;
1242    else if (Data.startswith("Fedora release 13"))
1243      return Fedora13;
1244    else if (Data.startswith("Fedora release") &&
1245             Data.find("Rawhide") != llvm::StringRef::npos)
1246      return FedoraRawhide;
1247    return UnknownDistro;
1248  }
1249
1250  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1251    llvm::StringRef Data = File.get()->getBuffer();
1252    if (Data[0] == '5')
1253      return DebianLenny;
1254    else if (Data.startswith("squeeze/sid"))
1255      return DebianSqueeze;
1256    return UnknownDistro;
1257  }
1258
1259  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1260    llvm::StringRef Data = File.get()->getBuffer();
1261    if (Data.startswith("openSUSE 11.3"))
1262      return OpenSuse11_3;
1263    return UnknownDistro;
1264  }
1265
1266  bool Exists;
1267  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1268    return Exherbo;
1269
1270  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1271    return ArchLinux;
1272
1273  return UnknownDistro;
1274}
1275
1276Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1277  : Generic_ELF(Host, Triple) {
1278  llvm::Triple::ArchType Arch =
1279    llvm::Triple(getDriver().DefaultHostTriple).getArch();
1280
1281  std::string Suffix32  = "";
1282  if (Arch == llvm::Triple::x86_64)
1283    Suffix32 = "/32";
1284
1285  std::string Suffix64  = "";
1286  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
1287    Suffix64 = "/64";
1288
1289  std::string Lib32 = "lib";
1290
1291  bool Exists;
1292  if (!llvm::sys::fs::exists("/lib32", Exists) && Exists)
1293    Lib32 = "lib32";
1294
1295  std::string Lib64 = "lib";
1296  bool Symlink;
1297  if (!llvm::sys::fs::exists("/lib64", Exists) && Exists &&
1298      (llvm::sys::fs::is_symlink("/lib64", Symlink) || !Symlink))
1299    Lib64 = "lib64";
1300
1301  std::string GccTriple = "";
1302  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
1303    if (!llvm::sys::fs::exists("/usr/lib/gcc/arm-linux-gnueabi", Exists) &&
1304        Exists)
1305      GccTriple = "arm-linux-gnueabi";
1306  } else if (Arch == llvm::Triple::x86_64) {
1307    if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-linux-gnu", Exists) &&
1308        Exists)
1309      GccTriple = "x86_64-linux-gnu";
1310    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-unknown-linux-gnu",
1311             Exists) && Exists)
1312      GccTriple = "x86_64-unknown-linux-gnu";
1313    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-pc-linux-gnu",
1314             Exists) && Exists)
1315      GccTriple = "x86_64-pc-linux-gnu";
1316    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-redhat-linux",
1317             Exists) && Exists)
1318      GccTriple = "x86_64-redhat-linux";
1319    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/x86_64-suse-linux",
1320             Exists) && Exists)
1321      GccTriple = "x86_64-suse-linux";
1322    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-manbo-linux-gnu",
1323             Exists) && Exists)
1324      GccTriple = "x86_64-manbo-linux-gnu";
1325    else if (!llvm::sys::fs::exists("/usr/lib/x86_64-linux-gnu/gcc",
1326             Exists) && Exists)
1327      GccTriple = "x86_64-linux-gnu";
1328  } else if (Arch == llvm::Triple::x86) {
1329    if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-linux-gnu", Exists) && Exists)
1330      GccTriple = "i686-linux-gnu";
1331    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-pc-linux-gnu", Exists) &&
1332             Exists)
1333      GccTriple = "i686-pc-linux-gnu";
1334    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-linux-gnu", Exists) &&
1335             Exists)
1336      GccTriple = "i486-linux-gnu";
1337    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-redhat-linux", Exists) &&
1338             Exists)
1339      GccTriple = "i686-redhat-linux";
1340    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i586-suse-linux", Exists) &&
1341             Exists)
1342      GccTriple = "i586-suse-linux";
1343    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-slackware-linux", Exists)
1344            && Exists)
1345      GccTriple = "i486-slackware-linux";
1346  } else if (Arch == llvm::Triple::ppc) {
1347    if (!llvm::sys::fs::exists("/usr/lib/powerpc-linux-gnu", Exists) && Exists)
1348      GccTriple = "powerpc-linux-gnu";
1349    else if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc-unknown-linux-gnu", Exists) && Exists)
1350      GccTriple = "powerpc-unknown-linux-gnu";
1351  } else if (Arch == llvm::Triple::ppc64) {
1352    if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc64-unknown-linux-gnu", Exists) && Exists)
1353      GccTriple = "powerpc64-unknown-linux-gnu";
1354    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/powerpc64-unknown-linux-gnu", Exists) && Exists)
1355      GccTriple = "powerpc64-unknown-linux-gnu";
1356  }
1357
1358  const char* GccVersions[] = {"4.6.0",
1359                               "4.5.2", "4.5.1", "4.5",
1360                               "4.4.5", "4.4.4", "4.4.3", "4.4",
1361                               "4.3.4", "4.3.3", "4.3.2", "4.3",
1362                               "4.2.4", "4.2.3", "4.2.2", "4.2.1", "4.2"};
1363  std::string Base = "";
1364  for (unsigned i = 0; i < sizeof(GccVersions)/sizeof(char*); ++i) {
1365    std::string Suffix = GccTriple + "/" + GccVersions[i];
1366    std::string t1 = "/usr/lib/gcc/" + Suffix;
1367    if (!llvm::sys::fs::exists(t1 + "/crtbegin.o", Exists) && Exists) {
1368      Base = t1;
1369      break;
1370    }
1371    std::string t2 = "/usr/lib64/gcc/" + Suffix;
1372    if (!llvm::sys::fs::exists(t2 + "/crtbegin.o", Exists) && Exists) {
1373      Base = t2;
1374      break;
1375    }
1376    std::string t3 = "/usr/lib/" + GccTriple + "/gcc/" + Suffix;
1377    if (!llvm::sys::fs::exists(t3 + "/crtbegin.o", Exists) && Exists) {
1378      Base = t3;
1379      break;
1380    }
1381  }
1382
1383  path_list &Paths = getFilePaths();
1384  bool Is32Bits = (getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::ppc);
1385
1386  std::string Suffix;
1387  std::string Lib;
1388
1389  if (Is32Bits) {
1390    Suffix = Suffix32;
1391    Lib = Lib32;
1392  } else {
1393    Suffix = Suffix64;
1394    Lib = Lib64;
1395  }
1396
1397  llvm::sys::Path LinkerPath(Base + "/../../../../" + GccTriple + "/bin/ld");
1398  if (!llvm::sys::fs::exists(LinkerPath.str(), Exists) && Exists)
1399    Linker = LinkerPath.str();
1400  else
1401    Linker = GetProgramPath("ld");
1402
1403  LinuxDistro Distro = DetectLinuxDistro(Arch);
1404
1405  if (IsUbuntu(Distro)) {
1406    ExtraOpts.push_back("-z");
1407    ExtraOpts.push_back("relro");
1408  }
1409
1410  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1411    ExtraOpts.push_back("-X");
1412
1413  if (IsFedora(Distro) || Distro == UbuntuMaverick || Distro == UbuntuNatty)
1414    ExtraOpts.push_back("--hash-style=gnu");
1415
1416  if (IsDebian(Distro) || Distro == UbuntuLucid || Distro == UbuntuJaunty ||
1417      Distro == UbuntuKarmic)
1418    ExtraOpts.push_back("--hash-style=both");
1419
1420  if (IsFedora(Distro))
1421    ExtraOpts.push_back("--no-add-needed");
1422
1423  if (Distro == DebianSqueeze || IsOpenSuse(Distro) ||
1424      IsFedora(Distro) || Distro == UbuntuLucid || Distro == UbuntuMaverick ||
1425      Distro == UbuntuKarmic || Distro == UbuntuNatty)
1426    ExtraOpts.push_back("--build-id");
1427
1428  if (Distro == ArchLinux)
1429    Lib = "lib";
1430
1431  Paths.push_back(Base + Suffix);
1432  if (HasMultilib(Arch, Distro)) {
1433    if (IsOpenSuse(Distro) && Is32Bits)
1434      Paths.push_back(Base + "/../../../../" + GccTriple + "/lib/../lib");
1435    Paths.push_back(Base + "/../../../../" + Lib);
1436    Paths.push_back("/lib/../" + Lib);
1437    Paths.push_back("/usr/lib/../" + Lib);
1438  }
1439  if (!Suffix.empty())
1440    Paths.push_back(Base);
1441  if (IsOpenSuse(Distro))
1442    Paths.push_back(Base + "/../../../../" + GccTriple + "/lib");
1443  Paths.push_back(Base + "/../../..");
1444  if (Arch == getArch() && IsUbuntu(Distro))
1445    Paths.push_back("/usr/lib/" + GccTriple);
1446}
1447
1448bool Linux::HasNativeLLVMSupport() const {
1449  return true;
1450}
1451
1452Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
1453                        const ActionList &Inputs) const {
1454  Action::ActionClass Key;
1455  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1456    Key = Action::AnalyzeJobClass;
1457  else
1458    Key = JA.getKind();
1459
1460  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1461                                             options::OPT_no_integrated_as,
1462                                             IsIntegratedAssemblerDefault());
1463
1464  Tool *&T = Tools[Key];
1465  if (!T) {
1466    switch (Key) {
1467    case Action::AssembleJobClass:
1468      if (UseIntegratedAs)
1469        T = new tools::ClangAs(*this);
1470      else
1471        T = new tools::linuxtools::Assemble(*this);
1472      break;
1473    case Action::LinkJobClass:
1474      T = new tools::linuxtools::Link(*this); break;
1475    default:
1476      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1477    }
1478  }
1479
1480  return *T;
1481}
1482
1483/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
1484
1485DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
1486  : Generic_ELF(Host, Triple) {
1487
1488  // Path mangling to find libexec
1489  getProgramPaths().push_back(getDriver().getInstalledDir());
1490  if (getDriver().getInstalledDir() != getDriver().Dir)
1491    getProgramPaths().push_back(getDriver().Dir);
1492
1493  getFilePaths().push_back(getDriver().Dir + "/../lib");
1494  getFilePaths().push_back("/usr/lib");
1495  getFilePaths().push_back("/usr/lib/gcc41");
1496}
1497
1498Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
1499                            const ActionList &Inputs) const {
1500  Action::ActionClass Key;
1501  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1502    Key = Action::AnalyzeJobClass;
1503  else
1504    Key = JA.getKind();
1505
1506  Tool *&T = Tools[Key];
1507  if (!T) {
1508    switch (Key) {
1509    case Action::AssembleJobClass:
1510      T = new tools::dragonfly::Assemble(*this); break;
1511    case Action::LinkJobClass:
1512      T = new tools::dragonfly::Link(*this); break;
1513    default:
1514      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1515    }
1516  }
1517
1518  return *T;
1519}
1520
1521Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
1522  : ToolChain(Host, Triple) {
1523}
1524
1525Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
1526                          const ActionList &Inputs) const {
1527  Action::ActionClass Key;
1528  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1529    Key = Action::AnalyzeJobClass;
1530  else
1531    Key = JA.getKind();
1532
1533  Tool *&T = Tools[Key];
1534  if (!T) {
1535    switch (Key) {
1536    case Action::InputClass:
1537    case Action::BindArchClass:
1538    case Action::LipoJobClass:
1539    case Action::DsymutilJobClass:
1540      assert(0 && "Invalid tool kind.");
1541    case Action::PreprocessJobClass:
1542    case Action::PrecompileJobClass:
1543    case Action::AnalyzeJobClass:
1544    case Action::CompileJobClass:
1545      T = new tools::Clang(*this); break;
1546    case Action::AssembleJobClass:
1547      T = new tools::ClangAs(*this); break;
1548    case Action::LinkJobClass:
1549      T = new tools::visualstudio::Link(*this); break;
1550    }
1551  }
1552
1553  return *T;
1554}
1555
1556bool Windows::IsIntegratedAssemblerDefault() const {
1557  return true;
1558}
1559
1560bool Windows::IsUnwindTablesDefault() const {
1561  // FIXME: Gross; we should probably have some separate target
1562  // definition, possibly even reusing the one in clang.
1563  return getArchName() == "x86_64";
1564}
1565
1566const char *Windows::GetDefaultRelocationModel() const {
1567  return "static";
1568}
1569
1570const char *Windows::GetForcedPicModel() const {
1571  if (getArchName() == "x86_64")
1572    return "pic";
1573  return 0;
1574}
1575