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