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