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