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