]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
Since contrib/libc++'s ancestry was never correct, subversion 1.8 and
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains.cpp
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 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/SanitizerArgs.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Option/Arg.h"
24 #include "llvm/Option/ArgList.h"
25 #include "llvm/Option/OptTable.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cstdlib> // ::getenv
34 #include <system_error>
35
36 using namespace clang::driver;
37 using namespace clang::driver::toolchains;
38 using namespace clang;
39 using namespace llvm::opt;
40
41 MachO::MachO(const Driver &D, const llvm::Triple &Triple,
42                        const ArgList &Args)
43   : ToolChain(D, Triple, Args) {
44   getProgramPaths().push_back(getDriver().getInstalledDir());
45   if (getDriver().getInstalledDir() != getDriver().Dir)
46     getProgramPaths().push_back(getDriver().Dir);
47
48   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
49   getProgramPaths().push_back(getDriver().getInstalledDir());
50   if (getDriver().getInstalledDir() != getDriver().Dir)
51     getProgramPaths().push_back(getDriver().Dir);
52 }
53
54 /// Darwin - Darwin tool chain for i386 and x86_64.
55 Darwin::Darwin(const Driver & D, const llvm::Triple & Triple,
56                const ArgList & Args)
57   : MachO(D, Triple, Args), TargetInitialized(false) {
58   // Compute the initial Darwin version from the triple
59   unsigned Major, Minor, Micro;
60   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
61     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
62       Triple.getOSName();
63   llvm::raw_string_ostream(MacosxVersionMin)
64     << Major << '.' << Minor << '.' << Micro;
65
66   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
67   // It should be removed when we stop supporting that.
68   DarwinVersion[0] = Minor + 4;
69   DarwinVersion[1] = Micro;
70   DarwinVersion[2] = 0;
71
72   // Compute the initial iOS version from the triple
73   Triple.getiOSVersion(Major, Minor, Micro);
74   llvm::raw_string_ostream(iOSVersionMin)
75     << Major << '.' << Minor << '.' << Micro;
76 }
77
78 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
79   types::ID Ty = types::lookupTypeForExtension(Ext);
80
81   // Darwin always preprocesses assembly files (unless -x is used explicitly).
82   if (Ty == types::TY_PP_Asm)
83     return types::TY_Asm;
84
85   return Ty;
86 }
87
88 bool MachO::HasNativeLLVMSupport() const {
89   return true;
90 }
91
92 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
93 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
94   if (isTargetIOSBased())
95     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
96   if (isNonFragile)
97     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
98   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
99 }
100
101 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
102 bool Darwin::hasBlocksRuntime() const {
103   if (isTargetIOSBased())
104     return !isIPhoneOSVersionLT(3, 2);
105   else {
106     assert(isTargetMacOS() && "unexpected darwin target");
107     return !isMacosxVersionLT(10, 6);
108   }
109 }
110
111 static const char *GetArmArchForMArch(StringRef Value) {
112   return llvm::StringSwitch<const char*>(Value)
113     .Case("armv6k", "armv6")
114     .Case("armv6m", "armv6m")
115     .Case("armv5tej", "armv5")
116     .Case("xscale", "xscale")
117     .Case("armv4t", "armv4t")
118     .Case("armv7", "armv7")
119     .Cases("armv7a", "armv7-a", "armv7")
120     .Cases("armv7r", "armv7-r", "armv7")
121     .Cases("armv7em", "armv7e-m", "armv7em")
122     .Cases("armv7k", "armv7-k", "armv7k")
123     .Cases("armv7m", "armv7-m", "armv7m")
124     .Cases("armv7s", "armv7-s", "armv7s")
125     .Default(nullptr);
126 }
127
128 static const char *GetArmArchForMCpu(StringRef Value) {
129   return llvm::StringSwitch<const char *>(Value)
130     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
131     .Cases("arm10e", "arm10tdmi", "armv5")
132     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
133     .Case("xscale", "xscale")
134     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
135     .Case("cortex-m0", "armv6m")
136     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
137     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7")
138     .Cases("cortex-r4", "cortex-r5", "armv7r")
139     .Case("cortex-m3", "armv7m")
140     .Cases("cortex-m4", "cortex-m7", "armv7em")
141     .Case("swift", "armv7s")
142     .Default(nullptr);
143 }
144
145 static bool isSoftFloatABI(const ArgList &Args) {
146   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
147                            options::OPT_mfloat_abi_EQ);
148   if (!A)
149     return false;
150
151   return A->getOption().matches(options::OPT_msoft_float) ||
152          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
153           A->getValue() == StringRef("soft"));
154 }
155
156 StringRef MachO::getMachOArchName(const ArgList &Args) const {
157   switch (getTriple().getArch()) {
158   default:
159     return getDefaultUniversalArchName();
160
161   case llvm::Triple::aarch64:
162     return "arm64";
163
164   case llvm::Triple::thumb:
165   case llvm::Triple::arm: {
166     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
167       if (const char *Arch = GetArmArchForMArch(A->getValue()))
168         return Arch;
169
170     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
171       if (const char *Arch = GetArmArchForMCpu(A->getValue()))
172         return Arch;
173
174     return "arm";
175   }
176   }
177 }
178
179 Darwin::~Darwin() {
180 }
181
182 MachO::~MachO() {
183 }
184
185
186 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
187                                                     types::ID InputType) const {
188   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
189
190   return Triple.getTriple();
191 }
192
193 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
194                                                 types::ID InputType) const {
195   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
196
197   // If the target isn't initialized (e.g., an unknown Darwin platform, return
198   // the default triple).
199   if (!isTargetInitialized())
200     return Triple.getTriple();
201
202   SmallString<16> Str;
203   Str += isTargetIOSBased() ? "ios" : "macosx";
204   Str += getTargetVersion().getAsString();
205   Triple.setOSName(Str);
206
207   return Triple.getTriple();
208 }
209
210 void Generic_ELF::anchor() {}
211
212 Tool *MachO::getTool(Action::ActionClass AC) const {
213   switch (AC) {
214   case Action::LipoJobClass:
215     if (!Lipo)
216       Lipo.reset(new tools::darwin::Lipo(*this));
217     return Lipo.get();
218   case Action::DsymutilJobClass:
219     if (!Dsymutil)
220       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
221     return Dsymutil.get();
222   case Action::VerifyDebugInfoJobClass:
223     if (!VerifyDebug)
224       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
225     return VerifyDebug.get();
226   default:
227     return ToolChain::getTool(AC);
228   }
229 }
230
231 Tool *MachO::buildLinker() const {
232   return new tools::darwin::Link(*this);
233 }
234
235 Tool *MachO::buildAssembler() const {
236   return new tools::darwin::Assemble(*this);
237 }
238
239 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
240                          const ArgList &Args)
241   : Darwin(D, Triple, Args) {
242 }
243
244 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
245   // For iOS, 64-bit, promote certain warnings to errors.
246   if (!isTargetMacOS() && getTriple().isArch64Bit()) {
247     // Always enable -Wdeprecated-objc-isa-usage and promote it
248     // to an error.
249     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
250     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
251
252     // Also error about implicit function declarations, as that
253     // can impact calling conventions.
254     CC1Args.push_back("-Werror=implicit-function-declaration");
255   }
256 }
257
258 /// \brief Determine whether Objective-C automated reference counting is
259 /// enabled.
260 static bool isObjCAutoRefCount(const ArgList &Args) {
261   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
262 }
263
264 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
265                                  ArgStringList &CmdArgs) const {
266   // Avoid linking compatibility stubs on i386 mac.
267   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
268     return;
269
270   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
271
272   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
273       runtime.hasSubscripting())
274     return;
275
276   CmdArgs.push_back("-force_load");
277   SmallString<128> P(getDriver().ClangExecutable);
278   llvm::sys::path::remove_filename(P); // 'clang'
279   llvm::sys::path::remove_filename(P); // 'bin'
280   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
281   // Mash in the platform.
282   if (isTargetIOSSimulator())
283     P += "iphonesimulator";
284   else if (isTargetIPhoneOS())
285     P += "iphoneos";
286   else
287     P += "macosx";
288   P += ".a";
289
290   CmdArgs.push_back(Args.MakeArgString(P));
291 }
292
293 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
294                               StringRef DarwinLibName, bool AlwaysLink,
295                               bool IsEmbedded, bool AddRPath) const {
296   SmallString<128> Dir(getDriver().ResourceDir);
297   llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
298
299   SmallString<128> P(Dir);
300   llvm::sys::path::append(P, DarwinLibName);
301
302   // For now, allow missing resource libraries to support developers who may
303   // not have compiler-rt checked out or integrated into their build (unless
304   // we explicitly force linking with this library).
305   if (AlwaysLink || llvm::sys::fs::exists(P.str()))
306     CmdArgs.push_back(Args.MakeArgString(P.str()));
307
308   // Adding the rpaths might negatively interact when other rpaths are involved,
309   // so we should make sure we add the rpaths last, after all user-specified
310   // rpaths. This is currently true from this place, but we need to be
311   // careful if this function is ever called before user's rpaths are emitted.
312   if (AddRPath) {
313     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
314
315     // Add @executable_path to rpath to support having the dylib copied with
316     // the executable.
317     CmdArgs.push_back("-rpath");
318     CmdArgs.push_back("@executable_path");
319
320     // Add the path to the resource dir to rpath to support using the dylib
321     // from the default location without copying.
322     CmdArgs.push_back("-rpath");
323     CmdArgs.push_back(Args.MakeArgString(Dir.str()));
324   }
325 }
326
327 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
328                                         ArgStringList &CmdArgs) const {
329   // Darwin only supports the compiler-rt based runtime libraries.
330   switch (GetRuntimeLibType(Args)) {
331   case ToolChain::RLT_CompilerRT:
332     break;
333   default:
334     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
335       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
336     return;
337   }
338
339   // Darwin doesn't support real static executables, don't link any runtime
340   // libraries with -static.
341   if (Args.hasArg(options::OPT_static) ||
342       Args.hasArg(options::OPT_fapple_kext) ||
343       Args.hasArg(options::OPT_mkernel))
344     return;
345
346   // Reject -static-libgcc for now, we can deal with this when and if someone
347   // cares. This is useful in situations where someone wants to statically link
348   // something like libstdc++, and needs its runtime support routines.
349   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
350     getDriver().Diag(diag::err_drv_unsupported_opt)
351       << A->getAsString(Args);
352     return;
353   }
354
355   // If we are building profile support, link that library in.
356   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
357                    false) ||
358       Args.hasArg(options::OPT_fprofile_generate) ||
359       Args.hasArg(options::OPT_fprofile_instr_generate) ||
360       Args.hasArg(options::OPT_fcreate_profile) ||
361       Args.hasArg(options::OPT_coverage)) {
362     // Select the appropriate runtime library for the target.
363     if (isTargetIOSBased())
364       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
365     else
366       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
367   }
368
369   const SanitizerArgs &Sanitize = getSanitizerArgs();
370
371   // Add Ubsan runtime library, if required.
372   if (Sanitize.needsUbsanRt()) {
373     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
374     if (isTargetIOSBased()) {
375       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
376         << "-fsanitize=undefined";
377     } else {
378       assert(isTargetMacOS() && "unexpected non OS X target");
379       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
380
381       // The Ubsan runtime library requires C++.
382       AddCXXStdlibLibArgs(Args, CmdArgs);
383     }
384   }
385
386   // Add ASAN runtime library, if required. Dynamic libraries and bundles
387   // should not be linked with the runtime library.
388   if (Sanitize.needsAsanRt()) {
389     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
390     if (isTargetIPhoneOS()) {
391       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
392         << "-fsanitize=address";
393     } else {
394       if (!Args.hasArg(options::OPT_dynamiclib) &&
395           !Args.hasArg(options::OPT_bundle)) {
396         // The ASAN runtime library requires C++.
397         AddCXXStdlibLibArgs(Args, CmdArgs);
398       }
399       if (isTargetMacOS()) {
400         AddLinkRuntimeLib(Args, CmdArgs,
401                           "libclang_rt.asan_osx_dynamic.dylib",
402                           /*AlwaysLink*/ true, /*IsEmbedded*/ false,
403                           /*AddRPath*/ true);
404       } else {
405         if (isTargetIOSSimulator()) {
406           AddLinkRuntimeLib(Args, CmdArgs,
407                             "libclang_rt.asan_iossim_dynamic.dylib",
408                             /*AlwaysLink*/ true, /*IsEmbedded*/ false,
409                             /*AddRPath*/ true);
410         }
411       }
412     }
413   }
414
415   // Otherwise link libSystem, then the dynamic runtime library, and finally any
416   // target specific static runtime library.
417   CmdArgs.push_back("-lSystem");
418
419   // Select the dynamic runtime library and the target specific static library.
420   if (isTargetIOSBased()) {
421     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
422     // it never went into the SDK.
423     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
424     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
425         getTriple().getArch() != llvm::Triple::aarch64)
426       CmdArgs.push_back("-lgcc_s.1");
427
428     // We currently always need a static runtime library for iOS.
429     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
430   } else {
431     assert(isTargetMacOS() && "unexpected non MacOS platform");
432     // The dynamic runtime library was merged with libSystem for 10.6 and
433     // beyond; only 10.4 and 10.5 need an additional runtime library.
434     if (isMacosxVersionLT(10, 5))
435       CmdArgs.push_back("-lgcc_s.10.4");
436     else if (isMacosxVersionLT(10, 6))
437       CmdArgs.push_back("-lgcc_s.10.5");
438
439     // For OS X, we thought we would only need a static runtime library when
440     // targeting 10.4, to provide versions of the static functions which were
441     // omitted from 10.4.dylib.
442     //
443     // Unfortunately, that turned out to not be true, because Darwin system
444     // headers can still use eprintf on i386, and it is not exported from
445     // libSystem. Therefore, we still must provide a runtime library just for
446     // the tiny tiny handful of projects that *might* use that symbol.
447     if (isMacosxVersionLT(10, 5)) {
448       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
449     } else {
450       if (getTriple().getArch() == llvm::Triple::x86)
451         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
452       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
453     }
454   }
455 }
456
457 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
458   const OptTable &Opts = getDriver().getOpts();
459
460   // Support allowing the SDKROOT environment variable used by xcrun and other
461   // Xcode tools to define the default sysroot, by making it the default for
462   // isysroot.
463   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
464     // Warn if the path does not exist.
465     if (!llvm::sys::fs::exists(A->getValue()))
466       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
467   } else {
468     if (char *env = ::getenv("SDKROOT")) {
469       // We only use this value as the default if it is an absolute path,
470       // exists, and it is not the root path.
471       if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
472           StringRef(env) != "/") {
473         Args.append(Args.MakeSeparateArg(
474                       nullptr, Opts.getOption(options::OPT_isysroot), env));
475       }
476     }
477   }
478
479   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
480   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
481
482   if (OSXVersion && iOSVersion) {
483     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
484           << OSXVersion->getAsString(Args)
485           << iOSVersion->getAsString(Args);
486     iOSVersion = nullptr;
487   } else if (!OSXVersion && !iOSVersion) {
488     // If no deployment target was specified on the command line, check for
489     // environment defines.
490     StringRef OSXTarget;
491     StringRef iOSTarget;
492     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
493       OSXTarget = env;
494     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
495       iOSTarget = env;
496
497     // If no '-miphoneos-version-min' specified on the command line and
498     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
499     // based on -isysroot.
500     if (iOSTarget.empty()) {
501       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
502         StringRef first, second;
503         StringRef isysroot = A->getValue();
504         std::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
505         if (second != "")
506           iOSTarget = second.substr(0,3);
507       }
508     }
509
510     // If no OSX or iOS target has been specified and we're compiling for armv7,
511     // go ahead as assume we're targeting iOS.
512     StringRef MachOArchName = getMachOArchName(Args);
513     if (OSXTarget.empty() && iOSTarget.empty() &&
514         (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
515          MachOArchName == "arm64"))
516         iOSTarget = iOSVersionMin;
517
518     // Allow conflicts among OSX and iOS for historical reasons, but choose the
519     // default platform.
520     if (!OSXTarget.empty() && !iOSTarget.empty()) {
521       if (getTriple().getArch() == llvm::Triple::arm ||
522           getTriple().getArch() == llvm::Triple::aarch64 ||
523           getTriple().getArch() == llvm::Triple::thumb)
524         OSXTarget = "";
525       else
526         iOSTarget = "";
527     }
528
529     if (!OSXTarget.empty()) {
530       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
531       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
532       Args.append(OSXVersion);
533     } else if (!iOSTarget.empty()) {
534       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
535       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
536       Args.append(iOSVersion);
537     } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
538                MachOArchName != "armv7em") {
539       // Otherwise, assume we are targeting OS X.
540       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
541       OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin);
542       Args.append(OSXVersion);
543     }
544   }
545
546   DarwinPlatformKind Platform;
547   if (OSXVersion)
548     Platform = MacOS;
549   else if (iOSVersion)
550     Platform = IPhoneOS;
551   else
552     llvm_unreachable("Unable to infer Darwin variant");
553
554   // Set the tool chain target information.
555   unsigned Major, Minor, Micro;
556   bool HadExtra;
557   if (Platform == MacOS) {
558     assert(!iOSVersion && "Unknown target platform!");
559     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
560                                    Micro, HadExtra) || HadExtra ||
561         Major != 10 || Minor >= 100 || Micro >= 100)
562       getDriver().Diag(diag::err_drv_invalid_version_number)
563         << OSXVersion->getAsString(Args);
564   } else if (Platform == IPhoneOS) {
565     assert(iOSVersion && "Unknown target platform!");
566     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor,
567                                    Micro, HadExtra) || HadExtra ||
568         Major >= 10 || Minor >= 100 || Micro >= 100)
569       getDriver().Diag(diag::err_drv_invalid_version_number)
570         << iOSVersion->getAsString(Args);
571   } else
572     llvm_unreachable("unknown kind of Darwin platform");
573
574   // Recognize iOS targets with an x86 architecture as the iOS simulator.
575   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
576                      getTriple().getArch() == llvm::Triple::x86_64))
577     Platform = IPhoneOSSimulator;
578
579   setTarget(Platform, Major, Minor, Micro);
580 }
581
582 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
583                                       ArgStringList &CmdArgs) const {
584   CXXStdlibType Type = GetCXXStdlibType(Args);
585
586   switch (Type) {
587   case ToolChain::CST_Libcxx:
588     CmdArgs.push_back("-lc++");
589     break;
590
591   case ToolChain::CST_Libstdcxx: {
592     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
593     // it was previously found in the gcc lib dir. However, for all the Darwin
594     // platforms we care about it was -lstdc++.6, so we search for that
595     // explicitly if we can't see an obvious -lstdc++ candidate.
596
597     // Check in the sysroot first.
598     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
599       SmallString<128> P(A->getValue());
600       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
601
602       if (!llvm::sys::fs::exists(P.str())) {
603         llvm::sys::path::remove_filename(P);
604         llvm::sys::path::append(P, "libstdc++.6.dylib");
605         if (llvm::sys::fs::exists(P.str())) {
606           CmdArgs.push_back(Args.MakeArgString(P.str()));
607           return;
608         }
609       }
610     }
611
612     // Otherwise, look in the root.
613     // FIXME: This should be removed someday when we don't have to care about
614     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
615     if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
616         llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
617       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
618       return;
619     }
620
621     // Otherwise, let the linker search.
622     CmdArgs.push_back("-lstdc++");
623     break;
624   }
625   }
626 }
627
628 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
629                                    ArgStringList &CmdArgs) const {
630
631   // For Darwin platforms, use the compiler-rt-based support library
632   // instead of the gcc-provided one (which is also incidentally
633   // only present in the gcc lib dir, which makes it hard to find).
634
635   SmallString<128> P(getDriver().ResourceDir);
636   llvm::sys::path::append(P, "lib", "darwin");
637
638   // Use the newer cc_kext for iOS ARM after 6.0.
639   if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
640       getTriple().getArch() == llvm::Triple::aarch64 ||
641       !isIPhoneOSVersionLT(6, 0)) {
642     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
643   } else {
644     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
645   }
646
647   // For now, allow missing resource libraries to support developers who may
648   // not have compiler-rt checked out or integrated into their build.
649   if (llvm::sys::fs::exists(P.str()))
650     CmdArgs.push_back(Args.MakeArgString(P.str()));
651 }
652
653 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
654                                      const char *BoundArch) const {
655   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
656   const OptTable &Opts = getDriver().getOpts();
657
658   // FIXME: We really want to get out of the tool chain level argument
659   // translation business, as it makes the driver functionality much
660   // more opaque. For now, we follow gcc closely solely for the
661   // purpose of easily achieving feature parity & testability. Once we
662   // have something that works, we should reevaluate each translation
663   // and try to push it down into tool specific logic.
664
665   for (Arg *A : Args) {
666     if (A->getOption().matches(options::OPT_Xarch__)) {
667       // Skip this argument unless the architecture matches either the toolchain
668       // triple arch, or the arch being bound.
669       llvm::Triple::ArchType XarchArch =
670         tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
671       if (!(XarchArch == getArch()  ||
672             (BoundArch && XarchArch ==
673              tools::darwin::getArchTypeForMachOArchName(BoundArch))))
674         continue;
675
676       Arg *OriginalArg = A;
677       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
678       unsigned Prev = Index;
679       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
680
681       // If the argument parsing failed or more than one argument was
682       // consumed, the -Xarch_ argument's parameter tried to consume
683       // extra arguments. Emit an error and ignore.
684       //
685       // We also want to disallow any options which would alter the
686       // driver behavior; that isn't going to work in our model. We
687       // use isDriverOption() as an approximation, although things
688       // like -O4 are going to slip through.
689       if (!XarchArg || Index > Prev + 1) {
690         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
691           << A->getAsString(Args);
692         continue;
693       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
694         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
695           << A->getAsString(Args);
696         continue;
697       }
698
699       XarchArg->setBaseArg(A);
700
701       A = XarchArg.release();
702       DAL->AddSynthesizedArg(A);
703
704       // Linker input arguments require custom handling. The problem is that we
705       // have already constructed the phase actions, so we can not treat them as
706       // "input arguments".
707       if (A->getOption().hasFlag(options::LinkerInput)) {
708         // Convert the argument into individual Zlinker_input_args.
709         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
710           DAL->AddSeparateArg(OriginalArg,
711                               Opts.getOption(options::OPT_Zlinker_input),
712                               A->getValue(i));
713
714         }
715         continue;
716       }
717     }
718
719     // Sob. These is strictly gcc compatible for the time being. Apple
720     // gcc translates options twice, which means that self-expanding
721     // options add duplicates.
722     switch ((options::ID) A->getOption().getID()) {
723     default:
724       DAL->append(A);
725       break;
726
727     case options::OPT_mkernel:
728     case options::OPT_fapple_kext:
729       DAL->append(A);
730       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
731       break;
732
733     case options::OPT_dependency_file:
734       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
735                           A->getValue());
736       break;
737
738     case options::OPT_gfull:
739       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
740       DAL->AddFlagArg(A,
741                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
742       break;
743
744     case options::OPT_gused:
745       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
746       DAL->AddFlagArg(A,
747              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
748       break;
749
750     case options::OPT_shared:
751       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
752       break;
753
754     case options::OPT_fconstant_cfstrings:
755       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
756       break;
757
758     case options::OPT_fno_constant_cfstrings:
759       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
760       break;
761
762     case options::OPT_Wnonportable_cfstrings:
763       DAL->AddFlagArg(A,
764                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
765       break;
766
767     case options::OPT_Wno_nonportable_cfstrings:
768       DAL->AddFlagArg(A,
769                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
770       break;
771
772     case options::OPT_fpascal_strings:
773       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
774       break;
775
776     case options::OPT_fno_pascal_strings:
777       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
778       break;
779     }
780   }
781
782   if (getTriple().getArch() == llvm::Triple::x86 ||
783       getTriple().getArch() == llvm::Triple::x86_64)
784     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
785       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
786                         "core2");
787
788   // Add the arch options based on the particular spelling of -arch, to match
789   // how the driver driver works.
790   if (BoundArch) {
791     StringRef Name = BoundArch;
792     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
793     const Option MArch = Opts.getOption(options::OPT_march_EQ);
794
795     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
796     // which defines the list of which architectures we accept.
797     if (Name == "ppc")
798       ;
799     else if (Name == "ppc601")
800       DAL->AddJoinedArg(nullptr, MCpu, "601");
801     else if (Name == "ppc603")
802       DAL->AddJoinedArg(nullptr, MCpu, "603");
803     else if (Name == "ppc604")
804       DAL->AddJoinedArg(nullptr, MCpu, "604");
805     else if (Name == "ppc604e")
806       DAL->AddJoinedArg(nullptr, MCpu, "604e");
807     else if (Name == "ppc750")
808       DAL->AddJoinedArg(nullptr, MCpu, "750");
809     else if (Name == "ppc7400")
810       DAL->AddJoinedArg(nullptr, MCpu, "7400");
811     else if (Name == "ppc7450")
812       DAL->AddJoinedArg(nullptr, MCpu, "7450");
813     else if (Name == "ppc970")
814       DAL->AddJoinedArg(nullptr, MCpu, "970");
815
816     else if (Name == "ppc64" || Name == "ppc64le")
817       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
818
819     else if (Name == "i386")
820       ;
821     else if (Name == "i486")
822       DAL->AddJoinedArg(nullptr, MArch, "i486");
823     else if (Name == "i586")
824       DAL->AddJoinedArg(nullptr, MArch, "i586");
825     else if (Name == "i686")
826       DAL->AddJoinedArg(nullptr, MArch, "i686");
827     else if (Name == "pentium")
828       DAL->AddJoinedArg(nullptr, MArch, "pentium");
829     else if (Name == "pentium2")
830       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
831     else if (Name == "pentpro")
832       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
833     else if (Name == "pentIIm3")
834       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
835
836     else if (Name == "x86_64")
837       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
838     else if (Name == "x86_64h") {
839       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
840       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
841     }
842
843     else if (Name == "arm")
844       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
845     else if (Name == "armv4t")
846       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
847     else if (Name == "armv5")
848       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
849     else if (Name == "xscale")
850       DAL->AddJoinedArg(nullptr, MArch, "xscale");
851     else if (Name == "armv6")
852       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
853     else if (Name == "armv6m")
854       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
855     else if (Name == "armv7")
856       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
857     else if (Name == "armv7em")
858       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
859     else if (Name == "armv7k")
860       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
861     else if (Name == "armv7m")
862       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
863     else if (Name == "armv7s")
864       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
865   }
866
867   return DAL;
868 }
869
870 void MachO::AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args,
871                                   llvm::opt::ArgStringList &CmdArgs) const {
872   // Embedded targets are simple at the moment, not supporting sanitizers and
873   // with different libraries for each member of the product { static, PIC } x
874   // { hard-float, soft-float }
875   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
876   CompilerRT +=
877       tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
878           ? "hard"
879           : "soft";
880   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
881
882   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
883 }
884
885
886 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
887                                       const char *BoundArch) const {
888   // First get the generic Apple args, before moving onto Darwin-specific ones.
889   DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
890   const OptTable &Opts = getDriver().getOpts();
891
892   // If no architecture is bound, none of the translations here are relevant.
893   if (!BoundArch)
894     return DAL;
895
896   // Add an explicit version min argument for the deployment target. We do this
897   // after argument translation because -Xarch_ arguments may add a version min
898   // argument.
899   AddDeploymentTarget(*DAL);
900
901   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
902   // FIXME: It would be far better to avoid inserting those -static arguments,
903   // but we can't check the deployment target in the translation code until
904   // it is set here.
905   if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
906     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
907       Arg *A = *it;
908       ++it;
909       if (A->getOption().getID() != options::OPT_mkernel &&
910           A->getOption().getID() != options::OPT_fapple_kext)
911         continue;
912       assert(it != ie && "unexpected argument translation");
913       A = *it;
914       assert(A->getOption().getID() == options::OPT_static &&
915              "missing expected -static argument");
916       it = DAL->getArgs().erase(it);
917     }
918   }
919
920   // Default to use libc++ on OS X 10.9+ and iOS 7+.
921   if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
922        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
923       !Args.getLastArg(options::OPT_stdlib_EQ))
924     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
925                       "libc++");
926
927   // Validate the C++ standard library choice.
928   CXXStdlibType Type = GetCXXStdlibType(*DAL);
929   if (Type == ToolChain::CST_Libcxx) {
930     // Check whether the target provides libc++.
931     StringRef where;
932
933     // Complain about targeting iOS < 5.0 in any way.
934     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
935       where = "iOS 5.0";
936
937     if (where != StringRef()) {
938       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
939         << where;
940     }
941   }
942
943   return DAL;
944 }
945
946 bool MachO::IsUnwindTablesDefault() const {
947   return getArch() == llvm::Triple::x86_64;
948 }
949
950 bool MachO::UseDwarfDebugFlags() const {
951   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
952     return S[0] != '\0';
953   return false;
954 }
955
956 bool Darwin::UseSjLjExceptions() const {
957   // Darwin uses SjLj exceptions on ARM.
958   return (getTriple().getArch() == llvm::Triple::arm ||
959           getTriple().getArch() == llvm::Triple::thumb);
960 }
961
962 bool MachO::isPICDefault() const {
963   return true;
964 }
965
966 bool MachO::isPIEDefault() const {
967   return false;
968 }
969
970 bool MachO::isPICDefaultForced() const {
971   return (getArch() == llvm::Triple::x86_64 ||
972           getArch() == llvm::Triple::aarch64);
973 }
974
975 bool MachO::SupportsProfiling() const {
976   // Profiling instrumentation is only supported on x86.
977   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
978 }
979
980 void Darwin::addMinVersionArgs(const llvm::opt::ArgList &Args,
981                                llvm::opt::ArgStringList &CmdArgs) const {
982   VersionTuple TargetVersion = getTargetVersion();
983
984   if (isTargetIOSSimulator())
985     CmdArgs.push_back("-ios_simulator_version_min");
986   else if (isTargetIOSBased())
987     CmdArgs.push_back("-iphoneos_version_min");
988   else {
989     assert(isTargetMacOS() && "unexpected target");
990     CmdArgs.push_back("-macosx_version_min");
991   }
992
993   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
994 }
995
996 void Darwin::addStartObjectFileArgs(const llvm::opt::ArgList &Args,
997                                     llvm::opt::ArgStringList &CmdArgs) const {
998   // Derived from startfile spec.
999   if (Args.hasArg(options::OPT_dynamiclib)) {
1000     // Derived from darwin_dylib1 spec.
1001     if (isTargetIOSSimulator()) {
1002       ; // iOS simulator does not need dylib1.o.
1003     } else if (isTargetIPhoneOS()) {
1004       if (isIPhoneOSVersionLT(3, 1))
1005         CmdArgs.push_back("-ldylib1.o");
1006     } else {
1007       if (isMacosxVersionLT(10, 5))
1008         CmdArgs.push_back("-ldylib1.o");
1009       else if (isMacosxVersionLT(10, 6))
1010         CmdArgs.push_back("-ldylib1.10.5.o");
1011     }
1012   } else {
1013     if (Args.hasArg(options::OPT_bundle)) {
1014       if (!Args.hasArg(options::OPT_static)) {
1015         // Derived from darwin_bundle1 spec.
1016         if (isTargetIOSSimulator()) {
1017           ; // iOS simulator does not need bundle1.o.
1018         } else if (isTargetIPhoneOS()) {
1019           if (isIPhoneOSVersionLT(3, 1))
1020             CmdArgs.push_back("-lbundle1.o");
1021         } else {
1022           if (isMacosxVersionLT(10, 6))
1023             CmdArgs.push_back("-lbundle1.o");
1024         }
1025       }
1026     } else {
1027       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1028         if (Args.hasArg(options::OPT_static) ||
1029             Args.hasArg(options::OPT_object) ||
1030             Args.hasArg(options::OPT_preload)) {
1031           CmdArgs.push_back("-lgcrt0.o");
1032         } else {
1033           CmdArgs.push_back("-lgcrt1.o");
1034
1035           // darwin_crt2 spec is empty.
1036         }
1037         // By default on OS X 10.8 and later, we don't link with a crt1.o
1038         // file and the linker knows to use _main as the entry point.  But,
1039         // when compiling with -pg, we need to link with the gcrt1.o file,
1040         // so pass the -no_new_main option to tell the linker to use the
1041         // "start" symbol as the entry point.
1042         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1043           CmdArgs.push_back("-no_new_main");
1044       } else {
1045         if (Args.hasArg(options::OPT_static) ||
1046             Args.hasArg(options::OPT_object) ||
1047             Args.hasArg(options::OPT_preload)) {
1048           CmdArgs.push_back("-lcrt0.o");
1049         } else {
1050           // Derived from darwin_crt1 spec.
1051           if (isTargetIOSSimulator()) {
1052             ; // iOS simulator does not need crt1.o.
1053           } else if (isTargetIPhoneOS()) {
1054             if (getArch() == llvm::Triple::aarch64)
1055               ; // iOS does not need any crt1 files for arm64
1056             else if (isIPhoneOSVersionLT(3, 1))
1057               CmdArgs.push_back("-lcrt1.o");
1058             else if (isIPhoneOSVersionLT(6, 0))
1059               CmdArgs.push_back("-lcrt1.3.1.o");
1060           } else {
1061             if (isMacosxVersionLT(10, 5))
1062               CmdArgs.push_back("-lcrt1.o");
1063             else if (isMacosxVersionLT(10, 6))
1064               CmdArgs.push_back("-lcrt1.10.5.o");
1065             else if (isMacosxVersionLT(10, 8))
1066               CmdArgs.push_back("-lcrt1.10.6.o");
1067
1068             // darwin_crt2 spec is empty.
1069           }
1070         }
1071       }
1072     }
1073   }
1074
1075   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1076       isMacosxVersionLT(10, 5)) {
1077     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1078     CmdArgs.push_back(Str);
1079   }
1080 }
1081
1082 bool Darwin::SupportsObjCGC() const {
1083   return isTargetMacOS();
1084 }
1085
1086 void Darwin::CheckObjCARC() const {
1087   if (isTargetIOSBased()|| (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1088     return;
1089   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1090 }
1091
1092 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1093 /// all subcommands; this relies on gcc translating the majority of
1094 /// command line options.
1095
1096 /// \brief Parse a GCCVersion object out of a string of text.
1097 ///
1098 /// This is the primary means of forming GCCVersion objects.
1099 /*static*/
1100 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1101   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1102   std::pair<StringRef, StringRef> First = VersionText.split('.');
1103   std::pair<StringRef, StringRef> Second = First.second.split('.');
1104
1105   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1106   if (First.first.getAsInteger(10, GoodVersion.Major) ||
1107       GoodVersion.Major < 0)
1108     return BadVersion;
1109   GoodVersion.MajorStr = First.first.str();
1110   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1111       GoodVersion.Minor < 0)
1112     return BadVersion;
1113   GoodVersion.MinorStr = Second.first.str();
1114
1115   // First look for a number prefix and parse that if present. Otherwise just
1116   // stash the entire patch string in the suffix, and leave the number
1117   // unspecified. This covers versions strings such as:
1118   //   4.4
1119   //   4.4.0
1120   //   4.4.x
1121   //   4.4.2-rc4
1122   //   4.4.x-patched
1123   // And retains any patch number it finds.
1124   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1125   if (!PatchText.empty()) {
1126     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1127       // Try to parse the number and any suffix.
1128       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1129           GoodVersion.Patch < 0)
1130         return BadVersion;
1131       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1132     }
1133   }
1134
1135   return GoodVersion;
1136 }
1137
1138 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1139 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1140                                           int RHSPatch,
1141                                           StringRef RHSPatchSuffix) const {
1142   if (Major != RHSMajor)
1143     return Major < RHSMajor;
1144   if (Minor != RHSMinor)
1145     return Minor < RHSMinor;
1146   if (Patch != RHSPatch) {
1147     // Note that versions without a specified patch sort higher than those with
1148     // a patch.
1149     if (RHSPatch == -1)
1150       return true;
1151     if (Patch == -1)
1152       return false;
1153
1154     // Otherwise just sort on the patch itself.
1155     return Patch < RHSPatch;
1156   }
1157   if (PatchSuffix != RHSPatchSuffix) {
1158     // Sort empty suffixes higher.
1159     if (RHSPatchSuffix.empty())
1160       return true;
1161     if (PatchSuffix.empty())
1162       return false;
1163
1164     // Provide a lexicographic sort to make this a total ordering.
1165     return PatchSuffix < RHSPatchSuffix;
1166   }
1167
1168   // The versions are equal.
1169   return false;
1170 }
1171
1172 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1173   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1174   if (A)
1175     return A->getValue();
1176   return GCC_INSTALL_PREFIX;
1177 }
1178
1179 /// \brief Initialize a GCCInstallationDetector from the driver.
1180 ///
1181 /// This performs all of the autodetection and sets up the various paths.
1182 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1183 ///
1184 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1185 /// should instead pull the target out of the driver. This is currently
1186 /// necessary because the driver doesn't store the final version of the target
1187 /// triple.
1188 void
1189 Generic_GCC::GCCInstallationDetector::init(
1190     const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
1191   llvm::Triple BiarchVariantTriple =
1192       TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1193                                  : TargetTriple.get32BitArchVariant();
1194   // The library directories which may contain GCC installations.
1195   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1196   // The compatible GCC triples for this particular architecture.
1197   SmallVector<StringRef, 16> CandidateTripleAliases;
1198   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1199   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1200                            CandidateTripleAliases, CandidateBiarchLibDirs,
1201                            CandidateBiarchTripleAliases);
1202
1203   // Compute the set of prefixes for our search.
1204   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1205                                        D.PrefixDirs.end());
1206
1207   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1208   if (GCCToolchainDir != "") {
1209     if (GCCToolchainDir.back() == '/')
1210       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1211
1212     Prefixes.push_back(GCCToolchainDir);
1213   } else {
1214     // If we have a SysRoot, try that first.
1215     if (!D.SysRoot.empty()) {
1216       Prefixes.push_back(D.SysRoot);
1217       Prefixes.push_back(D.SysRoot + "/usr");
1218     }
1219
1220     // Then look for gcc installed alongside clang.
1221     Prefixes.push_back(D.InstalledDir + "/..");
1222
1223     // And finally in /usr.
1224     if (D.SysRoot.empty())
1225       Prefixes.push_back("/usr");
1226   }
1227
1228   // Loop over the various components which exist and select the best GCC
1229   // installation available. GCC installs are ranked by version number.
1230   Version = GCCVersion::Parse("0.0.0");
1231   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1232     if (!llvm::sys::fs::exists(Prefixes[i]))
1233       continue;
1234     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1235       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1236       if (!llvm::sys::fs::exists(LibDir))
1237         continue;
1238       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1239         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1240                                CandidateTripleAliases[k]);
1241     }
1242     for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1243       const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1244       if (!llvm::sys::fs::exists(LibDir))
1245         continue;
1246       for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1247            ++k)
1248         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1249                                CandidateBiarchTripleAliases[k],
1250                                /*NeedsBiarchSuffix=*/ true);
1251     }
1252   }
1253 }
1254
1255 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1256   for (const auto &InstallPath : CandidateGCCInstallPaths)
1257     OS << "Found candidate GCC installation: " << InstallPath << "\n";
1258
1259   if (!GCCInstallPath.empty())
1260     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1261
1262   for (const auto &Multilib : Multilibs)
1263     OS << "Candidate multilib: " << Multilib << "\n";
1264
1265   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1266     OS << "Selected multilib: " << SelectedMultilib << "\n";
1267 }
1268
1269 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1270   if (BiarchSibling.hasValue()) {
1271     M = BiarchSibling.getValue();
1272     return true;
1273   }
1274   return false;
1275 }
1276
1277 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1278     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1279     SmallVectorImpl<StringRef> &LibDirs,
1280     SmallVectorImpl<StringRef> &TripleAliases,
1281     SmallVectorImpl<StringRef> &BiarchLibDirs,
1282     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1283   // Declare a bunch of static data sets that we'll select between below. These
1284   // are specifically designed to always refer to string literals to avoid any
1285   // lifetime or initialization issues.
1286   static const char *const AArch64LibDirs[] = { "/lib64", "/lib" };
1287   static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1288                                                 "aarch64-linux-gnu",
1289                                                 "aarch64-linux-android",
1290                                                 "aarch64-redhat-linux" };
1291   static const char *const AArch64beLibDirs[] = { "/lib" };
1292   static const char *const AArch64beTriples[] = { "aarch64_be-none-linux-gnu",
1293                                                   "aarch64_be-linux-gnu" };
1294
1295   static const char *const ARMLibDirs[] = { "/lib" };
1296   static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1297                                             "arm-linux-androideabi" };
1298   static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1299                                               "armv7hl-redhat-linux-gnueabi" };
1300   static const char *const ARMebLibDirs[] = { "/lib" };
1301   static const char *const ARMebTriples[] = { "armeb-linux-gnueabi",
1302                                               "armeb-linux-androideabi" };
1303   static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
1304                                                 "armebv7hl-redhat-linux-gnueabi" };
1305
1306   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1307   static const char *const X86_64Triples[] = {
1308     "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1309     "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1310     "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
1311     "x86_64-linux-android", "x86_64-unknown-linux"
1312   };
1313   static const char *const X32LibDirs[] = { "/libx32" };
1314   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1315   static const char *const X86Triples[] = {
1316     "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1317     "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1318     "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1319     "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
1320   };
1321
1322   static const char *const MIPSLibDirs[] = { "/lib" };
1323   static const char *const MIPSTriples[] = { "mips-linux-gnu",
1324                                              "mips-mti-linux-gnu",
1325                                              "mips-img-linux-gnu" };
1326   static const char *const MIPSELLibDirs[] = { "/lib" };
1327   static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1328                                                "mipsel-linux-android",
1329                                                "mips-img-linux-gnu" };
1330
1331   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1332   static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
1333                                                "mips-mti-linux-gnu",
1334                                                "mips-img-linux-gnu",
1335                                                "mips64-linux-gnuabi64" };
1336   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1337   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
1338                                                  "mips-mti-linux-gnu",
1339                                                  "mips-img-linux-gnu",
1340                                                  "mips64el-linux-android",
1341                                                  "mips64el-linux-gnuabi64" };
1342
1343   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1344   static const char *const PPCTriples[] = {
1345     "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1346     "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1347   };
1348   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1349   static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1350                                               "powerpc64-unknown-linux-gnu",
1351                                               "powerpc64-suse-linux",
1352                                               "ppc64-redhat-linux" };
1353   static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
1354   static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
1355                                                 "powerpc64le-unknown-linux-gnu",
1356                                                 "powerpc64le-suse-linux",
1357                                                 "ppc64le-redhat-linux" };
1358
1359   static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
1360   static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
1361                                                 "sparcv8-linux-gnu" };
1362   static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
1363   static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
1364                                                 "sparcv9-linux-gnu" };
1365
1366   static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1367   static const char *const SystemZTriples[] = {
1368     "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1369     "s390x-suse-linux", "s390x-redhat-linux"
1370   };
1371
1372   using std::begin;
1373   using std::end;
1374
1375   switch (TargetTriple.getArch()) {
1376   case llvm::Triple::aarch64:
1377     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1378     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1379     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1380     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1381     break;
1382   case llvm::Triple::aarch64_be:
1383     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1384     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1385     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1386     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1387     break;
1388   case llvm::Triple::arm:
1389   case llvm::Triple::thumb:
1390     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1391     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1392       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1393     } else {
1394       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1395     }
1396     break;
1397   case llvm::Triple::armeb:
1398   case llvm::Triple::thumbeb:
1399     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1400     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1401       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1402     } else {
1403       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1404     }
1405     break;
1406   case llvm::Triple::x86_64:
1407     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1408     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1409     // x32 is always available when x86_64 is available, so adding it as
1410     // secondary arch with x86_64 triples
1411     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1412       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1413       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1414     } else {
1415       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1416       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1417     }
1418     break;
1419   case llvm::Triple::x86:
1420     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1421     TripleAliases.append(begin(X86Triples), end(X86Triples));
1422     BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1423     BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1424     break;
1425   case llvm::Triple::mips:
1426     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1427     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1428     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1429     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1430     break;
1431   case llvm::Triple::mipsel:
1432     LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1433     TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1434     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1435     BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1436     BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1437     break;
1438   case llvm::Triple::mips64:
1439     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1440     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1441     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1442     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1443     break;
1444   case llvm::Triple::mips64el:
1445     LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1446     TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1447     BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1448     BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1449     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1450     break;
1451   case llvm::Triple::ppc:
1452     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1453     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1454     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1455     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1456     break;
1457   case llvm::Triple::ppc64:
1458     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1459     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1460     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1461     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1462     break;
1463   case llvm::Triple::ppc64le:
1464     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1465     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1466     break;
1467   case llvm::Triple::sparc:
1468     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1469     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1470     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1471     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1472     break;
1473   case llvm::Triple::sparcv9:
1474     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1475     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1476     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1477     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1478     break;
1479   case llvm::Triple::systemz:
1480     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1481     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1482     break;
1483
1484   default:
1485     // By default, just rely on the standard lib directories and the original
1486     // triple.
1487     break;
1488   }
1489
1490   // Always append the drivers target triple to the end, in case it doesn't
1491   // match any of our aliases.
1492   TripleAliases.push_back(TargetTriple.str());
1493
1494   // Also include the multiarch variant if it's different.
1495   if (TargetTriple.str() != BiarchTriple.str())
1496     BiarchTripleAliases.push_back(BiarchTriple.str());
1497 }
1498
1499 namespace {
1500 // Filter to remove Multilibs that don't exist as a suffix to Path
1501 class FilterNonExistent : public MultilibSet::FilterCallback {
1502   std::string Base;
1503 public:
1504   FilterNonExistent(std::string Base) : Base(Base) {}
1505   bool operator()(const Multilib &M) const override {
1506     return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
1507   }
1508 };
1509 } // end anonymous namespace
1510
1511 static void addMultilibFlag(bool Enabled, const char *const Flag,
1512                             std::vector<std::string> &Flags) {
1513   if (Enabled)
1514     Flags.push_back(std::string("+") + Flag);
1515   else
1516     Flags.push_back(std::string("-") + Flag);
1517 }
1518
1519 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1520   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1521          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1522 }
1523
1524 static bool isMips32(llvm::Triple::ArchType Arch) {
1525   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1526 }
1527
1528 static bool isMips64(llvm::Triple::ArchType Arch) {
1529   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1530 }
1531
1532 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1533   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1534 }
1535
1536 static bool isMips16(const ArgList &Args) {
1537   Arg *A = Args.getLastArg(options::OPT_mips16,
1538                            options::OPT_mno_mips16);
1539   return A && A->getOption().matches(options::OPT_mips16);
1540 }
1541
1542 static bool isMicroMips(const ArgList &Args) {
1543   Arg *A = Args.getLastArg(options::OPT_mmicromips,
1544                            options::OPT_mno_micromips);
1545   return A && A->getOption().matches(options::OPT_mmicromips);
1546 }
1547
1548 struct DetectedMultilibs {
1549   /// The set of multilibs that the detected installation supports.
1550   MultilibSet Multilibs;
1551
1552   /// The primary multilib appropriate for the given flags.
1553   Multilib SelectedMultilib;
1554
1555   /// On Biarch systems, this corresponds to the default multilib when
1556   /// targeting the non-default multilib. Otherwise, it is empty.
1557   llvm::Optional<Multilib> BiarchSibling;
1558 };
1559
1560 static Multilib makeMultilib(StringRef commonSuffix) {
1561   return Multilib(commonSuffix, commonSuffix, commonSuffix);
1562 }
1563
1564 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
1565                               const llvm::opt::ArgList &Args,
1566                               DetectedMultilibs &Result) {
1567   // Some MIPS toolchains put libraries and object files compiled
1568   // using different options in to the sub-directoris which names
1569   // reflects the flags used for compilation. For example sysroot
1570   // directory might looks like the following examples:
1571   //
1572   // /usr
1573   //   /lib      <= crt*.o files compiled with '-mips32'
1574   // /mips16
1575   //   /usr
1576   //     /lib    <= crt*.o files compiled with '-mips16'
1577   //   /el
1578   //     /usr
1579   //       /lib  <= crt*.o files compiled with '-mips16 -EL'
1580   //
1581   // or
1582   //
1583   // /usr
1584   //   /lib      <= crt*.o files compiled with '-mips32r2'
1585   // /mips16
1586   //   /usr
1587   //     /lib    <= crt*.o files compiled with '-mips32r2 -mips16'
1588   // /mips32
1589   //     /usr
1590   //       /lib  <= crt*.o files compiled with '-mips32'
1591
1592   FilterNonExistent NonExistent(Path);
1593
1594   // Check for FSF toolchain multilibs
1595   MultilibSet FSFMipsMultilibs;
1596   {
1597     auto MArchMips32 = makeMultilib("/mips32")
1598       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32");
1599
1600     auto MArchMicroMips = makeMultilib("/micromips")
1601       .flag("+m32").flag("-m64").flag("+mmicromips");
1602
1603     auto MArchMips64r2 = makeMultilib("/mips64r2")
1604       .flag("-m32").flag("+m64").flag("+march=mips64r2");
1605
1606     auto MArchMips64 = makeMultilib("/mips64")
1607       .flag("-m32").flag("+m64").flag("-march=mips64r2");
1608
1609     auto MArchDefault = makeMultilib("")
1610       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32r2");
1611
1612     auto Mips16 = makeMultilib("/mips16")
1613       .flag("+mips16");
1614
1615     auto UCLibc = makeMultilib("/uclibc")
1616       .flag("+muclibc");
1617
1618     auto MAbi64 = makeMultilib("/64")
1619       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1620
1621     auto BigEndian = makeMultilib("")
1622       .flag("+EB").flag("-EL");
1623
1624     auto LittleEndian = makeMultilib("/el")
1625       .flag("+EL").flag("-EB");
1626
1627     auto SoftFloat = makeMultilib("/sof")
1628       .flag("+msoft-float");
1629
1630     auto Nan2008 = makeMultilib("/nan2008")
1631       .flag("+mnan=2008");
1632
1633     FSFMipsMultilibs = MultilibSet()
1634       .Either(MArchMips32, MArchMicroMips, 
1635               MArchMips64r2, MArchMips64, MArchDefault)
1636       .Maybe(UCLibc)
1637       .Maybe(Mips16)
1638       .FilterOut("/mips64/mips16")
1639       .FilterOut("/mips64r2/mips16")
1640       .FilterOut("/micromips/mips16")
1641       .Maybe(MAbi64)
1642       .FilterOut("/micromips/64")
1643       .FilterOut("/mips32/64")
1644       .FilterOut("^/64")
1645       .FilterOut("/mips16/64")
1646       .Either(BigEndian, LittleEndian)
1647       .Maybe(SoftFloat)
1648       .Maybe(Nan2008)
1649       .FilterOut(".*sof/nan2008")
1650       .FilterOut(NonExistent)
1651       .setIncludeDirsCallback([](
1652           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1653         std::vector<std::string> Dirs;
1654         Dirs.push_back((InstallDir + "/include").str());
1655         std::string SysRootInc = InstallDir.str() + "/../../../../sysroot";
1656         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1657           Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1658         else
1659           Dirs.push_back(SysRootInc + "/usr/include");
1660         return Dirs;
1661       });
1662   }
1663
1664   // Check for Code Sourcery toolchain multilibs
1665   MultilibSet CSMipsMultilibs;
1666   {
1667     auto MArchMips16 = makeMultilib("/mips16")
1668       .flag("+m32").flag("+mips16");
1669
1670     auto MArchMicroMips = makeMultilib("/micromips")
1671       .flag("+m32").flag("+mmicromips");
1672
1673     auto MArchDefault = makeMultilib("")
1674       .flag("-mips16").flag("-mmicromips");
1675
1676     auto UCLibc = makeMultilib("/uclibc")
1677       .flag("+muclibc");
1678
1679     auto SoftFloat = makeMultilib("/soft-float")
1680       .flag("+msoft-float");
1681
1682     auto Nan2008 = makeMultilib("/nan2008")
1683       .flag("+mnan=2008");
1684
1685     auto DefaultFloat = makeMultilib("")
1686       .flag("-msoft-float").flag("-mnan=2008");
1687
1688     auto BigEndian = makeMultilib("")
1689       .flag("+EB").flag("-EL");
1690
1691     auto LittleEndian = makeMultilib("/el")
1692       .flag("+EL").flag("-EB");
1693
1694     // Note that this one's osSuffix is ""
1695     auto MAbi64 = makeMultilib("")
1696       .gccSuffix("/64")
1697       .includeSuffix("/64")
1698       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1699
1700     CSMipsMultilibs = MultilibSet()
1701       .Either(MArchMips16, MArchMicroMips, MArchDefault)
1702       .Maybe(UCLibc)
1703       .Either(SoftFloat, Nan2008, DefaultFloat)
1704       .FilterOut("/micromips/nan2008")
1705       .FilterOut("/mips16/nan2008")
1706       .Either(BigEndian, LittleEndian)
1707       .Maybe(MAbi64)
1708       .FilterOut("/mips16.*/64")
1709       .FilterOut("/micromips.*/64")
1710       .FilterOut(NonExistent)
1711       .setIncludeDirsCallback([](
1712           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1713         std::vector<std::string> Dirs;
1714         Dirs.push_back((InstallDir + "/include").str());
1715         std::string SysRootInc =
1716             InstallDir.str() + "/../../../../" + TripleStr.str();
1717         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1718           Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1719         else
1720           Dirs.push_back(SysRootInc + "/libc/usr/include");
1721         return Dirs;
1722       });
1723   }
1724
1725   MultilibSet AndroidMipsMultilibs = MultilibSet()
1726     .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1727     .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1728     .FilterOut(NonExistent);
1729
1730   MultilibSet DebianMipsMultilibs;
1731   {
1732     Multilib MAbiN32 = Multilib()
1733       .gccSuffix("/n32")
1734       .includeSuffix("/n32")
1735       .flag("+mabi=n32");
1736
1737     Multilib M64 = Multilib()
1738       .gccSuffix("/64")
1739       .includeSuffix("/64")
1740       .flag("+m64").flag("-m32").flag("-mabi=n32");
1741
1742     Multilib M32 = Multilib()
1743       .flag("-m64").flag("+m32").flag("-mabi=n32");
1744
1745     DebianMipsMultilibs = MultilibSet()
1746       .Either(M32, M64, MAbiN32)
1747       .FilterOut(NonExistent);
1748   }
1749
1750   MultilibSet ImgMultilibs;
1751   {
1752     auto Mips64r6 = makeMultilib("/mips64r6")
1753       .flag("+m64").flag("-m32");
1754
1755     auto LittleEndian = makeMultilib("/el")
1756       .flag("+EL").flag("-EB");
1757
1758     auto MAbi64 = makeMultilib("/64")
1759       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1760
1761     ImgMultilibs = MultilibSet()
1762       .Maybe(Mips64r6)
1763       .Maybe(MAbi64)
1764       .Maybe(LittleEndian)
1765       .FilterOut(NonExistent)
1766       .setIncludeDirsCallback([](
1767           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1768         std::vector<std::string> Dirs;
1769         Dirs.push_back((InstallDir + "/include").str());
1770         Dirs.push_back((InstallDir + "/../../../../sysroot/usr/include").str());
1771         return Dirs;
1772       });
1773   }
1774
1775   StringRef CPUName;
1776   StringRef ABIName;
1777   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1778
1779   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1780
1781   Multilib::flags_list Flags;
1782   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
1783   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
1784   addMultilibFlag(isMips16(Args), "mips16", Flags);
1785   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1786   addMultilibFlag(CPUName == "mips32r2", "march=mips32r2", Flags);
1787   addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1788   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1789   addMultilibFlag(CPUName == "mips64r2" || CPUName == "octeon",
1790                   "march=mips64r2", Flags);
1791   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1792   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1793   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1794                   Flags);
1795   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1796   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1797   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1798   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1799   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1800   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1801
1802   if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
1803     // Select Android toolchain. It's the only choice in that case.
1804     if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1805       Result.Multilibs = AndroidMipsMultilibs;
1806       return true;
1807     }
1808     return false;
1809   }
1810
1811   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1812       TargetTriple.getOS() == llvm::Triple::Linux &&
1813       TargetTriple.getEnvironment() == llvm::Triple::GNU) {
1814     // Select mips-img-linux-gnu toolchain.
1815     if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
1816       Result.Multilibs = ImgMultilibs;
1817       return true;
1818     }
1819     return false;
1820   }
1821
1822   // Sort candidates. Toolchain that best meets the directories goes first.
1823   // Then select the first toolchains matches command line flags.
1824   MultilibSet *candidates[] = { &DebianMipsMultilibs, &FSFMipsMultilibs,
1825                                 &CSMipsMultilibs };
1826   std::sort(
1827       std::begin(candidates), std::end(candidates),
1828       [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
1829   for (const auto &candidate : candidates) {
1830     if (candidate->select(Flags, Result.SelectedMultilib)) {
1831       if (candidate == &DebianMipsMultilibs)
1832         Result.BiarchSibling = Multilib();
1833       Result.Multilibs = *candidate;
1834       return true;
1835     }
1836   }
1837
1838   {
1839     // Fallback to the regular toolchain-tree structure.
1840     Multilib Default;
1841     Result.Multilibs.push_back(Default);
1842     Result.Multilibs.FilterOut(NonExistent);
1843
1844     if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1845       Result.BiarchSibling = Multilib();
1846       return true;
1847     }
1848   }
1849
1850   return false;
1851 }
1852
1853 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
1854                                 StringRef Path, const ArgList &Args,
1855                                 bool NeedsBiarchSuffix,
1856                                 DetectedMultilibs &Result) {
1857
1858   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1859   // in what would normally be GCCInstallPath and put the 64-bit
1860   // libs in a subdirectory named 64. The simple logic we follow is that
1861   // *if* there is a subdirectory of the right name with crtbegin.o in it,
1862   // we use that. If not, and if not a biarch triple alias, we look for
1863   // crtbegin.o without the subdirectory.
1864
1865   Multilib Default;
1866   Multilib Alt64 = Multilib()
1867     .gccSuffix("/64")
1868     .includeSuffix("/64")
1869     .flag("-m32").flag("+m64").flag("-mx32");
1870   Multilib Alt32 = Multilib()
1871     .gccSuffix("/32")
1872     .includeSuffix("/32")
1873     .flag("+m32").flag("-m64").flag("-mx32");
1874   Multilib Altx32 = Multilib()
1875     .gccSuffix("/x32")
1876     .includeSuffix("/x32")
1877     .flag("-m32").flag("-m64").flag("+mx32");
1878
1879   FilterNonExistent NonExistent(Path);
1880
1881   // Determine default multilib from: 32, 64, x32
1882   // Also handle cases such as 64 on 32, 32 on 64, etc.
1883   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1884   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1885   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1886     Want = WANT64;
1887   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1888     Want = WANT64;
1889   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1890     Want = WANT32;
1891   else {
1892     if (TargetTriple.isArch32Bit())
1893       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1894     else if (IsX32)
1895       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1896     else
1897       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1898   }
1899
1900   if (Want == WANT32)
1901     Default.flag("+m32").flag("-m64").flag("-mx32");
1902   else if (Want == WANT64)
1903     Default.flag("-m32").flag("+m64").flag("-mx32");
1904   else if (Want == WANTX32)
1905     Default.flag("-m32").flag("-m64").flag("+mx32");
1906   else
1907     return false;
1908
1909   Result.Multilibs.push_back(Default);
1910   Result.Multilibs.push_back(Alt64);
1911   Result.Multilibs.push_back(Alt32);
1912   Result.Multilibs.push_back(Altx32);
1913
1914   Result.Multilibs.FilterOut(NonExistent);
1915
1916   Multilib::flags_list Flags;
1917   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1918   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1919   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1920
1921   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1922     return false;
1923
1924   if (Result.SelectedMultilib == Alt64 ||
1925       Result.SelectedMultilib == Alt32 ||
1926       Result.SelectedMultilib == Altx32)
1927     Result.BiarchSibling = Default;
1928
1929   return true;
1930 }
1931
1932 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1933     const llvm::Triple &TargetTriple, const ArgList &Args,
1934     const std::string &LibDir, StringRef CandidateTriple,
1935     bool NeedsBiarchSuffix) {
1936   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1937   // There are various different suffixes involving the triple we
1938   // check for. We also record what is necessary to walk from each back
1939   // up to the lib directory.
1940   const std::string LibSuffixes[] = {
1941     "/gcc/" + CandidateTriple.str(),
1942     // Debian puts cross-compilers in gcc-cross
1943     "/gcc-cross/" + CandidateTriple.str(),
1944     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1945
1946     // The Freescale PPC SDK has the gcc libraries in
1947     // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1948     "/" + CandidateTriple.str(),
1949
1950     // Ubuntu has a strange mis-matched pair of triples that this happens to
1951     // match.
1952     // FIXME: It may be worthwhile to generalize this and look for a second
1953     // triple.
1954     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1955   };
1956   const std::string InstallSuffixes[] = {
1957     "/../../..",    // gcc/
1958     "/../../..",    // gcc-cross/
1959     "/../../../..", // <triple>/gcc/
1960     "/../..",       // <triple>/
1961     "/../../../.."  // i386-linux-gnu/gcc/<triple>/
1962   };
1963   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1964   const unsigned NumLibSuffixes =
1965       (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1966   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1967     StringRef LibSuffix = LibSuffixes[i];
1968     std::error_code EC;
1969     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1970          !EC && LI != LE; LI = LI.increment(EC)) {
1971       StringRef VersionText = llvm::sys::path::filename(LI->path());
1972       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1973       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1974         if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1975           continue; // Saw this path before; no need to look at it again.
1976       if (CandidateVersion.isOlderThan(4, 1, 1))
1977         continue;
1978       if (CandidateVersion <= Version)
1979         continue;
1980
1981       DetectedMultilibs Detected;
1982
1983       // Debian mips multilibs behave more like the rest of the biarch ones,
1984       // so handle them there
1985       if (isMipsArch(TargetArch)) {
1986         if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
1987           continue;
1988       } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
1989                                       NeedsBiarchSuffix, Detected)) {
1990         continue;
1991       }
1992
1993       Multilibs = Detected.Multilibs;
1994       SelectedMultilib = Detected.SelectedMultilib;
1995       BiarchSibling = Detected.BiarchSibling;
1996       Version = CandidateVersion;
1997       GCCTriple.setTriple(CandidateTriple);
1998       // FIXME: We hack together the directory name here instead of
1999       // using LI to ensure stable path separators across Windows and
2000       // Linux.
2001       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
2002       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
2003       IsValid = true;
2004     }
2005   }
2006 }
2007
2008 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
2009                          const ArgList &Args)
2010   : ToolChain(D, Triple, Args), GCCInstallation() {
2011   getProgramPaths().push_back(getDriver().getInstalledDir());
2012   if (getDriver().getInstalledDir() != getDriver().Dir)
2013     getProgramPaths().push_back(getDriver().Dir);
2014 }
2015
2016 Generic_GCC::~Generic_GCC() {
2017 }
2018
2019 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2020   switch (AC) {
2021   case Action::PreprocessJobClass:
2022     if (!Preprocess)
2023       Preprocess.reset(new tools::gcc::Preprocess(*this));
2024     return Preprocess.get();
2025   case Action::CompileJobClass:
2026     if (!Compile)
2027       Compile.reset(new tools::gcc::Compile(*this));
2028     return Compile.get();
2029   default:
2030     return ToolChain::getTool(AC);
2031   }
2032 }
2033
2034 Tool *Generic_GCC::buildAssembler() const {
2035   return new tools::gnutools::Assemble(*this);
2036 }
2037
2038 Tool *Generic_GCC::buildLinker() const {
2039   return new tools::gcc::Link(*this);
2040 }
2041
2042 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2043   // Print the information about how we detected the GCC installation.
2044   GCCInstallation.print(OS);
2045 }
2046
2047 bool Generic_GCC::IsUnwindTablesDefault() const {
2048   return getArch() == llvm::Triple::x86_64;
2049 }
2050
2051 bool Generic_GCC::isPICDefault() const {
2052   return false;
2053 }
2054
2055 bool Generic_GCC::isPIEDefault() const {
2056   return false;
2057 }
2058
2059 bool Generic_GCC::isPICDefaultForced() const {
2060   return false;
2061 }
2062
2063 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2064   return getTriple().getArch() == llvm::Triple::x86 ||
2065          getTriple().getArch() == llvm::Triple::x86_64 ||
2066          getTriple().getArch() == llvm::Triple::aarch64 ||
2067          getTriple().getArch() == llvm::Triple::aarch64_be ||
2068          getTriple().getArch() == llvm::Triple::arm ||
2069          getTriple().getArch() == llvm::Triple::armeb ||
2070          getTriple().getArch() == llvm::Triple::thumb ||
2071          getTriple().getArch() == llvm::Triple::thumbeb ||
2072          getTriple().getArch() == llvm::Triple::ppc ||
2073          getTriple().getArch() == llvm::Triple::ppc64 ||
2074          getTriple().getArch() == llvm::Triple::ppc64le ||
2075          getTriple().getArch() == llvm::Triple::sparc ||
2076          getTriple().getArch() == llvm::Triple::sparcv9 ||
2077          getTriple().getArch() == llvm::Triple::systemz;
2078 }
2079
2080 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2081                                         ArgStringList &CC1Args) const {
2082   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2083   bool UseInitArrayDefault =
2084       getTriple().getArch() == llvm::Triple::aarch64 ||
2085       getTriple().getArch() == llvm::Triple::aarch64_be ||
2086       (getTriple().getOS() == llvm::Triple::Linux &&
2087        (!V.isOlderThan(4, 7, 0) ||
2088         getTriple().getEnvironment() == llvm::Triple::Android));
2089
2090   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2091                          options::OPT_fno_use_init_array,
2092                          UseInitArrayDefault))
2093     CC1Args.push_back("-fuse-init-array");
2094 }
2095
2096 /// Hexagon Toolchain
2097
2098 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
2099                                   const ArgList &Args) {
2100
2101   // Locate the rest of the toolchain ...
2102   std::string GccToolchain = getGCCToolchainDir(Args);
2103
2104   if (!GccToolchain.empty())
2105     return GccToolchain;
2106
2107   std::string InstallRelDir = InstalledDir + "/../../gnu";
2108   if (llvm::sys::fs::exists(InstallRelDir))
2109     return InstallRelDir;
2110
2111   std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
2112   if (llvm::sys::fs::exists(PrefixRelDir))
2113     return PrefixRelDir;
2114
2115   return InstallRelDir;
2116 }
2117
2118 static void GetHexagonLibraryPaths(
2119   const ArgList &Args,
2120   const std::string &Ver,
2121   const std::string &MarchString,
2122   const std::string &InstalledDir,
2123   ToolChain::path_list *LibPaths)
2124 {
2125   bool buildingLib = Args.hasArg(options::OPT_shared);
2126
2127   //----------------------------------------------------------------------------
2128   // -L Args
2129   //----------------------------------------------------------------------------
2130   for (arg_iterator
2131          it = Args.filtered_begin(options::OPT_L),
2132          ie = Args.filtered_end();
2133        it != ie;
2134        ++it) {
2135     for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
2136       LibPaths->push_back((*it)->getValue(i));
2137   }
2138
2139   //----------------------------------------------------------------------------
2140   // Other standard paths
2141   //----------------------------------------------------------------------------
2142   const std::string MarchSuffix = "/" + MarchString;
2143   const std::string G0Suffix = "/G0";
2144   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
2145   const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
2146
2147   // lib/gcc/hexagon/...
2148   std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
2149   if (buildingLib) {
2150     LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
2151     LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
2152   }
2153   LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
2154   LibPaths->push_back(LibGCCHexagonDir + Ver);
2155
2156   // lib/gcc/...
2157   LibPaths->push_back(RootDir + "lib/gcc");
2158
2159   // hexagon/lib/...
2160   std::string HexagonLibDir = RootDir + "hexagon/lib";
2161   if (buildingLib) {
2162     LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
2163     LibPaths->push_back(HexagonLibDir + G0Suffix);
2164   }
2165   LibPaths->push_back(HexagonLibDir + MarchSuffix);
2166   LibPaths->push_back(HexagonLibDir);
2167 }
2168
2169 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
2170                        const ArgList &Args)
2171   : Linux(D, Triple, Args) {
2172   const std::string InstalledDir(getDriver().getInstalledDir());
2173   const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
2174
2175   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2176   // program paths
2177   const std::string BinDir(GnuDir + "/bin");
2178   if (llvm::sys::fs::exists(BinDir))
2179     getProgramPaths().push_back(BinDir);
2180
2181   // Determine version of GCC libraries and headers to use.
2182   const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
2183   std::error_code ec;
2184   GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
2185   for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
2186        !ec && di != de; di = di.increment(ec)) {
2187     GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
2188     if (MaxVersion < cv)
2189       MaxVersion = cv;
2190   }
2191   GCCLibAndIncVersion = MaxVersion;
2192
2193   ToolChain::path_list *LibPaths= &getFilePaths();
2194
2195   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2196   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2197   // support 'linux' we'll need to fix this up
2198   LibPaths->clear();
2199
2200   GetHexagonLibraryPaths(
2201     Args,
2202     GetGCCLibAndIncVersion(),
2203     GetTargetCPU(Args),
2204     InstalledDir,
2205     LibPaths);
2206 }
2207
2208 Hexagon_TC::~Hexagon_TC() {
2209 }
2210
2211 Tool *Hexagon_TC::buildAssembler() const {
2212   return new tools::hexagon::Assemble(*this);
2213 }
2214
2215 Tool *Hexagon_TC::buildLinker() const {
2216   return new tools::hexagon::Link(*this);
2217 }
2218
2219 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2220                                            ArgStringList &CC1Args) const {
2221   const Driver &D = getDriver();
2222
2223   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2224       DriverArgs.hasArg(options::OPT_nostdlibinc))
2225     return;
2226
2227   std::string Ver(GetGCCLibAndIncVersion());
2228   std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
2229   std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
2230   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
2231   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
2232   addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
2233 }
2234
2235 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2236                                               ArgStringList &CC1Args) const {
2237
2238   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2239       DriverArgs.hasArg(options::OPT_nostdincxx))
2240     return;
2241
2242   const Driver &D = getDriver();
2243   std::string Ver(GetGCCLibAndIncVersion());
2244   SmallString<128> IncludeDir(
2245       Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
2246
2247   llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
2248   llvm::sys::path::append(IncludeDir, Ver);
2249   addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
2250 }
2251
2252 ToolChain::CXXStdlibType
2253 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
2254   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2255   if (!A)
2256     return ToolChain::CST_Libstdcxx;
2257
2258   StringRef Value = A->getValue();
2259   if (Value != "libstdc++") {
2260     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2261       << A->getAsString(Args);
2262   }
2263
2264   return ToolChain::CST_Libstdcxx;
2265 }
2266
2267 static int getHexagonVersion(const ArgList &Args) {
2268   Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
2269   // Select the default CPU (v4) if none was given.
2270   if (!A)
2271     return 4;
2272
2273   // FIXME: produce errors if we cannot parse the version.
2274   StringRef WhichHexagon = A->getValue();
2275   if (WhichHexagon.startswith("hexagonv")) {
2276     int Val;
2277     if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
2278       return Val;
2279   }
2280   if (WhichHexagon.startswith("v")) {
2281     int Val;
2282     if (!WhichHexagon.substr(1).getAsInteger(10, Val))
2283       return Val;
2284   }
2285
2286   // FIXME: should probably be an error.
2287   return 4;
2288 }
2289
2290 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
2291 {
2292   int V = getHexagonVersion(Args);
2293   // FIXME: We don't support versions < 4. We should error on them.
2294   switch (V) {
2295   default:
2296     llvm_unreachable("Unexpected version");
2297   case 5:
2298     return "v5";
2299   case 4:
2300     return "v4";
2301   case 3:
2302     return "v3";
2303   case 2:
2304     return "v2";
2305   case 1:
2306     return "v1";
2307   }
2308 }
2309 // End Hexagon
2310
2311 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2312 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2313 /// Currently does not support anything else but compilation.
2314
2315 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
2316                            const ArgList &Args)
2317   : ToolChain(D, Triple, Args) {
2318   // Path mangling to find libexec
2319   std::string Path(getDriver().Dir);
2320
2321   Path += "/../libexec";
2322   getProgramPaths().push_back(Path);
2323 }
2324
2325 TCEToolChain::~TCEToolChain() {
2326 }
2327
2328 bool TCEToolChain::IsMathErrnoDefault() const {
2329   return true;
2330 }
2331
2332 bool TCEToolChain::isPICDefault() const {
2333   return false;
2334 }
2335
2336 bool TCEToolChain::isPIEDefault() const {
2337   return false;
2338 }
2339
2340 bool TCEToolChain::isPICDefaultForced() const {
2341   return false;
2342 }
2343
2344 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2345
2346 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2347   : Generic_ELF(D, Triple, Args) {
2348   getFilePaths().push_back(getDriver().Dir + "/../lib");
2349   getFilePaths().push_back("/usr/lib");
2350 }
2351
2352 Tool *OpenBSD::buildAssembler() const {
2353   return new tools::openbsd::Assemble(*this);
2354 }
2355
2356 Tool *OpenBSD::buildLinker() const {
2357   return new tools::openbsd::Link(*this);
2358 }
2359
2360 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2361
2362 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2363   : Generic_ELF(D, Triple, Args) {
2364   getFilePaths().push_back(getDriver().Dir + "/../lib");
2365   getFilePaths().push_back("/usr/lib");
2366 }
2367
2368 Tool *Bitrig::buildAssembler() const {
2369   return new tools::bitrig::Assemble(*this);
2370 }
2371
2372 Tool *Bitrig::buildLinker() const {
2373   return new tools::bitrig::Link(*this);
2374 }
2375
2376 ToolChain::CXXStdlibType
2377 Bitrig::GetCXXStdlibType(const ArgList &Args) const {
2378   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2379     StringRef Value = A->getValue();
2380     if (Value == "libstdc++")
2381       return ToolChain::CST_Libstdcxx;
2382     if (Value == "libc++")
2383       return ToolChain::CST_Libcxx;
2384
2385     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2386       << A->getAsString(Args);
2387   }
2388   return ToolChain::CST_Libcxx;
2389 }
2390
2391 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2392                                           ArgStringList &CC1Args) const {
2393   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2394       DriverArgs.hasArg(options::OPT_nostdincxx))
2395     return;
2396
2397   switch (GetCXXStdlibType(DriverArgs)) {
2398   case ToolChain::CST_Libcxx:
2399     addSystemInclude(DriverArgs, CC1Args,
2400                      getDriver().SysRoot + "/usr/include/c++/v1");
2401     break;
2402   case ToolChain::CST_Libstdcxx:
2403     addSystemInclude(DriverArgs, CC1Args,
2404                      getDriver().SysRoot + "/usr/include/c++/stdc++");
2405     addSystemInclude(DriverArgs, CC1Args,
2406                      getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
2407
2408     StringRef Triple = getTriple().str();
2409     if (Triple.startswith("amd64"))
2410       addSystemInclude(DriverArgs, CC1Args,
2411                        getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
2412                        Triple.substr(5));
2413     else
2414       addSystemInclude(DriverArgs, CC1Args,
2415                        getDriver().SysRoot + "/usr/include/c++/stdc++/" +
2416                        Triple);
2417     break;
2418   }
2419 }
2420
2421 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
2422                                  ArgStringList &CmdArgs) const {
2423   switch (GetCXXStdlibType(Args)) {
2424   case ToolChain::CST_Libcxx:
2425     CmdArgs.push_back("-lc++");
2426     CmdArgs.push_back("-lc++abi");
2427     CmdArgs.push_back("-lpthread");
2428     break;
2429   case ToolChain::CST_Libstdcxx:
2430     CmdArgs.push_back("-lstdc++");
2431     break;
2432   }
2433 }
2434
2435 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
2436
2437 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2438   : Generic_ELF(D, Triple, Args) {
2439
2440   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
2441   // back to '/usr/lib' if it doesn't exist.
2442   if ((Triple.getArch() == llvm::Triple::x86 ||
2443        Triple.getArch() == llvm::Triple::ppc) &&
2444       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
2445     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2446   else
2447     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2448 }
2449
2450 ToolChain::CXXStdlibType
2451 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2452   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2453     StringRef Value = A->getValue();
2454     if (Value == "libstdc++")
2455       return ToolChain::CST_Libstdcxx;
2456     if (Value == "libc++")
2457       return ToolChain::CST_Libcxx;
2458
2459     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2460       << A->getAsString(Args);
2461   }
2462   if (getTriple().getOSMajorVersion() >= 10) 
2463     return ToolChain::CST_Libcxx;
2464   return ToolChain::CST_Libstdcxx;
2465 }
2466
2467 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2468                                            ArgStringList &CC1Args) const {
2469   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2470       DriverArgs.hasArg(options::OPT_nostdincxx))
2471     return;
2472
2473   switch (GetCXXStdlibType(DriverArgs)) {
2474   case ToolChain::CST_Libcxx:
2475     addSystemInclude(DriverArgs, CC1Args,
2476                      getDriver().SysRoot + "/usr/include/c++/v1");
2477     break;
2478   case ToolChain::CST_Libstdcxx:
2479     addSystemInclude(DriverArgs, CC1Args,
2480                      getDriver().SysRoot + "/usr/include/c++/4.2");
2481     addSystemInclude(DriverArgs, CC1Args,
2482                      getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2483     break;
2484   }
2485 }
2486
2487 Tool *FreeBSD::buildAssembler() const {
2488   return new tools::freebsd::Assemble(*this);
2489 }
2490
2491 Tool *FreeBSD::buildLinker() const {
2492   return new tools::freebsd::Link(*this);
2493 }
2494
2495 bool FreeBSD::UseSjLjExceptions() const {
2496   // FreeBSD uses SjLj exceptions on ARM oabi.
2497   switch (getTriple().getEnvironment()) {
2498   case llvm::Triple::GNUEABIHF:
2499   case llvm::Triple::GNUEABI:
2500   case llvm::Triple::EABI:
2501     return false;
2502
2503   default:
2504     return (getTriple().getArch() == llvm::Triple::arm ||
2505             getTriple().getArch() == llvm::Triple::thumb);
2506   }
2507 }
2508
2509 bool FreeBSD::HasNativeLLVMSupport() const {
2510   return true;
2511 }
2512
2513 bool FreeBSD::isPIEDefault() const {
2514   return getSanitizerArgs().requiresPIE();
2515 }
2516
2517 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2518
2519 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2520   : Generic_ELF(D, Triple, Args) {
2521
2522   if (getDriver().UseStdLib) {
2523     // When targeting a 32-bit platform, try the special directory used on
2524     // 64-bit hosts, and only fall back to the main library directory if that
2525     // doesn't work.
2526     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2527     // what all logic is needed to emulate the '=' prefix here.
2528     switch (Triple.getArch()) {
2529     case llvm::Triple::x86:
2530       getFilePaths().push_back("=/usr/lib/i386");
2531       break;
2532     case llvm::Triple::arm:
2533     case llvm::Triple::armeb:
2534     case llvm::Triple::thumb:
2535     case llvm::Triple::thumbeb:
2536       switch (Triple.getEnvironment()) {
2537       case llvm::Triple::EABI:
2538       case llvm::Triple::GNUEABI:
2539         getFilePaths().push_back("=/usr/lib/eabi");
2540         break;
2541       case llvm::Triple::EABIHF:
2542       case llvm::Triple::GNUEABIHF:
2543         getFilePaths().push_back("=/usr/lib/eabihf");
2544         break;
2545       default:
2546         getFilePaths().push_back("=/usr/lib/oabi");
2547         break;
2548       }
2549       break;
2550     case llvm::Triple::mips64:
2551     case llvm::Triple::mips64el:
2552       if (tools::mips::hasMipsAbiArg(Args, "o32"))
2553         getFilePaths().push_back("=/usr/lib/o32");
2554       else if (tools::mips::hasMipsAbiArg(Args, "64"))
2555         getFilePaths().push_back("=/usr/lib/64");
2556       break;
2557     case llvm::Triple::ppc:
2558       getFilePaths().push_back("=/usr/lib/powerpc");
2559       break;
2560     case llvm::Triple::sparc:
2561       getFilePaths().push_back("=/usr/lib/sparc");
2562       break;
2563     default:
2564       break;
2565     }
2566
2567     getFilePaths().push_back("=/usr/lib");
2568   }
2569 }
2570
2571 Tool *NetBSD::buildAssembler() const {
2572   return new tools::netbsd::Assemble(*this);
2573 }
2574
2575 Tool *NetBSD::buildLinker() const {
2576   return new tools::netbsd::Link(*this);
2577 }
2578
2579 ToolChain::CXXStdlibType
2580 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2581   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2582     StringRef Value = A->getValue();
2583     if (Value == "libstdc++")
2584       return ToolChain::CST_Libstdcxx;
2585     if (Value == "libc++")
2586       return ToolChain::CST_Libcxx;
2587
2588     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2589       << A->getAsString(Args);
2590   }
2591
2592   unsigned Major, Minor, Micro;
2593   getTriple().getOSVersion(Major, Minor, Micro);
2594   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
2595     switch (getArch()) {
2596     case llvm::Triple::aarch64:
2597     case llvm::Triple::arm:
2598     case llvm::Triple::armeb:
2599     case llvm::Triple::thumb:
2600     case llvm::Triple::thumbeb:
2601     case llvm::Triple::ppc:
2602     case llvm::Triple::ppc64:
2603     case llvm::Triple::ppc64le:
2604     case llvm::Triple::x86:
2605     case llvm::Triple::x86_64:
2606       return ToolChain::CST_Libcxx;
2607     default:
2608       break;
2609     }
2610   }
2611   return ToolChain::CST_Libstdcxx;
2612 }
2613
2614 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2615                                           ArgStringList &CC1Args) const {
2616   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2617       DriverArgs.hasArg(options::OPT_nostdincxx))
2618     return;
2619
2620   switch (GetCXXStdlibType(DriverArgs)) {
2621   case ToolChain::CST_Libcxx:
2622     addSystemInclude(DriverArgs, CC1Args,
2623                      getDriver().SysRoot + "/usr/include/c++/");
2624     break;
2625   case ToolChain::CST_Libstdcxx:
2626     addSystemInclude(DriverArgs, CC1Args,
2627                      getDriver().SysRoot + "/usr/include/g++");
2628     addSystemInclude(DriverArgs, CC1Args,
2629                      getDriver().SysRoot + "/usr/include/g++/backward");
2630     break;
2631   }
2632 }
2633
2634 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2635
2636 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2637   : Generic_ELF(D, Triple, Args) {
2638   getFilePaths().push_back(getDriver().Dir + "/../lib");
2639   getFilePaths().push_back("/usr/lib");
2640 }
2641
2642 Tool *Minix::buildAssembler() const {
2643   return new tools::minix::Assemble(*this);
2644 }
2645
2646 Tool *Minix::buildLinker() const {
2647   return new tools::minix::Link(*this);
2648 }
2649
2650 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2651
2652 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2653                  const ArgList &Args)
2654   : Generic_GCC(D, Triple, Args) {
2655
2656   getProgramPaths().push_back(getDriver().getInstalledDir());
2657   if (getDriver().getInstalledDir() != getDriver().Dir)
2658     getProgramPaths().push_back(getDriver().Dir);
2659
2660   getFilePaths().push_back(getDriver().Dir + "/../lib");
2661   getFilePaths().push_back("/usr/lib");
2662 }
2663
2664 Tool *Solaris::buildAssembler() const {
2665   return new tools::solaris::Assemble(*this);
2666 }
2667
2668 Tool *Solaris::buildLinker() const {
2669   return new tools::solaris::Link(*this);
2670 }
2671
2672 /// Distribution (very bare-bones at the moment).
2673
2674 enum Distro {
2675   ArchLinux,
2676   DebianLenny,
2677   DebianSqueeze,
2678   DebianWheezy,
2679   DebianJessie,
2680   Exherbo,
2681   RHEL4,
2682   RHEL5,
2683   RHEL6,
2684   Fedora,
2685   OpenSUSE,
2686   UbuntuHardy,
2687   UbuntuIntrepid,
2688   UbuntuJaunty,
2689   UbuntuKarmic,
2690   UbuntuLucid,
2691   UbuntuMaverick,
2692   UbuntuNatty,
2693   UbuntuOneiric,
2694   UbuntuPrecise,
2695   UbuntuQuantal,
2696   UbuntuRaring,
2697   UbuntuSaucy,
2698   UbuntuTrusty,
2699   UnknownDistro
2700 };
2701
2702 static bool IsRedhat(enum Distro Distro) {
2703   return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
2704 }
2705
2706 static bool IsOpenSUSE(enum Distro Distro) {
2707   return Distro == OpenSUSE;
2708 }
2709
2710 static bool IsDebian(enum Distro Distro) {
2711   return Distro >= DebianLenny && Distro <= DebianJessie;
2712 }
2713
2714 static bool IsUbuntu(enum Distro Distro) {
2715   return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
2716 }
2717
2718 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2719   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2720       llvm::MemoryBuffer::getFile("/etc/lsb-release");
2721   if (File) {
2722     StringRef Data = File.get()->getBuffer();
2723     SmallVector<StringRef, 16> Lines;
2724     Data.split(Lines, "\n");
2725     Distro Version = UnknownDistro;
2726     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2727       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2728         Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2729           .Case("hardy", UbuntuHardy)
2730           .Case("intrepid", UbuntuIntrepid)
2731           .Case("jaunty", UbuntuJaunty)
2732           .Case("karmic", UbuntuKarmic)
2733           .Case("lucid", UbuntuLucid)
2734           .Case("maverick", UbuntuMaverick)
2735           .Case("natty", UbuntuNatty)
2736           .Case("oneiric", UbuntuOneiric)
2737           .Case("precise", UbuntuPrecise)
2738           .Case("quantal", UbuntuQuantal)
2739           .Case("raring", UbuntuRaring)
2740           .Case("saucy", UbuntuSaucy)
2741           .Case("trusty", UbuntuTrusty)
2742           .Default(UnknownDistro);
2743     return Version;
2744   }
2745
2746   File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
2747   if (File) {
2748     StringRef Data = File.get()->getBuffer();
2749     if (Data.startswith("Fedora release"))
2750       return Fedora;
2751     if (Data.startswith("Red Hat Enterprise Linux") ||
2752         Data.startswith("CentOS")) {
2753       if (Data.find("release 6") != StringRef::npos)
2754         return RHEL6;
2755       else if (Data.find("release 5") != StringRef::npos)
2756         return RHEL5;
2757       else if (Data.find("release 4") != StringRef::npos)
2758         return RHEL4;
2759     }
2760     return UnknownDistro;
2761   }
2762
2763   File = llvm::MemoryBuffer::getFile("/etc/debian_version");
2764   if (File) {
2765     StringRef Data = File.get()->getBuffer();
2766     if (Data[0] == '5')
2767       return DebianLenny;
2768     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2769       return DebianSqueeze;
2770     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
2771       return DebianWheezy;
2772     else if (Data.startswith("jessie/sid")  || Data[0] == '8')
2773       return DebianJessie;
2774     return UnknownDistro;
2775   }
2776
2777   if (llvm::sys::fs::exists("/etc/SuSE-release"))
2778     return OpenSUSE;
2779
2780   if (llvm::sys::fs::exists("/etc/exherbo-release"))
2781     return Exherbo;
2782
2783   if (llvm::sys::fs::exists("/etc/arch-release"))
2784     return ArchLinux;
2785
2786   return UnknownDistro;
2787 }
2788
2789 /// \brief Get our best guess at the multiarch triple for a target.
2790 ///
2791 /// Debian-based systems are starting to use a multiarch setup where they use
2792 /// a target-triple directory in the library and header search paths.
2793 /// Unfortunately, this triple does not align with the vanilla target triple,
2794 /// so we provide a rough mapping here.
2795 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
2796                                       StringRef SysRoot) {
2797   // For most architectures, just use whatever we have rather than trying to be
2798   // clever.
2799   switch (TargetTriple.getArch()) {
2800   default:
2801     return TargetTriple.str();
2802
2803     // We use the existence of '/lib/<triple>' as a directory to detect some
2804     // common linux triples that don't quite match the Clang triple for both
2805     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2806     // regardless of what the actual target triple is.
2807   case llvm::Triple::arm:
2808   case llvm::Triple::thumb:
2809     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2810       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2811         return "arm-linux-gnueabihf";
2812     } else {
2813       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2814         return "arm-linux-gnueabi";
2815     }
2816     return TargetTriple.str();
2817   case llvm::Triple::armeb:
2818   case llvm::Triple::thumbeb:
2819     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2820       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
2821         return "armeb-linux-gnueabihf";
2822     } else {
2823       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
2824         return "armeb-linux-gnueabi";
2825     }
2826     return TargetTriple.str();
2827   case llvm::Triple::x86:
2828     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2829       return "i386-linux-gnu";
2830     return TargetTriple.str();
2831   case llvm::Triple::x86_64:
2832     // We don't want this for x32, otherwise it will match x86_64 libs
2833     if (TargetTriple.getEnvironment() != llvm::Triple::GNUX32 &&
2834         llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2835       return "x86_64-linux-gnu";
2836     return TargetTriple.str();
2837   case llvm::Triple::aarch64:
2838     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2839       return "aarch64-linux-gnu";
2840     return TargetTriple.str();
2841   case llvm::Triple::aarch64_be:
2842     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
2843       return "aarch64_be-linux-gnu";
2844     return TargetTriple.str();
2845   case llvm::Triple::mips:
2846     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2847       return "mips-linux-gnu";
2848     return TargetTriple.str();
2849   case llvm::Triple::mipsel:
2850     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2851       return "mipsel-linux-gnu";
2852     return TargetTriple.str();
2853   case llvm::Triple::mips64:
2854     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
2855       return "mips64-linux-gnu";
2856     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
2857       return "mips64-linux-gnuabi64";
2858     return TargetTriple.str();
2859   case llvm::Triple::mips64el:
2860     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
2861       return "mips64el-linux-gnu";
2862     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
2863       return "mips64el-linux-gnuabi64";
2864     return TargetTriple.str();
2865   case llvm::Triple::ppc:
2866     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2867       return "powerpc-linux-gnuspe";
2868     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2869       return "powerpc-linux-gnu";
2870     return TargetTriple.str();
2871   case llvm::Triple::ppc64:
2872     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2873       return "powerpc64-linux-gnu";
2874   case llvm::Triple::ppc64le:
2875     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
2876       return "powerpc64le-linux-gnu";
2877     return TargetTriple.str();
2878   }
2879 }
2880
2881 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2882   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2883 }
2884
2885 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
2886   if (isMipsArch(Triple.getArch())) {
2887     // lib32 directory has a special meaning on MIPS targets.
2888     // It contains N32 ABI binaries. Use this folder if produce
2889     // code for N32 ABI only.
2890     if (tools::mips::hasMipsAbiArg(Args, "n32"))
2891       return "lib32";
2892     return Triple.isArch32Bit() ? "lib" : "lib64";
2893   }
2894
2895   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
2896   // using that variant while targeting other architectures causes problems
2897   // because the libraries are laid out in shared system roots that can't cope
2898   // with a 'lib32' library search path being considered. So we only enable
2899   // them when we know we may need it.
2900   //
2901   // FIXME: This is a bit of a hack. We should really unify this code for
2902   // reasoning about oslibdir spellings with the lib dir spellings in the
2903   // GCCInstallationDetector, but that is a more significant refactoring.
2904   if (Triple.getArch() == llvm::Triple::x86 ||
2905       Triple.getArch() == llvm::Triple::ppc)
2906     return "lib32";
2907
2908   if (Triple.getArch() == llvm::Triple::x86_64 &&
2909       Triple.getEnvironment() == llvm::Triple::GNUX32)
2910     return "libx32";
2911
2912   return Triple.isArch32Bit() ? "lib" : "lib64";
2913 }
2914
2915 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2916   : Generic_ELF(D, Triple, Args) {
2917   GCCInstallation.init(D, Triple, Args);
2918   Multilibs = GCCInstallation.getMultilibs();
2919   llvm::Triple::ArchType Arch = Triple.getArch();
2920   std::string SysRoot = computeSysRoot();
2921
2922   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2923   // least) put various tools in a triple-prefixed directory off of the parent
2924   // of the GCC installation. We use the GCC triple here to ensure that we end
2925   // up with tools that support the same amount of cross compiling as the
2926   // detected GCC installation. For example, if we find a GCC installation
2927   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2928   // used to target i386.
2929   // FIXME: This seems unlikely to be Linux-specific.
2930   ToolChain::path_list &PPaths = getProgramPaths();
2931   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2932                          GCCInstallation.getTriple().str() + "/bin").str());
2933
2934   Linker = GetLinkerPath();
2935
2936   Distro Distro = DetectDistro(Arch);
2937
2938   if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2939     ExtraOpts.push_back("-z");
2940     ExtraOpts.push_back("relro");
2941   }
2942
2943   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2944     ExtraOpts.push_back("-X");
2945
2946   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2947   const bool IsMips = isMipsArch(Arch);
2948
2949   if (IsMips && !SysRoot.empty())
2950     ExtraOpts.push_back("--sysroot=" + SysRoot);
2951
2952   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2953   // and the MIPS ABI require .dynsym to be sorted in different ways.
2954   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2955   // ABI requires a mapping between the GOT and the symbol table.
2956   // Android loader does not support .gnu.hash.
2957   if (!IsMips && !IsAndroid) {
2958     if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2959         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2960       ExtraOpts.push_back("--hash-style=gnu");
2961
2962     if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2963         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2964       ExtraOpts.push_back("--hash-style=both");
2965   }
2966
2967   if (IsRedhat(Distro))
2968     ExtraOpts.push_back("--no-add-needed");
2969
2970   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2971       Distro == DebianJessie || IsOpenSUSE(Distro) ||
2972       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2973       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2974     ExtraOpts.push_back("--build-id");
2975
2976   if (IsOpenSUSE(Distro))
2977     ExtraOpts.push_back("--enable-new-dtags");
2978
2979   // The selection of paths to try here is designed to match the patterns which
2980   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2981   // This was determined by running GCC in a fake filesystem, creating all
2982   // possible permutations of these directories, and seeing which ones it added
2983   // to the link paths.
2984   path_list &Paths = getFilePaths();
2985
2986   const std::string OSLibDir = getOSLibDir(Triple, Args);
2987   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2988
2989   // Add the multilib suffixed paths where they are available.
2990   if (GCCInstallation.isValid()) {
2991     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2992     const std::string &LibPath = GCCInstallation.getParentLibPath();
2993     const Multilib &Multilib = GCCInstallation.getMultilib();
2994
2995     // Sourcery CodeBench MIPS toolchain holds some libraries under
2996     // a biarch-like suffix of the GCC installation.
2997     addPathIfExists((GCCInstallation.getInstallPath() +
2998                      Multilib.gccSuffix()),
2999                     Paths);
3000
3001     // GCC cross compiling toolchains will install target libraries which ship
3002     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3003     // any part of the GCC installation in
3004     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3005     // debatable, but is the reality today. We need to search this tree even
3006     // when we have a sysroot somewhere else. It is the responsibility of
3007     // whomever is doing the cross build targeting a sysroot using a GCC
3008     // installation that is *not* within the system root to ensure two things:
3009     //
3010     //  1) Any DSOs that are linked in from this tree or from the install path
3011     //     above must be present on the system root and found via an
3012     //     appropriate rpath.
3013     //  2) There must not be libraries installed into
3014     //     <prefix>/<triple>/<libdir> unless they should be preferred over
3015     //     those within the system root.
3016     //
3017     // Note that this matches the GCC behavior. See the below comment for where
3018     // Clang diverges from GCC's behavior.
3019     addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3020                     Multilib.osSuffix(),
3021                     Paths);
3022
3023     // If the GCC installation we found is inside of the sysroot, we want to
3024     // prefer libraries installed in the parent prefix of the GCC installation.
3025     // It is important to *not* use these paths when the GCC installation is
3026     // outside of the system root as that can pick up unintended libraries.
3027     // This usually happens when there is an external cross compiler on the
3028     // host system, and a more minimal sysroot available that is the target of
3029     // the cross. Note that GCC does include some of these directories in some
3030     // configurations but this seems somewhere between questionable and simply
3031     // a bug.
3032     if (StringRef(LibPath).startswith(SysRoot)) {
3033       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
3034       addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
3035     }
3036   }
3037
3038   // Similar to the logic for GCC above, if we currently running Clang inside
3039   // of the requested system root, add its parent library paths to
3040   // those searched.
3041   // FIXME: It's not clear whether we should use the driver's installed
3042   // directory ('Dir' below) or the ResourceDir.
3043   if (StringRef(D.Dir).startswith(SysRoot)) {
3044     addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
3045     addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
3046   }
3047
3048   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
3049   addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
3050   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3051   addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3052
3053   // Try walking via the GCC triple path in case of biarch or multiarch GCC
3054   // installations with strange symlinks.
3055   if (GCCInstallation.isValid()) {
3056     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3057                     "/../../" + OSLibDir, Paths);
3058
3059     // Add the 'other' biarch variant path
3060     Multilib BiarchSibling;
3061     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3062       addPathIfExists(GCCInstallation.getInstallPath() +
3063                       BiarchSibling.gccSuffix(), Paths);
3064     }
3065
3066     // See comments above on the multilib variant for details of why this is
3067     // included even from outside the sysroot.
3068     const std::string &LibPath = GCCInstallation.getParentLibPath();
3069     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3070     const Multilib &Multilib = GCCInstallation.getMultilib();
3071     addPathIfExists(LibPath + "/../" + GCCTriple.str() +
3072                     "/lib" + Multilib.osSuffix(), Paths);
3073
3074     // See comments above on the multilib variant for details of why this is
3075     // only included from within the sysroot.
3076     if (StringRef(LibPath).startswith(SysRoot))
3077       addPathIfExists(LibPath, Paths);
3078   }
3079
3080   // Similar to the logic for GCC above, if we are currently running Clang
3081   // inside of the requested system root, add its parent library path to those
3082   // searched.
3083   // FIXME: It's not clear whether we should use the driver's installed
3084   // directory ('Dir' below) or the ResourceDir.
3085   if (StringRef(D.Dir).startswith(SysRoot))
3086     addPathIfExists(D.Dir + "/../lib", Paths);
3087
3088   addPathIfExists(SysRoot + "/lib", Paths);
3089   addPathIfExists(SysRoot + "/usr/lib", Paths);
3090 }
3091
3092 bool Linux::HasNativeLLVMSupport() const {
3093   return true;
3094 }
3095
3096 Tool *Linux::buildLinker() const {
3097   return new tools::gnutools::Link(*this);
3098 }
3099
3100 Tool *Linux::buildAssembler() const {
3101   return new tools::gnutools::Assemble(*this);
3102 }
3103
3104 std::string Linux::computeSysRoot() const {
3105   if (!getDriver().SysRoot.empty())
3106     return getDriver().SysRoot;
3107
3108   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3109     return std::string();
3110
3111   // Standalone MIPS toolchains use different names for sysroot folder
3112   // and put it into different places. Here we try to check some known
3113   // variants.
3114
3115   const StringRef InstallDir = GCCInstallation.getInstallPath();
3116   const StringRef TripleStr = GCCInstallation.getTriple().str();
3117   const Multilib &Multilib = GCCInstallation.getMultilib();
3118
3119   std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
3120                       Multilib.osSuffix()).str();
3121
3122   if (llvm::sys::fs::exists(Path))
3123     return Path;
3124
3125   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3126
3127   if (llvm::sys::fs::exists(Path))
3128     return Path;
3129
3130   return std::string();
3131 }
3132
3133 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3134                                       ArgStringList &CC1Args) const {
3135   const Driver &D = getDriver();
3136   std::string SysRoot = computeSysRoot();
3137
3138   if (DriverArgs.hasArg(options::OPT_nostdinc))
3139     return;
3140
3141   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3142     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3143
3144   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3145     SmallString<128> P(D.ResourceDir);
3146     llvm::sys::path::append(P, "include");
3147     addSystemInclude(DriverArgs, CC1Args, P.str());
3148   }
3149
3150   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3151     return;
3152
3153   // Check for configure-time C include directories.
3154   StringRef CIncludeDirs(C_INCLUDE_DIRS);
3155   if (CIncludeDirs != "") {
3156     SmallVector<StringRef, 5> dirs;
3157     CIncludeDirs.split(dirs, ":");
3158     for (StringRef dir : dirs) {
3159       StringRef Prefix =
3160           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3161       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3162     }
3163     return;
3164   }
3165
3166   // Lacking those, try to detect the correct set of system includes for the
3167   // target triple.
3168
3169   // Add include directories specific to the selected multilib set and multilib.
3170   if (GCCInstallation.isValid()) {
3171     auto Callback = Multilibs.includeDirsCallback();
3172     if (Callback) {
3173       const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3174                                          GCCInstallation.getTriple().str(),
3175                                          GCCInstallation.getMultilib());
3176       for (const auto &Path : IncludePaths)
3177         addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3178     }
3179   }
3180
3181   // Implement generic Debian multiarch support.
3182   const StringRef X86_64MultiarchIncludeDirs[] = {
3183     "/usr/include/x86_64-linux-gnu",
3184
3185     // FIXME: These are older forms of multiarch. It's not clear that they're
3186     // in use in any released version of Debian, so we should consider
3187     // removing them.
3188     "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
3189   };
3190   const StringRef X86MultiarchIncludeDirs[] = {
3191     "/usr/include/i386-linux-gnu",
3192
3193     // FIXME: These are older forms of multiarch. It's not clear that they're
3194     // in use in any released version of Debian, so we should consider
3195     // removing them.
3196     "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3197     "/usr/include/i486-linux-gnu"
3198   };
3199   const StringRef AArch64MultiarchIncludeDirs[] = {
3200     "/usr/include/aarch64-linux-gnu"
3201   };
3202   const StringRef ARMMultiarchIncludeDirs[] = {
3203     "/usr/include/arm-linux-gnueabi"
3204   };
3205   const StringRef ARMHFMultiarchIncludeDirs[] = {
3206     "/usr/include/arm-linux-gnueabihf"
3207   };
3208   const StringRef MIPSMultiarchIncludeDirs[] = {
3209     "/usr/include/mips-linux-gnu"
3210   };
3211   const StringRef MIPSELMultiarchIncludeDirs[] = {
3212     "/usr/include/mipsel-linux-gnu"
3213   };
3214   const StringRef MIPS64MultiarchIncludeDirs[] = {
3215     "/usr/include/mips64-linux-gnu",
3216     "/usr/include/mips64-linux-gnuabi64"
3217   };
3218   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3219     "/usr/include/mips64el-linux-gnu",
3220     "/usr/include/mips64el-linux-gnuabi64"
3221   };
3222   const StringRef PPCMultiarchIncludeDirs[] = {
3223     "/usr/include/powerpc-linux-gnu"
3224   };
3225   const StringRef PPC64MultiarchIncludeDirs[] = {
3226     "/usr/include/powerpc64-linux-gnu"
3227   };
3228   const StringRef PPC64LEMultiarchIncludeDirs[] = {
3229     "/usr/include/powerpc64le-linux-gnu"
3230   };
3231   ArrayRef<StringRef> MultiarchIncludeDirs;
3232   if (getTriple().getArch() == llvm::Triple::x86_64) {
3233     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3234   } else if (getTriple().getArch() == llvm::Triple::x86) {
3235     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3236   } else if (getTriple().getArch() == llvm::Triple::aarch64 ||
3237              getTriple().getArch() == llvm::Triple::aarch64_be) {
3238     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3239   } else if (getTriple().getArch() == llvm::Triple::arm) {
3240     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3241       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3242     else
3243       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3244   } else if (getTriple().getArch() == llvm::Triple::mips) {
3245     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3246   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
3247     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3248   } else if (getTriple().getArch() == llvm::Triple::mips64) {
3249     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3250   } else if (getTriple().getArch() == llvm::Triple::mips64el) {
3251     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3252   } else if (getTriple().getArch() == llvm::Triple::ppc) {
3253     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3254   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
3255     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3256   } else if (getTriple().getArch() == llvm::Triple::ppc64le) {
3257     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3258   }
3259   for (StringRef Dir : MultiarchIncludeDirs) {
3260     if (llvm::sys::fs::exists(SysRoot + Dir)) {
3261       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
3262       break;
3263     }
3264   }
3265
3266   if (getTriple().getOS() == llvm::Triple::RTEMS)
3267     return;
3268
3269   // Add an include of '/include' directly. This isn't provided by default by
3270   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
3271   // add even when Clang is acting as-if it were a system compiler.
3272   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
3273
3274   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
3275 }
3276
3277 /// \brief Helper to add the variant paths of a libstdc++ installation.
3278 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
3279                                                 StringRef GCCTriple,
3280                                                 StringRef GCCMultiarchTriple,
3281                                                 StringRef TargetMultiarchTriple,
3282                                                 Twine IncludeSuffix,
3283                                                 const ArgList &DriverArgs,
3284                                                 ArgStringList &CC1Args) {
3285   if (!llvm::sys::fs::exists(Base + Suffix))
3286     return false;
3287
3288   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
3289
3290   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
3291   // that path exists or we have neither a GCC nor target multiarch triple, use
3292   // this vanilla search path.
3293   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
3294       llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
3295     addSystemInclude(DriverArgs, CC1Args,
3296                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
3297   } else {
3298     // Otherwise try to use multiarch naming schemes which have normalized the
3299     // triples and put the triple before the suffix.
3300     //
3301     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
3302     // the target triple, so we support that here.
3303     addSystemInclude(DriverArgs, CC1Args,
3304                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
3305     addSystemInclude(DriverArgs, CC1Args,
3306                      Base + "/" + TargetMultiarchTriple + Suffix);
3307   }
3308
3309   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3310   return true;
3311 }
3312
3313 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3314                                          ArgStringList &CC1Args) const {
3315   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3316       DriverArgs.hasArg(options::OPT_nostdincxx))
3317     return;
3318
3319   // Check if libc++ has been enabled and provide its include paths if so.
3320   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
3321     const std::string LibCXXIncludePathCandidates[] = {
3322       // The primary location is within the Clang installation.
3323       // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
3324       // newer ABI versions.
3325       getDriver().Dir + "/../include/c++/v1",
3326
3327       // We also check the system as for a long time this is the only place Clang looked.
3328       // FIXME: We should really remove this. It doesn't make any sense.
3329       getDriver().SysRoot + "/usr/include/c++/v1"
3330     };
3331     for (const auto &IncludePath : LibCXXIncludePathCandidates) {
3332       if (!llvm::sys::fs::exists(IncludePath))
3333         continue;
3334       // Add the first candidate that exists.
3335       addSystemInclude(DriverArgs, CC1Args, IncludePath);
3336       break;
3337     }
3338     return;
3339   }
3340
3341   // We need a detected GCC installation on Linux to provide libstdc++'s
3342   // headers. We handled the libc++ case above.
3343   if (!GCCInstallation.isValid())
3344     return;
3345
3346   // By default, look for the C++ headers in an include directory adjacent to
3347   // the lib directory of the GCC installation. Note that this is expect to be
3348   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3349   StringRef LibDir = GCCInstallation.getParentLibPath();
3350   StringRef InstallDir = GCCInstallation.getInstallPath();
3351   StringRef TripleStr = GCCInstallation.getTriple().str();
3352   const Multilib &Multilib = GCCInstallation.getMultilib();
3353   const std::string GCCMultiarchTriple =
3354       getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
3355   const std::string TargetMultiarchTriple =
3356       getMultiarchTriple(getTriple(), getDriver().SysRoot);
3357   const GCCVersion &Version = GCCInstallation.getVersion();
3358
3359   // The primary search for libstdc++ supports multiarch variants.
3360   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3361                                "/c++/" + Version.Text, TripleStr, GCCMultiarchTriple,
3362                                TargetMultiarchTriple,
3363                                Multilib.includeSuffix(), DriverArgs, CC1Args))
3364     return;
3365
3366   // Otherwise, fall back on a bunch of options which don't use multiarch
3367   // layouts for simplicity.
3368   const std::string LibStdCXXIncludePathCandidates[] = {
3369     // Gentoo is weird and places its headers inside the GCC install, so if the
3370     // first attempt to find the headers fails, try these patterns.
3371     InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3372         Version.MinorStr,
3373     InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3374     // Android standalone toolchain has C++ headers in yet another place.
3375     LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
3376     // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
3377     // without a subdirectory corresponding to the gcc version.
3378     LibDir.str() + "/../include/c++",
3379   };
3380
3381   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3382     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3383                                  /*GCCMultiarchTriple*/ "",
3384                                  /*TargetMultiarchTriple*/ "",
3385                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
3386       break;
3387   }
3388 }
3389
3390 bool Linux::isPIEDefault() const {
3391   return getSanitizerArgs().requiresPIE();
3392 }
3393
3394 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
3395
3396 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3397   : Generic_ELF(D, Triple, Args) {
3398
3399   // Path mangling to find libexec
3400   getProgramPaths().push_back(getDriver().getInstalledDir());
3401   if (getDriver().getInstalledDir() != getDriver().Dir)
3402     getProgramPaths().push_back(getDriver().Dir);
3403
3404   getFilePaths().push_back(getDriver().Dir + "/../lib");
3405   getFilePaths().push_back("/usr/lib");
3406   if (llvm::sys::fs::exists("/usr/lib/gcc47"))
3407     getFilePaths().push_back("/usr/lib/gcc47");
3408   else
3409     getFilePaths().push_back("/usr/lib/gcc44");
3410 }
3411
3412 Tool *DragonFly::buildAssembler() const {
3413   return new tools::dragonfly::Assemble(*this);
3414 }
3415
3416 Tool *DragonFly::buildLinker() const {
3417   return new tools::dragonfly::Link(*this);
3418 }
3419
3420
3421 /// XCore tool chain
3422 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
3423              const ArgList &Args) : ToolChain(D, Triple, Args) {
3424   // ProgramPaths are found via 'PATH' environment variable.
3425 }
3426
3427 Tool *XCore::buildAssembler() const {
3428   return new tools::XCore::Assemble(*this);
3429 }
3430
3431 Tool *XCore::buildLinker() const {
3432   return new tools::XCore::Link(*this);
3433 }
3434
3435 bool XCore::isPICDefault() const {
3436   return false;
3437 }
3438
3439 bool XCore::isPIEDefault() const {
3440   return false;
3441 }
3442
3443 bool XCore::isPICDefaultForced() const {
3444   return false;
3445 }
3446
3447 bool XCore::SupportsProfiling() const {
3448   return false;
3449 }
3450
3451 bool XCore::hasBlocksRuntime() const {
3452   return false;
3453 }
3454
3455 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3456                                       ArgStringList &CC1Args) const {
3457   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3458       DriverArgs.hasArg(options::OPT_nostdlibinc))
3459     return;
3460   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
3461     SmallVector<StringRef, 4> Dirs;
3462     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3463     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3464     ArrayRef<StringRef> DirVec(Dirs);
3465     addSystemIncludes(DriverArgs, CC1Args, DirVec);
3466   }
3467 }
3468
3469 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3470                                      llvm::opt::ArgStringList &CC1Args) const {
3471   CC1Args.push_back("-nostdsysteminc");
3472 }
3473
3474 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3475                                          ArgStringList &CC1Args) const {
3476   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3477       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3478       DriverArgs.hasArg(options::OPT_nostdincxx))
3479     return;
3480   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
3481     SmallVector<StringRef, 4> Dirs;
3482     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3483     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3484     ArrayRef<StringRef> DirVec(Dirs);
3485     addSystemIncludes(DriverArgs, CC1Args, DirVec);
3486   }
3487 }
3488
3489 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
3490                                 ArgStringList &CmdArgs) const {
3491   // We don't output any lib args. This is handled by xcc.
3492 }