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