]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
Merge llvm, clang, lld and lldb trunk r291274, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains.cpp
1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===//
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/Cuda.h"
12 #include "clang/Basic/ObjCRuntime.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Distro.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Option/Arg.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Option/OptTable.h"
29 #include "llvm/Option/Option.h"
30 #include "llvm/ProfileData/InstrProf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/TargetParser.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cstdlib> // ::getenv
39 #include <system_error>
40
41 using namespace clang::driver;
42 using namespace clang::driver::toolchains;
43 using namespace clang;
44 using namespace llvm::opt;
45
46 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
47     : ToolChain(D, Triple, Args) {
48   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
49   getProgramPaths().push_back(getDriver().getInstalledDir());
50   if (getDriver().getInstalledDir() != getDriver().Dir)
51     getProgramPaths().push_back(getDriver().Dir);
52 }
53
54 /// Darwin - Darwin tool chain for i386 and x86_64.
55 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
56     : MachO(D, Triple, Args), TargetInitialized(false),
57       CudaInstallation(D, Triple, Args) {}
58
59 types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
60   types::ID Ty = types::lookupTypeForExtension(Ext);
61
62   // Darwin always preprocesses assembly files (unless -x is used explicitly).
63   if (Ty == types::TY_PP_Asm)
64     return types::TY_Asm;
65
66   return Ty;
67 }
68
69 bool MachO::HasNativeLLVMSupport() const { return true; }
70
71 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
72   // Default to use libc++ on OS X 10.9+ and iOS 7+.
73   if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
74        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
75        isTargetWatchOSBased())
76     return ToolChain::CST_Libcxx;
77
78   return ToolChain::CST_Libstdcxx;
79 }
80
81 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
82 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
83   if (isTargetWatchOSBased())
84     return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
85   if (isTargetIOSBased())
86     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
87   if (isNonFragile)
88     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
89   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
90 }
91
92 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
93 bool Darwin::hasBlocksRuntime() const {
94   if (isTargetWatchOSBased())
95     return true;
96   else if (isTargetIOSBased())
97     return !isIPhoneOSVersionLT(3, 2);
98   else {
99     assert(isTargetMacOS() && "unexpected darwin target");
100     return !isMacosxVersionLT(10, 6);
101   }
102 }
103
104 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
105                                 ArgStringList &CC1Args) const {
106   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
107 }
108
109 // This is just a MachO name translation routine and there's no
110 // way to join this into ARMTargetParser without breaking all
111 // other assumptions. Maybe MachO should consider standardising
112 // their nomenclature.
113 static const char *ArmMachOArchName(StringRef Arch) {
114   return llvm::StringSwitch<const char *>(Arch)
115       .Case("armv6k", "armv6")
116       .Case("armv6m", "armv6m")
117       .Case("armv5tej", "armv5")
118       .Case("xscale", "xscale")
119       .Case("armv4t", "armv4t")
120       .Case("armv7", "armv7")
121       .Cases("armv7a", "armv7-a", "armv7")
122       .Cases("armv7r", "armv7-r", "armv7")
123       .Cases("armv7em", "armv7e-m", "armv7em")
124       .Cases("armv7k", "armv7-k", "armv7k")
125       .Cases("armv7m", "armv7-m", "armv7m")
126       .Cases("armv7s", "armv7-s", "armv7s")
127       .Default(nullptr);
128 }
129
130 static const char *ArmMachOArchNameCPU(StringRef CPU) {
131   unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
132   if (ArchKind == llvm::ARM::AK_INVALID)
133     return nullptr;
134   StringRef Arch = llvm::ARM::getArchName(ArchKind);
135
136   // FIXME: Make sure this MachO triple mangling is really necessary.
137   // ARMv5* normalises to ARMv5.
138   if (Arch.startswith("armv5"))
139     Arch = Arch.substr(0, 5);
140   // ARMv6*, except ARMv6M, normalises to ARMv6.
141   else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
142     Arch = Arch.substr(0, 5);
143   // ARMv7A normalises to ARMv7.
144   else if (Arch.endswith("v7a"))
145     Arch = Arch.substr(0, 5);
146   return Arch.data();
147 }
148
149 static bool isSoftFloatABI(const ArgList &Args) {
150   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
151                            options::OPT_mfloat_abi_EQ);
152   if (!A)
153     return false;
154
155   return A->getOption().matches(options::OPT_msoft_float) ||
156          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
157           A->getValue() == StringRef("soft"));
158 }
159
160 StringRef MachO::getMachOArchName(const ArgList &Args) const {
161   switch (getTriple().getArch()) {
162   default:
163     return getDefaultUniversalArchName();
164
165   case llvm::Triple::aarch64:
166     return "arm64";
167
168   case llvm::Triple::thumb:
169   case llvm::Triple::arm:
170     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
171       if (const char *Arch = ArmMachOArchName(A->getValue()))
172         return Arch;
173
174     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
175       if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
176         return Arch;
177
178     return "arm";
179   }
180 }
181
182 Darwin::~Darwin() {}
183
184 MachO::~MachO() {}
185
186 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
187                                                 types::ID InputType) const {
188   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
189
190   // If the target isn't initialized (e.g., an unknown Darwin platform, return
191   // the default triple).
192   if (!isTargetInitialized())
193     return Triple.getTriple();
194
195   SmallString<16> Str;
196   if (isTargetWatchOSBased())
197     Str += "watchos";
198   else if (isTargetTvOSBased())
199     Str += "tvos";
200   else if (isTargetIOSBased())
201     Str += "ios";
202   else
203     Str += "macosx";
204   Str += getTargetVersion().getAsString();
205   Triple.setOSName(Str);
206
207   return Triple.getTriple();
208 }
209
210 void Generic_ELF::anchor() {}
211
212 Tool *MachO::getTool(Action::ActionClass AC) const {
213   switch (AC) {
214   case Action::LipoJobClass:
215     if (!Lipo)
216       Lipo.reset(new tools::darwin::Lipo(*this));
217     return Lipo.get();
218   case Action::DsymutilJobClass:
219     if (!Dsymutil)
220       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
221     return Dsymutil.get();
222   case Action::VerifyDebugInfoJobClass:
223     if (!VerifyDebug)
224       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
225     return VerifyDebug.get();
226   default:
227     return ToolChain::getTool(AC);
228   }
229 }
230
231 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
232
233 Tool *MachO::buildAssembler() const {
234   return new tools::darwin::Assembler(*this);
235 }
236
237 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
238                          const ArgList &Args)
239     : Darwin(D, Triple, Args) {}
240
241 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
242   // For modern targets, promote certain warnings to errors.
243   if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
244     // Always enable -Wdeprecated-objc-isa-usage and promote it
245     // to an error.
246     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
247     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
248
249     // For iOS and watchOS, also error about implicit function declarations,
250     // as that can impact calling conventions.
251     if (!isTargetMacOS())
252       CC1Args.push_back("-Werror=implicit-function-declaration");
253   }
254 }
255
256 /// \brief Determine whether Objective-C automated reference counting is
257 /// enabled.
258 static bool isObjCAutoRefCount(const ArgList &Args) {
259   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
260 }
261
262 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
263                                  ArgStringList &CmdArgs) const {
264   // Avoid linking compatibility stubs on i386 mac.
265   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
266     return;
267
268   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
269
270   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
271       runtime.hasSubscripting())
272     return;
273
274   CmdArgs.push_back("-force_load");
275   SmallString<128> P(getDriver().ClangExecutable);
276   llvm::sys::path::remove_filename(P); // 'clang'
277   llvm::sys::path::remove_filename(P); // 'bin'
278   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
279   // Mash in the platform.
280   if (isTargetWatchOSSimulator())
281     P += "watchsimulator";
282   else if (isTargetWatchOS())
283     P += "watchos";
284   else if (isTargetTvOSSimulator())
285     P += "appletvsimulator";
286   else if (isTargetTvOS())
287     P += "appletvos";
288   else if (isTargetIOSSimulator())
289     P += "iphonesimulator";
290   else if (isTargetIPhoneOS())
291     P += "iphoneos";
292   else
293     P += "macosx";
294   P += ".a";
295
296   CmdArgs.push_back(Args.MakeArgString(P));
297 }
298
299 unsigned DarwinClang::GetDefaultDwarfVersion() const {
300   // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
301   if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
302       (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
303     return 2;
304   return 4;
305 }
306
307 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
308                               StringRef DarwinLibName, bool AlwaysLink,
309                               bool IsEmbedded, bool AddRPath) const {
310   SmallString<128> Dir(getDriver().ResourceDir);
311   llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
312
313   SmallString<128> P(Dir);
314   llvm::sys::path::append(P, DarwinLibName);
315
316   // For now, allow missing resource libraries to support developers who may
317   // not have compiler-rt checked out or integrated into their build (unless
318   // we explicitly force linking with this library).
319   if (AlwaysLink || getVFS().exists(P))
320     CmdArgs.push_back(Args.MakeArgString(P));
321
322   // Adding the rpaths might negatively interact when other rpaths are involved,
323   // so we should make sure we add the rpaths last, after all user-specified
324   // rpaths. This is currently true from this place, but we need to be
325   // careful if this function is ever called before user's rpaths are emitted.
326   if (AddRPath) {
327     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
328
329     // Add @executable_path to rpath to support having the dylib copied with
330     // the executable.
331     CmdArgs.push_back("-rpath");
332     CmdArgs.push_back("@executable_path");
333
334     // Add the path to the resource dir to rpath to support using the dylib
335     // from the default location without copying.
336     CmdArgs.push_back("-rpath");
337     CmdArgs.push_back(Args.MakeArgString(Dir));
338   }
339 }
340
341 StringRef Darwin::getPlatformFamily() const {
342   switch (TargetPlatform) {
343     case DarwinPlatformKind::MacOS:
344       return "MacOSX";
345     case DarwinPlatformKind::IPhoneOS:
346     case DarwinPlatformKind::IPhoneOSSimulator:
347       return "iPhone";
348     case DarwinPlatformKind::TvOS:
349     case DarwinPlatformKind::TvOSSimulator:
350       return "AppleTV";
351     case DarwinPlatformKind::WatchOS:
352     case DarwinPlatformKind::WatchOSSimulator:
353       return "Watch";
354   }
355   llvm_unreachable("Unsupported platform");
356 }
357
358 StringRef Darwin::getSDKName(StringRef isysroot) {
359   // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
360   llvm::sys::path::const_iterator SDKDir;
361   auto BeginSDK = llvm::sys::path::begin(isysroot);
362   auto EndSDK = llvm::sys::path::end(isysroot);
363   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
364     StringRef SDK = *IT;
365     if (SDK.endswith(".sdk"))
366       return SDK.slice(0, SDK.size() - 4);
367   }
368   return "";
369 }
370
371 StringRef Darwin::getOSLibraryNameSuffix() const {
372   switch(TargetPlatform) {
373   case DarwinPlatformKind::MacOS:
374     return "osx";
375   case DarwinPlatformKind::IPhoneOS:
376     return "ios";
377   case DarwinPlatformKind::IPhoneOSSimulator:
378     return "iossim";
379   case DarwinPlatformKind::TvOS:
380     return "tvos";
381   case DarwinPlatformKind::TvOSSimulator:
382     return "tvossim";
383   case DarwinPlatformKind::WatchOS:
384     return "watchos";
385   case DarwinPlatformKind::WatchOSSimulator:
386     return "watchossim";
387   }
388   llvm_unreachable("Unsupported platform");
389 }
390
391 void Darwin::addProfileRTLibs(const ArgList &Args,
392                               ArgStringList &CmdArgs) const {
393   if (!needsProfileRT(Args)) return;
394
395   AddLinkRuntimeLib(Args, CmdArgs, (Twine("libclang_rt.profile_") +
396        getOSLibraryNameSuffix() + ".a").str(),
397                     /*AlwaysLink*/ true);
398 }
399
400 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
401                                           ArgStringList &CmdArgs,
402                                           StringRef Sanitizer) const {
403   AddLinkRuntimeLib(
404       Args, CmdArgs,
405       (Twine("libclang_rt.") + Sanitizer + "_" +
406        getOSLibraryNameSuffix() + "_dynamic.dylib").str(),
407       /*AlwaysLink*/ true, /*IsEmbedded*/ false,
408       /*AddRPath*/ true);
409 }
410
411 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
412     const ArgList &Args) const {
413   if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
414     StringRef Value = A->getValue();
415     if (Value != "compiler-rt")
416       getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
417           << Value << "darwin";
418   }
419
420   return ToolChain::RLT_CompilerRT;
421 }
422
423 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
424                                         ArgStringList &CmdArgs) const {
425   // Call once to ensure diagnostic is printed if wrong value was specified
426   GetRuntimeLibType(Args);
427
428   // Darwin doesn't support real static executables, don't link any runtime
429   // libraries with -static.
430   if (Args.hasArg(options::OPT_static) ||
431       Args.hasArg(options::OPT_fapple_kext) ||
432       Args.hasArg(options::OPT_mkernel))
433     return;
434
435   // Reject -static-libgcc for now, we can deal with this when and if someone
436   // cares. This is useful in situations where someone wants to statically link
437   // something like libstdc++, and needs its runtime support routines.
438   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
439     getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
440     return;
441   }
442
443   const SanitizerArgs &Sanitize = getSanitizerArgs();
444   if (Sanitize.needsAsanRt())
445     AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
446   if (Sanitize.needsUbsanRt())
447     AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
448   if (Sanitize.needsTsanRt())
449     AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
450   if (Sanitize.needsStatsRt()) {
451     StringRef OS = isTargetMacOS() ? "osx" : "iossim";
452     AddLinkRuntimeLib(Args, CmdArgs,
453                       (Twine("libclang_rt.stats_client_") + OS + ".a").str(),
454                       /*AlwaysLink=*/true);
455     AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
456   }
457   if (Sanitize.needsEsanRt())
458     AddLinkSanitizerLibArgs(Args, CmdArgs, "esan");
459
460   // Otherwise link libSystem, then the dynamic runtime library, and finally any
461   // target specific static runtime library.
462   CmdArgs.push_back("-lSystem");
463
464   // Select the dynamic runtime library and the target specific static library.
465   if (isTargetWatchOSBased()) {
466     // We currently always need a static runtime library for watchOS.
467     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
468   } else if (isTargetTvOSBased()) {
469     // We currently always need a static runtime library for tvOS.
470     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
471   } else if (isTargetIOSBased()) {
472     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
473     // it never went into the SDK.
474     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
475     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
476         getTriple().getArch() != llvm::Triple::aarch64)
477       CmdArgs.push_back("-lgcc_s.1");
478
479     // We currently always need a static runtime library for iOS.
480     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
481   } else {
482     assert(isTargetMacOS() && "unexpected non MacOS platform");
483     // The dynamic runtime library was merged with libSystem for 10.6 and
484     // beyond; only 10.4 and 10.5 need an additional runtime library.
485     if (isMacosxVersionLT(10, 5))
486       CmdArgs.push_back("-lgcc_s.10.4");
487     else if (isMacosxVersionLT(10, 6))
488       CmdArgs.push_back("-lgcc_s.10.5");
489
490     // Originally for OS X, we thought we would only need a static runtime
491     // library when targeting 10.4, to provide versions of the static functions
492     // which were omitted from 10.4.dylib. This led to the creation of the 10.4
493     // builtins library.
494     //
495     // Unfortunately, that turned out to not be true, because Darwin system
496     // headers can still use eprintf on i386, and it is not exported from
497     // libSystem. Therefore, we still must provide a runtime library just for
498     // the tiny tiny handful of projects that *might* use that symbol.
499     //
500     // Then over time, we figured out it was useful to add more things to the
501     // runtime so we created libclang_rt.osx.a to provide new functions when
502     // deploying to old OS builds, and for a long time we had both eprintf and
503     // osx builtin libraries. Which just seems excessive. So with PR 28855, we
504     // are removing the eprintf library and expecting eprintf to be provided by
505     // the OS X builtins library.
506     if (isMacosxVersionLT(10, 5))
507       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
508     else
509       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
510   }
511 }
512
513 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
514   const OptTable &Opts = getDriver().getOpts();
515
516   // Support allowing the SDKROOT environment variable used by xcrun and other
517   // Xcode tools to define the default sysroot, by making it the default for
518   // isysroot.
519   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
520     // Warn if the path does not exist.
521     if (!getVFS().exists(A->getValue()))
522       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
523   } else {
524     if (char *env = ::getenv("SDKROOT")) {
525       // We only use this value as the default if it is an absolute path,
526       // exists, and it is not the root path.
527       if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
528           StringRef(env) != "/") {
529         Args.append(Args.MakeSeparateArg(
530             nullptr, Opts.getOption(options::OPT_isysroot), env));
531       }
532     }
533   }
534
535   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
536   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
537   Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ);
538   Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ);
539
540   if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
541     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
542         << OSXVersion->getAsString(Args)
543         << (iOSVersion ? iOSVersion :
544             TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
545     iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
546   } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
547     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
548         << iOSVersion->getAsString(Args)
549         << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
550     TvOSVersion = WatchOSVersion = nullptr;
551   } else if (TvOSVersion && WatchOSVersion) {
552      getDriver().Diag(diag::err_drv_argument_not_allowed_with)
553         << TvOSVersion->getAsString(Args)
554         << WatchOSVersion->getAsString(Args);
555     WatchOSVersion = nullptr;
556   } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
557     // If no deployment target was specified on the command line, check for
558     // environment defines.
559     std::string OSXTarget;
560     std::string iOSTarget;
561     std::string TvOSTarget;
562     std::string WatchOSTarget;
563
564     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
565       OSXTarget = env;
566     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
567       iOSTarget = env;
568     if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
569       TvOSTarget = env;
570     if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
571       WatchOSTarget = env;
572
573     // If there is no command-line argument to specify the Target version and
574     // no environment variable defined, see if we can set the default based
575     // on -isysroot.
576     if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
577         TvOSTarget.empty() && Args.hasArg(options::OPT_isysroot)) {
578       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
579         StringRef isysroot = A->getValue();
580         StringRef SDK = getSDKName(isysroot);
581         if (SDK.size() > 0) {
582           // Slice the version number out.
583           // Version number is between the first and the last number.
584           size_t StartVer = SDK.find_first_of("0123456789");
585           size_t EndVer = SDK.find_last_of("0123456789");
586           if (StartVer != StringRef::npos && EndVer > StartVer) {
587             StringRef Version = SDK.slice(StartVer, EndVer + 1);
588             if (SDK.startswith("iPhoneOS") ||
589                 SDK.startswith("iPhoneSimulator"))
590               iOSTarget = Version;
591             else if (SDK.startswith("MacOSX"))
592               OSXTarget = Version;
593             else if (SDK.startswith("WatchOS") ||
594                      SDK.startswith("WatchSimulator"))
595               WatchOSTarget = Version;
596             else if (SDK.startswith("AppleTVOS") ||
597                      SDK.startswith("AppleTVSimulator"))
598               TvOSTarget = Version;
599           }
600         }
601       }
602     }
603
604     // If no OSX or iOS target has been specified, try to guess platform
605     // from arch name and compute the version from the triple.
606     if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
607         WatchOSTarget.empty()) {
608       StringRef MachOArchName = getMachOArchName(Args);
609       unsigned Major, Minor, Micro;
610       if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
611           MachOArchName == "arm64") {
612         getTriple().getiOSVersion(Major, Minor, Micro);
613         llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
614                                             << Micro;
615       } else if (MachOArchName == "armv7k") {
616         getTriple().getWatchOSVersion(Major, Minor, Micro);
617         llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
618                                                 << Micro;
619       } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
620                  MachOArchName != "armv7em") {
621         if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
622           getDriver().Diag(diag::err_drv_invalid_darwin_version)
623               << getTriple().getOSName();
624         }
625         llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
626                                             << Micro;
627       }
628     }
629
630     // Do not allow conflicts with the watchOS target.
631     if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
632       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
633         << "WATCHOS_DEPLOYMENT_TARGET"
634         << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
635             "TVOS_DEPLOYMENT_TARGET");
636     }
637
638     // Do not allow conflicts with the tvOS target.
639     if (!TvOSTarget.empty() && !iOSTarget.empty()) {
640       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
641         << "TVOS_DEPLOYMENT_TARGET"
642         << "IPHONEOS_DEPLOYMENT_TARGET";
643     }
644
645     // Allow conflicts among OSX and iOS for historical reasons, but choose the
646     // default platform.
647     if (!OSXTarget.empty() && (!iOSTarget.empty() ||
648                                !WatchOSTarget.empty() ||
649                                !TvOSTarget.empty())) {
650       if (getTriple().getArch() == llvm::Triple::arm ||
651           getTriple().getArch() == llvm::Triple::aarch64 ||
652           getTriple().getArch() == llvm::Triple::thumb)
653         OSXTarget = "";
654       else
655         iOSTarget = WatchOSTarget = TvOSTarget = "";
656     }
657
658     if (!OSXTarget.empty()) {
659       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
660       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
661       Args.append(OSXVersion);
662     } else if (!iOSTarget.empty()) {
663       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
664       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
665       Args.append(iOSVersion);
666     } else if (!TvOSTarget.empty()) {
667       const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
668       TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
669       Args.append(TvOSVersion);
670     } else if (!WatchOSTarget.empty()) {
671       const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
672       WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
673       Args.append(WatchOSVersion);
674     }
675   }
676
677   DarwinPlatformKind Platform;
678   if (OSXVersion)
679     Platform = MacOS;
680   else if (iOSVersion)
681     Platform = IPhoneOS;
682   else if (TvOSVersion)
683     Platform = TvOS;
684   else if (WatchOSVersion)
685     Platform = WatchOS;
686   else
687     llvm_unreachable("Unable to infer Darwin variant");
688
689   // Set the tool chain target information.
690   unsigned Major, Minor, Micro;
691   bool HadExtra;
692   if (Platform == MacOS) {
693     assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
694            "Unknown target platform!");
695     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
696                                    HadExtra) ||
697         HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
698       getDriver().Diag(diag::err_drv_invalid_version_number)
699           << OSXVersion->getAsString(Args);
700   } else if (Platform == IPhoneOS) {
701     assert(iOSVersion && "Unknown target platform!");
702     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
703                                    HadExtra) ||
704         HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
705       getDriver().Diag(diag::err_drv_invalid_version_number)
706           << iOSVersion->getAsString(Args);
707   } else if (Platform == TvOS) {
708     if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
709                                    Micro, HadExtra) || HadExtra ||
710         Major >= 100 || Minor >= 100 || Micro >= 100)
711       getDriver().Diag(diag::err_drv_invalid_version_number)
712           << TvOSVersion->getAsString(Args);
713   } else if (Platform == WatchOS) {
714     if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
715                                    Micro, HadExtra) || HadExtra ||
716         Major >= 10 || Minor >= 100 || Micro >= 100)
717       getDriver().Diag(diag::err_drv_invalid_version_number)
718           << WatchOSVersion->getAsString(Args);
719   } else
720     llvm_unreachable("unknown kind of Darwin platform");
721
722   // Recognize iOS targets with an x86 architecture as the iOS simulator.
723   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
724                      getTriple().getArch() == llvm::Triple::x86_64))
725     Platform = IPhoneOSSimulator;
726   if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
727                       getTriple().getArch() == llvm::Triple::x86_64))
728     Platform = TvOSSimulator;
729   if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
730                          getTriple().getArch() == llvm::Triple::x86_64))
731     Platform = WatchOSSimulator;
732
733   setTarget(Platform, Major, Minor, Micro);
734
735   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
736     StringRef SDK = getSDKName(A->getValue());
737     if (SDK.size() > 0) {
738       size_t StartVer = SDK.find_first_of("0123456789");
739       StringRef SDKName = SDK.slice(0, StartVer);
740       if (!SDKName.startswith(getPlatformFamily()))
741         getDriver().Diag(diag::warn_incompatible_sysroot)
742             << SDKName << getPlatformFamily();
743     }
744   }
745 }
746
747 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
748                                       ArgStringList &CmdArgs) const {
749   CXXStdlibType Type = GetCXXStdlibType(Args);
750
751   switch (Type) {
752   case ToolChain::CST_Libcxx:
753     CmdArgs.push_back("-lc++");
754     break;
755
756   case ToolChain::CST_Libstdcxx:
757     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
758     // it was previously found in the gcc lib dir. However, for all the Darwin
759     // platforms we care about it was -lstdc++.6, so we search for that
760     // explicitly if we can't see an obvious -lstdc++ candidate.
761
762     // Check in the sysroot first.
763     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
764       SmallString<128> P(A->getValue());
765       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
766
767       if (!getVFS().exists(P)) {
768         llvm::sys::path::remove_filename(P);
769         llvm::sys::path::append(P, "libstdc++.6.dylib");
770         if (getVFS().exists(P)) {
771           CmdArgs.push_back(Args.MakeArgString(P));
772           return;
773         }
774       }
775     }
776
777     // Otherwise, look in the root.
778     // FIXME: This should be removed someday when we don't have to care about
779     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
780     if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
781         getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
782       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
783       return;
784     }
785
786     // Otherwise, let the linker search.
787     CmdArgs.push_back("-lstdc++");
788     break;
789   }
790 }
791
792 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
793                                    ArgStringList &CmdArgs) const {
794   // For Darwin platforms, use the compiler-rt-based support library
795   // instead of the gcc-provided one (which is also incidentally
796   // only present in the gcc lib dir, which makes it hard to find).
797
798   SmallString<128> P(getDriver().ResourceDir);
799   llvm::sys::path::append(P, "lib", "darwin");
800
801   // Use the newer cc_kext for iOS ARM after 6.0.
802   if (isTargetWatchOS()) {
803     llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
804   } else if (isTargetTvOS()) {
805     llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
806   } else if (isTargetIPhoneOS()) {
807     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
808   } else {
809     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
810   }
811
812   // For now, allow missing resource libraries to support developers who may
813   // not have compiler-rt checked out or integrated into their build.
814   if (getVFS().exists(P))
815     CmdArgs.push_back(Args.MakeArgString(P));
816 }
817
818 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
819                                      StringRef BoundArch,
820                                      Action::OffloadKind) const {
821   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
822   const OptTable &Opts = getDriver().getOpts();
823
824   // FIXME: We really want to get out of the tool chain level argument
825   // translation business, as it makes the driver functionality much
826   // more opaque. For now, we follow gcc closely solely for the
827   // purpose of easily achieving feature parity & testability. Once we
828   // have something that works, we should reevaluate each translation
829   // and try to push it down into tool specific logic.
830
831   for (Arg *A : Args) {
832     if (A->getOption().matches(options::OPT_Xarch__)) {
833       // Skip this argument unless the architecture matches either the toolchain
834       // triple arch, or the arch being bound.
835       llvm::Triple::ArchType XarchArch =
836           tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
837       if (!(XarchArch == getArch() ||
838             (!BoundArch.empty() &&
839              XarchArch ==
840                  tools::darwin::getArchTypeForMachOArchName(BoundArch))))
841         continue;
842
843       Arg *OriginalArg = A;
844       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
845       unsigned Prev = Index;
846       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
847
848       // If the argument parsing failed or more than one argument was
849       // consumed, the -Xarch_ argument's parameter tried to consume
850       // extra arguments. Emit an error and ignore.
851       //
852       // We also want to disallow any options which would alter the
853       // driver behavior; that isn't going to work in our model. We
854       // use isDriverOption() as an approximation, although things
855       // like -O4 are going to slip through.
856       if (!XarchArg || Index > Prev + 1) {
857         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
858             << A->getAsString(Args);
859         continue;
860       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
861         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
862             << A->getAsString(Args);
863         continue;
864       }
865
866       XarchArg->setBaseArg(A);
867
868       A = XarchArg.release();
869       DAL->AddSynthesizedArg(A);
870
871       // Linker input arguments require custom handling. The problem is that we
872       // have already constructed the phase actions, so we can not treat them as
873       // "input arguments".
874       if (A->getOption().hasFlag(options::LinkerInput)) {
875         // Convert the argument into individual Zlinker_input_args.
876         for (const char *Value : A->getValues()) {
877           DAL->AddSeparateArg(
878               OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
879         }
880         continue;
881       }
882     }
883
884     // Sob. These is strictly gcc compatible for the time being. Apple
885     // gcc translates options twice, which means that self-expanding
886     // options add duplicates.
887     switch ((options::ID)A->getOption().getID()) {
888     default:
889       DAL->append(A);
890       break;
891
892     case options::OPT_mkernel:
893     case options::OPT_fapple_kext:
894       DAL->append(A);
895       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
896       break;
897
898     case options::OPT_dependency_file:
899       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
900       break;
901
902     case options::OPT_gfull:
903       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
904       DAL->AddFlagArg(
905           A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
906       break;
907
908     case options::OPT_gused:
909       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
910       DAL->AddFlagArg(
911           A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
912       break;
913
914     case options::OPT_shared:
915       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
916       break;
917
918     case options::OPT_fconstant_cfstrings:
919       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
920       break;
921
922     case options::OPT_fno_constant_cfstrings:
923       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
924       break;
925
926     case options::OPT_Wnonportable_cfstrings:
927       DAL->AddFlagArg(A,
928                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
929       break;
930
931     case options::OPT_Wno_nonportable_cfstrings:
932       DAL->AddFlagArg(
933           A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
934       break;
935
936     case options::OPT_fpascal_strings:
937       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
938       break;
939
940     case options::OPT_fno_pascal_strings:
941       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
942       break;
943     }
944   }
945
946   if (getTriple().getArch() == llvm::Triple::x86 ||
947       getTriple().getArch() == llvm::Triple::x86_64)
948     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
949       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
950                         "core2");
951
952   // Add the arch options based on the particular spelling of -arch, to match
953   // how the driver driver works.
954   if (!BoundArch.empty()) {
955     StringRef Name = BoundArch;
956     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
957     const Option MArch = Opts.getOption(options::OPT_march_EQ);
958
959     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
960     // which defines the list of which architectures we accept.
961     if (Name == "ppc")
962       ;
963     else if (Name == "ppc601")
964       DAL->AddJoinedArg(nullptr, MCpu, "601");
965     else if (Name == "ppc603")
966       DAL->AddJoinedArg(nullptr, MCpu, "603");
967     else if (Name == "ppc604")
968       DAL->AddJoinedArg(nullptr, MCpu, "604");
969     else if (Name == "ppc604e")
970       DAL->AddJoinedArg(nullptr, MCpu, "604e");
971     else if (Name == "ppc750")
972       DAL->AddJoinedArg(nullptr, MCpu, "750");
973     else if (Name == "ppc7400")
974       DAL->AddJoinedArg(nullptr, MCpu, "7400");
975     else if (Name == "ppc7450")
976       DAL->AddJoinedArg(nullptr, MCpu, "7450");
977     else if (Name == "ppc970")
978       DAL->AddJoinedArg(nullptr, MCpu, "970");
979
980     else if (Name == "ppc64" || Name == "ppc64le")
981       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
982
983     else if (Name == "i386")
984       ;
985     else if (Name == "i486")
986       DAL->AddJoinedArg(nullptr, MArch, "i486");
987     else if (Name == "i586")
988       DAL->AddJoinedArg(nullptr, MArch, "i586");
989     else if (Name == "i686")
990       DAL->AddJoinedArg(nullptr, MArch, "i686");
991     else if (Name == "pentium")
992       DAL->AddJoinedArg(nullptr, MArch, "pentium");
993     else if (Name == "pentium2")
994       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
995     else if (Name == "pentpro")
996       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
997     else if (Name == "pentIIm3")
998       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
999
1000     else if (Name == "x86_64")
1001       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1002     else if (Name == "x86_64h") {
1003       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1004       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
1005     }
1006
1007     else if (Name == "arm")
1008       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1009     else if (Name == "armv4t")
1010       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1011     else if (Name == "armv5")
1012       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
1013     else if (Name == "xscale")
1014       DAL->AddJoinedArg(nullptr, MArch, "xscale");
1015     else if (Name == "armv6")
1016       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
1017     else if (Name == "armv6m")
1018       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
1019     else if (Name == "armv7")
1020       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
1021     else if (Name == "armv7em")
1022       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
1023     else if (Name == "armv7k")
1024       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
1025     else if (Name == "armv7m")
1026       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
1027     else if (Name == "armv7s")
1028       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
1029   }
1030
1031   return DAL;
1032 }
1033
1034 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
1035                                   ArgStringList &CmdArgs) const {
1036   // Embedded targets are simple at the moment, not supporting sanitizers and
1037   // with different libraries for each member of the product { static, PIC } x
1038   // { hard-float, soft-float }
1039   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
1040   CompilerRT +=
1041       (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
1042           ? "hard"
1043           : "soft";
1044   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
1045
1046   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
1047 }
1048
1049 DerivedArgList *
1050 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
1051                       Action::OffloadKind DeviceOffloadKind) const {
1052   // First get the generic Apple args, before moving onto Darwin-specific ones.
1053   DerivedArgList *DAL =
1054       MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
1055   const OptTable &Opts = getDriver().getOpts();
1056
1057   // If no architecture is bound, none of the translations here are relevant.
1058   if (BoundArch.empty())
1059     return DAL;
1060
1061   // Add an explicit version min argument for the deployment target. We do this
1062   // after argument translation because -Xarch_ arguments may add a version min
1063   // argument.
1064   AddDeploymentTarget(*DAL);
1065
1066   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1067   // FIXME: It would be far better to avoid inserting those -static arguments,
1068   // but we can't check the deployment target in the translation code until
1069   // it is set here.
1070   if (isTargetWatchOSBased() ||
1071       (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1072     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1073       Arg *A = *it;
1074       ++it;
1075       if (A->getOption().getID() != options::OPT_mkernel &&
1076           A->getOption().getID() != options::OPT_fapple_kext)
1077         continue;
1078       assert(it != ie && "unexpected argument translation");
1079       A = *it;
1080       assert(A->getOption().getID() == options::OPT_static &&
1081              "missing expected -static argument");
1082       it = DAL->getArgs().erase(it);
1083     }
1084   }
1085
1086   if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
1087       GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
1088     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1089                       "libc++");
1090
1091   // Validate the C++ standard library choice.
1092   CXXStdlibType Type = GetCXXStdlibType(*DAL);
1093   if (Type == ToolChain::CST_Libcxx) {
1094     // Check whether the target provides libc++.
1095     StringRef where;
1096
1097     // Complain about targeting iOS < 5.0 in any way.
1098     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1099       where = "iOS 5.0";
1100
1101     if (where != StringRef()) {
1102       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1103     }
1104   }
1105
1106   auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
1107   if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
1108     if (Args.hasFlag(options::OPT_fomit_frame_pointer,
1109                      options::OPT_fno_omit_frame_pointer, false))
1110       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
1111           << "-fomit-frame-pointer" << BoundArch;
1112     if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1113                      options::OPT_mno_omit_leaf_frame_pointer, false))
1114       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
1115           << "-momit-leaf-frame-pointer" << BoundArch;
1116   }
1117
1118   return DAL;
1119 }
1120
1121 bool MachO::IsUnwindTablesDefault() const {
1122   return getArch() == llvm::Triple::x86_64;
1123 }
1124
1125 bool MachO::UseDwarfDebugFlags() const {
1126   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1127     return S[0] != '\0';
1128   return false;
1129 }
1130
1131 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1132   // Darwin uses SjLj exceptions on ARM.
1133   if (getTriple().getArch() != llvm::Triple::arm &&
1134       getTriple().getArch() != llvm::Triple::thumb)
1135     return false;
1136
1137   // Only watchOS uses the new DWARF/Compact unwinding method.
1138   llvm::Triple Triple(ComputeLLVMTriple(Args));
1139   return !Triple.isWatchABI();
1140 }
1141
1142 bool Darwin::SupportsEmbeddedBitcode() const {
1143   assert(TargetInitialized && "Target not initialized!");
1144   if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
1145     return false;
1146   return true;
1147 }
1148
1149 bool MachO::isPICDefault() const { return true; }
1150
1151 bool MachO::isPIEDefault() const { return false; }
1152
1153 bool MachO::isPICDefaultForced() const {
1154   return (getArch() == llvm::Triple::x86_64 ||
1155           getArch() == llvm::Triple::aarch64);
1156 }
1157
1158 bool MachO::SupportsProfiling() const {
1159   // Profiling instrumentation is only supported on x86.
1160   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1161 }
1162
1163 void Darwin::addMinVersionArgs(const ArgList &Args,
1164                                ArgStringList &CmdArgs) const {
1165   VersionTuple TargetVersion = getTargetVersion();
1166
1167   if (isTargetWatchOS())
1168     CmdArgs.push_back("-watchos_version_min");
1169   else if (isTargetWatchOSSimulator())
1170     CmdArgs.push_back("-watchos_simulator_version_min");
1171   else if (isTargetTvOS())
1172     CmdArgs.push_back("-tvos_version_min");
1173   else if (isTargetTvOSSimulator())
1174     CmdArgs.push_back("-tvos_simulator_version_min");
1175   else if (isTargetIOSSimulator())
1176     CmdArgs.push_back("-ios_simulator_version_min");
1177   else if (isTargetIOSBased())
1178     CmdArgs.push_back("-iphoneos_version_min");
1179   else {
1180     assert(isTargetMacOS() && "unexpected target");
1181     CmdArgs.push_back("-macosx_version_min");
1182   }
1183
1184   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1185 }
1186
1187 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1188                                     ArgStringList &CmdArgs) const {
1189   // Derived from startfile spec.
1190   if (Args.hasArg(options::OPT_dynamiclib)) {
1191     // Derived from darwin_dylib1 spec.
1192     if (isTargetWatchOSBased()) {
1193       ; // watchOS does not need dylib1.o.
1194     } else if (isTargetIOSSimulator()) {
1195       ; // iOS simulator does not need dylib1.o.
1196     } else if (isTargetIPhoneOS()) {
1197       if (isIPhoneOSVersionLT(3, 1))
1198         CmdArgs.push_back("-ldylib1.o");
1199     } else {
1200       if (isMacosxVersionLT(10, 5))
1201         CmdArgs.push_back("-ldylib1.o");
1202       else if (isMacosxVersionLT(10, 6))
1203         CmdArgs.push_back("-ldylib1.10.5.o");
1204     }
1205   } else {
1206     if (Args.hasArg(options::OPT_bundle)) {
1207       if (!Args.hasArg(options::OPT_static)) {
1208         // Derived from darwin_bundle1 spec.
1209         if (isTargetWatchOSBased()) {
1210           ; // watchOS does not need bundle1.o.
1211         } else if (isTargetIOSSimulator()) {
1212           ; // iOS simulator does not need bundle1.o.
1213         } else if (isTargetIPhoneOS()) {
1214           if (isIPhoneOSVersionLT(3, 1))
1215             CmdArgs.push_back("-lbundle1.o");
1216         } else {
1217           if (isMacosxVersionLT(10, 6))
1218             CmdArgs.push_back("-lbundle1.o");
1219         }
1220       }
1221     } else {
1222       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1223         if (Args.hasArg(options::OPT_static) ||
1224             Args.hasArg(options::OPT_object) ||
1225             Args.hasArg(options::OPT_preload)) {
1226           CmdArgs.push_back("-lgcrt0.o");
1227         } else {
1228           CmdArgs.push_back("-lgcrt1.o");
1229
1230           // darwin_crt2 spec is empty.
1231         }
1232         // By default on OS X 10.8 and later, we don't link with a crt1.o
1233         // file and the linker knows to use _main as the entry point.  But,
1234         // when compiling with -pg, we need to link with the gcrt1.o file,
1235         // so pass the -no_new_main option to tell the linker to use the
1236         // "start" symbol as the entry point.
1237         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1238           CmdArgs.push_back("-no_new_main");
1239       } else {
1240         if (Args.hasArg(options::OPT_static) ||
1241             Args.hasArg(options::OPT_object) ||
1242             Args.hasArg(options::OPT_preload)) {
1243           CmdArgs.push_back("-lcrt0.o");
1244         } else {
1245           // Derived from darwin_crt1 spec.
1246           if (isTargetWatchOSBased()) {
1247             ; // watchOS does not need crt1.o.
1248           } else if (isTargetIOSSimulator()) {
1249             ; // iOS simulator does not need crt1.o.
1250           } else if (isTargetIPhoneOS()) {
1251             if (getArch() == llvm::Triple::aarch64)
1252               ; // iOS does not need any crt1 files for arm64
1253             else if (isIPhoneOSVersionLT(3, 1))
1254               CmdArgs.push_back("-lcrt1.o");
1255             else if (isIPhoneOSVersionLT(6, 0))
1256               CmdArgs.push_back("-lcrt1.3.1.o");
1257           } else {
1258             if (isMacosxVersionLT(10, 5))
1259               CmdArgs.push_back("-lcrt1.o");
1260             else if (isMacosxVersionLT(10, 6))
1261               CmdArgs.push_back("-lcrt1.10.5.o");
1262             else if (isMacosxVersionLT(10, 8))
1263               CmdArgs.push_back("-lcrt1.10.6.o");
1264
1265             // darwin_crt2 spec is empty.
1266           }
1267         }
1268       }
1269     }
1270   }
1271
1272   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1273       !isTargetWatchOS() &&
1274       isMacosxVersionLT(10, 5)) {
1275     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1276     CmdArgs.push_back(Str);
1277   }
1278 }
1279
1280 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1281
1282 void Darwin::CheckObjCARC() const {
1283   if (isTargetIOSBased() || isTargetWatchOSBased() ||
1284       (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1285     return;
1286   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1287 }
1288
1289 SanitizerMask Darwin::getSupportedSanitizers() const {
1290   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
1291   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1292   Res |= SanitizerKind::Address;
1293   if (isTargetMacOS()) {
1294     if (!isMacosxVersionLT(10, 9))
1295       Res |= SanitizerKind::Vptr;
1296     Res |= SanitizerKind::SafeStack;
1297     if (IsX86_64)
1298       Res |= SanitizerKind::Thread;
1299   } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
1300     if (IsX86_64)
1301       Res |= SanitizerKind::Thread;
1302   }
1303   return Res;
1304 }
1305
1306 void Darwin::printVerboseInfo(raw_ostream &OS) const {
1307   CudaInstallation.print(OS);
1308 }
1309
1310 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1311 /// all subcommands; this relies on gcc translating the majority of
1312 /// command line options.
1313
1314 /// \brief Parse a GCCVersion object out of a string of text.
1315 ///
1316 /// This is the primary means of forming GCCVersion objects.
1317 /*static*/
1318 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1319   const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1320   std::pair<StringRef, StringRef> First = VersionText.split('.');
1321   std::pair<StringRef, StringRef> Second = First.second.split('.');
1322
1323   GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1324   if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1325     return BadVersion;
1326   GoodVersion.MajorStr = First.first.str();
1327   if (First.second.empty())
1328     return GoodVersion;
1329   if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1330     return BadVersion;
1331   GoodVersion.MinorStr = Second.first.str();
1332
1333   // First look for a number prefix and parse that if present. Otherwise just
1334   // stash the entire patch string in the suffix, and leave the number
1335   // unspecified. This covers versions strings such as:
1336   //   5        (handled above)
1337   //   4.4
1338   //   4.4.0
1339   //   4.4.x
1340   //   4.4.2-rc4
1341   //   4.4.x-patched
1342   // And retains any patch number it finds.
1343   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1344   if (!PatchText.empty()) {
1345     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1346       // Try to parse the number and any suffix.
1347       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1348           GoodVersion.Patch < 0)
1349         return BadVersion;
1350       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1351     }
1352   }
1353
1354   return GoodVersion;
1355 }
1356
1357 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1358 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1359                                           int RHSPatch,
1360                                           StringRef RHSPatchSuffix) const {
1361   if (Major != RHSMajor)
1362     return Major < RHSMajor;
1363   if (Minor != RHSMinor)
1364     return Minor < RHSMinor;
1365   if (Patch != RHSPatch) {
1366     // Note that versions without a specified patch sort higher than those with
1367     // a patch.
1368     if (RHSPatch == -1)
1369       return true;
1370     if (Patch == -1)
1371       return false;
1372
1373     // Otherwise just sort on the patch itself.
1374     return Patch < RHSPatch;
1375   }
1376   if (PatchSuffix != RHSPatchSuffix) {
1377     // Sort empty suffixes higher.
1378     if (RHSPatchSuffix.empty())
1379       return true;
1380     if (PatchSuffix.empty())
1381       return false;
1382
1383     // Provide a lexicographic sort to make this a total ordering.
1384     return PatchSuffix < RHSPatchSuffix;
1385   }
1386
1387   // The versions are equal.
1388   return false;
1389 }
1390
1391 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1392   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1393   if (A)
1394     return A->getValue();
1395   return GCC_INSTALL_PREFIX;
1396 }
1397
1398 /// \brief Initialize a GCCInstallationDetector from the driver.
1399 ///
1400 /// This performs all of the autodetection and sets up the various paths.
1401 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1402 ///
1403 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1404 /// should instead pull the target out of the driver. This is currently
1405 /// necessary because the driver doesn't store the final version of the target
1406 /// triple.
1407 void Generic_GCC::GCCInstallationDetector::init(
1408     const llvm::Triple &TargetTriple, const ArgList &Args,
1409     ArrayRef<std::string> ExtraTripleAliases) {
1410   llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1411                                          ? TargetTriple.get64BitArchVariant()
1412                                          : TargetTriple.get32BitArchVariant();
1413   // The library directories which may contain GCC installations.
1414   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1415   // The compatible GCC triples for this particular architecture.
1416   SmallVector<StringRef, 16> CandidateTripleAliases;
1417   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1418   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1419                            CandidateTripleAliases, CandidateBiarchLibDirs,
1420                            CandidateBiarchTripleAliases);
1421
1422   // Compute the set of prefixes for our search.
1423   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1424                                        D.PrefixDirs.end());
1425
1426   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1427   if (GCCToolchainDir != "") {
1428     if (GCCToolchainDir.back() == '/')
1429       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1430
1431     Prefixes.push_back(GCCToolchainDir);
1432   } else {
1433     // If we have a SysRoot, try that first.
1434     if (!D.SysRoot.empty()) {
1435       Prefixes.push_back(D.SysRoot);
1436       Prefixes.push_back(D.SysRoot + "/usr");
1437     }
1438
1439     // Then look for gcc installed alongside clang.
1440     Prefixes.push_back(D.InstalledDir + "/..");
1441
1442     // Then look for distribution supplied gcc installations.
1443     if (D.SysRoot.empty()) {
1444       // Look for RHEL devtoolsets.
1445       Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
1446       Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
1447       Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
1448       Prefixes.push_back("/opt/rh/devtoolset-1.1/root/usr");
1449       Prefixes.push_back("/opt/rh/devtoolset-1.0/root/usr");
1450       // And finally in /usr.
1451       Prefixes.push_back("/usr");
1452     }
1453   }
1454
1455   // Try to respect gcc-config on Gentoo. However, do that only
1456   // if --gcc-toolchain is not provided or equal to the Gentoo install
1457   // in /usr. This avoids accidentally enforcing the system GCC version
1458   // when using a custom toolchain.
1459   if (GCCToolchainDir == "" || GCCToolchainDir == D.SysRoot + "/usr") {
1460     for (StringRef CandidateTriple : ExtraTripleAliases) {
1461       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
1462         return;
1463     }
1464     for (StringRef CandidateTriple : CandidateTripleAliases) {
1465       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
1466         return;
1467     }
1468     for (StringRef CandidateTriple : CandidateBiarchTripleAliases) {
1469       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
1470         return;
1471     }
1472   }
1473
1474   // Loop over the various components which exist and select the best GCC
1475   // installation available. GCC installs are ranked by version number.
1476   Version = GCCVersion::Parse("0.0.0");
1477   for (const std::string &Prefix : Prefixes) {
1478     if (!D.getVFS().exists(Prefix))
1479       continue;
1480     for (StringRef Suffix : CandidateLibDirs) {
1481       const std::string LibDir = Prefix + Suffix.str();
1482       if (!D.getVFS().exists(LibDir))
1483         continue;
1484       for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1485         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1486       for (StringRef Candidate : CandidateTripleAliases)
1487         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1488     }
1489     for (StringRef Suffix : CandidateBiarchLibDirs) {
1490       const std::string LibDir = Prefix + Suffix.str();
1491       if (!D.getVFS().exists(LibDir))
1492         continue;
1493       for (StringRef Candidate : CandidateBiarchTripleAliases)
1494         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1495                                /*NeedsBiarchSuffix=*/ true);
1496     }
1497   }
1498 }
1499
1500 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1501   for (const auto &InstallPath : CandidateGCCInstallPaths)
1502     OS << "Found candidate GCC installation: " << InstallPath << "\n";
1503
1504   if (!GCCInstallPath.empty())
1505     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1506
1507   for (const auto &Multilib : Multilibs)
1508     OS << "Candidate multilib: " << Multilib << "\n";
1509
1510   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1511     OS << "Selected multilib: " << SelectedMultilib << "\n";
1512 }
1513
1514 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1515   if (BiarchSibling.hasValue()) {
1516     M = BiarchSibling.getValue();
1517     return true;
1518   }
1519   return false;
1520 }
1521
1522 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1523     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1524     SmallVectorImpl<StringRef> &LibDirs,
1525     SmallVectorImpl<StringRef> &TripleAliases,
1526     SmallVectorImpl<StringRef> &BiarchLibDirs,
1527     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1528   // Declare a bunch of static data sets that we'll select between below. These
1529   // are specifically designed to always refer to string literals to avoid any
1530   // lifetime or initialization issues.
1531   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1532   static const char *const AArch64Triples[] = {
1533       "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1534       "aarch64-redhat-linux"};
1535   static const char *const AArch64beLibDirs[] = {"/lib"};
1536   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1537                                                  "aarch64_be-linux-gnu"};
1538
1539   static const char *const ARMLibDirs[] = {"/lib"};
1540   static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1541                                            "arm-linux-androideabi"};
1542   static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1543                                              "armv7hl-redhat-linux-gnueabi"};
1544   static const char *const ARMebLibDirs[] = {"/lib"};
1545   static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1546                                              "armeb-linux-androideabi"};
1547   static const char *const ARMebHFTriples[] = {
1548       "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1549
1550   static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1551   static const char *const X86_64Triples[] = {
1552       "x86_64-linux-gnu",       "x86_64-unknown-linux-gnu",
1553       "x86_64-pc-linux-gnu",    "x86_64-redhat-linux6E",
1554       "x86_64-redhat-linux",    "x86_64-suse-linux",
1555       "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1556       "x86_64-slackware-linux", "x86_64-linux-android",
1557       "x86_64-unknown-linux"};
1558   static const char *const X32LibDirs[] = {"/libx32"};
1559   static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1560   static const char *const X86Triples[] = {
1561       "i686-linux-gnu",       "i686-pc-linux-gnu",     "i486-linux-gnu",
1562       "i386-linux-gnu",       "i386-redhat-linux6E",   "i686-redhat-linux",
1563       "i586-redhat-linux",    "i386-redhat-linux",     "i586-suse-linux",
1564       "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1565       "i586-linux-gnu"};
1566
1567   static const char *const MIPSLibDirs[] = {"/lib"};
1568   static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1569                                             "mips-mti-linux-gnu",
1570                                             "mips-img-linux-gnu"};
1571   static const char *const MIPSELLibDirs[] = {"/lib"};
1572   static const char *const MIPSELTriples[] = {"mipsel-linux-gnu",
1573                                               "mips-img-linux-gnu"};
1574
1575   static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1576   static const char *const MIPS64Triples[] = {
1577       "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1578       "mips64-linux-gnuabi64"};
1579   static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1580   static const char *const MIPS64ELTriples[] = {
1581       "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1582       "mips64el-linux-gnuabi64"};
1583
1584   static const char *const MIPSELAndroidLibDirs[] = {"/lib", "/libr2",
1585                                                      "/libr6"};
1586   static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
1587   static const char *const MIPS64ELAndroidLibDirs[] = {"/lib64", "/lib",
1588                                                        "/libr2", "/libr6"};
1589   static const char *const MIPS64ELAndroidTriples[] = {
1590       "mips64el-linux-android"};
1591
1592   static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1593   static const char *const PPCTriples[] = {
1594       "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1595       "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1596   static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1597   static const char *const PPC64Triples[] = {
1598       "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1599       "powerpc64-suse-linux", "ppc64-redhat-linux"};
1600   static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1601   static const char *const PPC64LETriples[] = {
1602       "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1603       "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1604
1605   static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1606   static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1607                                                "sparcv8-linux-gnu"};
1608   static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1609   static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1610                                                "sparcv9-linux-gnu"};
1611
1612   static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1613   static const char *const SystemZTriples[] = {
1614       "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1615       "s390x-suse-linux", "s390x-redhat-linux"};
1616
1617   // Solaris.
1618   static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
1619   static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
1620                                                     "i386-pc-solaris2.11"};
1621
1622   using std::begin;
1623   using std::end;
1624
1625   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1626     LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
1627     TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
1628     return;
1629   }
1630
1631   switch (TargetTriple.getArch()) {
1632   case llvm::Triple::aarch64:
1633     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1634     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1635     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1636     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1637     break;
1638   case llvm::Triple::aarch64_be:
1639     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1640     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1641     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1642     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1643     break;
1644   case llvm::Triple::arm:
1645   case llvm::Triple::thumb:
1646     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1647     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1648       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1649     } else {
1650       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1651     }
1652     break;
1653   case llvm::Triple::armeb:
1654   case llvm::Triple::thumbeb:
1655     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1656     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1657       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1658     } else {
1659       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1660     }
1661     break;
1662   case llvm::Triple::x86_64:
1663     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1664     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1665     // x32 is always available when x86_64 is available, so adding it as
1666     // secondary arch with x86_64 triples
1667     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1668       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1669       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1670     } else {
1671       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1672       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1673     }
1674     break;
1675   case llvm::Triple::x86:
1676     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1677     // MCU toolchain is 32 bit only and its triple alias is TargetTriple
1678     // itself, which will be appended below.
1679     if (!TargetTriple.isOSIAMCU()) {
1680       TripleAliases.append(begin(X86Triples), end(X86Triples));
1681       BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1682       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1683     }
1684     break;
1685   case llvm::Triple::mips:
1686     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1687     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1688     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1689     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1690     break;
1691   case llvm::Triple::mipsel:
1692     if (TargetTriple.isAndroid()) {
1693       LibDirs.append(begin(MIPSELAndroidLibDirs), end(MIPSELAndroidLibDirs));
1694       TripleAliases.append(begin(MIPSELAndroidTriples),
1695                            end(MIPSELAndroidTriples));
1696       BiarchLibDirs.append(begin(MIPS64ELAndroidLibDirs),
1697                            end(MIPS64ELAndroidLibDirs));
1698       BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
1699                                  end(MIPS64ELAndroidTriples));
1700
1701     } else {
1702       LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1703       TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1704       TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1705       BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1706       BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1707     }
1708     break;
1709   case llvm::Triple::mips64:
1710     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1711     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1712     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1713     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1714     break;
1715   case llvm::Triple::mips64el:
1716     if (TargetTriple.isAndroid()) {
1717       LibDirs.append(begin(MIPS64ELAndroidLibDirs),
1718                      end(MIPS64ELAndroidLibDirs));
1719       TripleAliases.append(begin(MIPS64ELAndroidTriples),
1720                            end(MIPS64ELAndroidTriples));
1721       BiarchLibDirs.append(begin(MIPSELAndroidLibDirs),
1722                            end(MIPSELAndroidLibDirs));
1723       BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
1724                                  end(MIPSELAndroidTriples));
1725
1726     } else {
1727       LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1728       TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1729       BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1730       BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1731       BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1732     }
1733     break;
1734   case llvm::Triple::ppc:
1735     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1736     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1737     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1738     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1739     break;
1740   case llvm::Triple::ppc64:
1741     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1742     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1743     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1744     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1745     break;
1746   case llvm::Triple::ppc64le:
1747     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1748     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1749     break;
1750   case llvm::Triple::sparc:
1751   case llvm::Triple::sparcel:
1752     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1753     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1754     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1755     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1756     break;
1757   case llvm::Triple::sparcv9:
1758     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1759     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1760     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1761     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1762     break;
1763   case llvm::Triple::systemz:
1764     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1765     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1766     break;
1767   default:
1768     // By default, just rely on the standard lib directories and the original
1769     // triple.
1770     break;
1771   }
1772
1773   // Always append the drivers target triple to the end, in case it doesn't
1774   // match any of our aliases.
1775   TripleAliases.push_back(TargetTriple.str());
1776
1777   // Also include the multiarch variant if it's different.
1778   if (TargetTriple.str() != BiarchTriple.str())
1779     BiarchTripleAliases.push_back(BiarchTriple.str());
1780 }
1781
1782 // Parses the contents of version.txt in an CUDA installation.  It should
1783 // contain one line of the from e.g. "CUDA Version 7.5.2".
1784 static CudaVersion ParseCudaVersionFile(llvm::StringRef V) {
1785   if (!V.startswith("CUDA Version "))
1786     return CudaVersion::UNKNOWN;
1787   V = V.substr(strlen("CUDA Version "));
1788   int Major = -1, Minor = -1;
1789   auto First = V.split('.');
1790   auto Second = First.second.split('.');
1791   if (First.first.getAsInteger(10, Major) ||
1792       Second.first.getAsInteger(10, Minor))
1793     return CudaVersion::UNKNOWN;
1794
1795   if (Major == 7 && Minor == 0) {
1796     // This doesn't appear to ever happen -- version.txt doesn't exist in the
1797     // CUDA 7 installs I've seen.  But no harm in checking.
1798     return CudaVersion::CUDA_70;
1799   }
1800   if (Major == 7 && Minor == 5)
1801     return CudaVersion::CUDA_75;
1802   if (Major == 8 && Minor == 0)
1803     return CudaVersion::CUDA_80;
1804   return CudaVersion::UNKNOWN;
1805 }
1806
1807 CudaInstallationDetector::CudaInstallationDetector(
1808     const Driver &D, const llvm::Triple &HostTriple,
1809     const llvm::opt::ArgList &Args)
1810     : D(D) {
1811   SmallVector<std::string, 4> CudaPathCandidates;
1812
1813   // In decreasing order so we prefer newer versions to older versions.
1814   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
1815
1816   if (Args.hasArg(options::OPT_cuda_path_EQ)) {
1817     CudaPathCandidates.push_back(
1818         Args.getLastArgValue(options::OPT_cuda_path_EQ));
1819   } else if (HostTriple.isOSWindows()) {
1820     for (const char *Ver : Versions)
1821       CudaPathCandidates.push_back(
1822           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
1823           Ver);
1824   } else {
1825     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1826     for (const char *Ver : Versions)
1827       CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-" + Ver);
1828   }
1829
1830   for (const auto &CudaPath : CudaPathCandidates) {
1831     if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1832       continue;
1833
1834     InstallPath = CudaPath;
1835     BinPath = CudaPath + "/bin";
1836     IncludePath = InstallPath + "/include";
1837     LibDevicePath = InstallPath + "/nvvm/libdevice";
1838
1839     auto &FS = D.getVFS();
1840     if (!(FS.exists(IncludePath) && FS.exists(BinPath) &&
1841           FS.exists(LibDevicePath)))
1842       continue;
1843
1844     // On Linux, we have both lib and lib64 directories, and we need to choose
1845     // based on our triple.  On MacOS, we have only a lib directory.
1846     //
1847     // It's sufficient for our purposes to be flexible: If both lib and lib64
1848     // exist, we choose whichever one matches our triple.  Otherwise, if only
1849     // lib exists, we use it.
1850     if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
1851       LibPath = InstallPath + "/lib64";
1852     else if (FS.exists(InstallPath + "/lib"))
1853       LibPath = InstallPath + "/lib";
1854     else
1855       continue;
1856
1857     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
1858         FS.getBufferForFile(InstallPath + "/version.txt");
1859     if (!VersionFile) {
1860       // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
1861       // version.txt isn't present.
1862       Version = CudaVersion::CUDA_70;
1863     } else {
1864       Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
1865     }
1866
1867     std::error_code EC;
1868     for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
1869          !EC && LI != LE; LI = LI.increment(EC)) {
1870       StringRef FilePath = LI->path();
1871       StringRef FileName = llvm::sys::path::filename(FilePath);
1872       // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1873       const StringRef LibDeviceName = "libdevice.";
1874       if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1875         continue;
1876       StringRef GpuArch = FileName.slice(
1877           LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1878       LibDeviceMap[GpuArch] = FilePath.str();
1879       // Insert map entries for specifc devices with this compute
1880       // capability. NVCC's choice of the libdevice library version is
1881       // rather peculiar and depends on the CUDA version.
1882       if (GpuArch == "compute_20") {
1883         LibDeviceMap["sm_20"] = FilePath;
1884         LibDeviceMap["sm_21"] = FilePath;
1885         LibDeviceMap["sm_32"] = FilePath;
1886       } else if (GpuArch == "compute_30") {
1887         LibDeviceMap["sm_30"] = FilePath;
1888         if (Version < CudaVersion::CUDA_80) {
1889           LibDeviceMap["sm_50"] = FilePath;
1890           LibDeviceMap["sm_52"] = FilePath;
1891           LibDeviceMap["sm_53"] = FilePath;
1892         }
1893         LibDeviceMap["sm_60"] = FilePath;
1894         LibDeviceMap["sm_61"] = FilePath;
1895         LibDeviceMap["sm_62"] = FilePath;
1896       } else if (GpuArch == "compute_35") {
1897         LibDeviceMap["sm_35"] = FilePath;
1898         LibDeviceMap["sm_37"] = FilePath;
1899       } else if (GpuArch == "compute_50") {
1900         if (Version >= CudaVersion::CUDA_80) {
1901           LibDeviceMap["sm_50"] = FilePath;
1902           LibDeviceMap["sm_52"] = FilePath;
1903           LibDeviceMap["sm_53"] = FilePath;
1904         }
1905       }
1906     }
1907
1908     IsValid = true;
1909     break;
1910   }
1911 }
1912
1913 void CudaInstallationDetector::AddCudaIncludeArgs(
1914     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
1915   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1916     // Add cuda_wrappers/* to our system include path.  This lets us wrap
1917     // standard library headers.
1918     SmallString<128> P(D.ResourceDir);
1919     llvm::sys::path::append(P, "include");
1920     llvm::sys::path::append(P, "cuda_wrappers");
1921     CC1Args.push_back("-internal-isystem");
1922     CC1Args.push_back(DriverArgs.MakeArgString(P));
1923   }
1924
1925   if (DriverArgs.hasArg(options::OPT_nocudainc))
1926     return;
1927
1928   if (!isValid()) {
1929     D.Diag(diag::err_drv_no_cuda_installation);
1930     return;
1931   }
1932
1933   CC1Args.push_back("-internal-isystem");
1934   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
1935   CC1Args.push_back("-include");
1936   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
1937 }
1938
1939 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
1940     CudaArch Arch) const {
1941   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
1942       ArchsWithVersionTooLowErrors.count(Arch) > 0)
1943     return;
1944
1945   auto RequiredVersion = MinVersionForCudaArch(Arch);
1946   if (Version < RequiredVersion) {
1947     ArchsWithVersionTooLowErrors.insert(Arch);
1948     D.Diag(diag::err_drv_cuda_version_too_low)
1949         << InstallPath << CudaArchToString(Arch) << CudaVersionToString(Version)
1950         << CudaVersionToString(RequiredVersion);
1951   }
1952 }
1953
1954 void CudaInstallationDetector::print(raw_ostream &OS) const {
1955   if (isValid())
1956     OS << "Found CUDA installation: " << InstallPath << ", version "
1957        << CudaVersionToString(Version) << "\n";
1958 }
1959
1960 namespace {
1961 // Filter to remove Multilibs that don't exist as a suffix to Path
1962 class FilterNonExistent {
1963   StringRef Base, File;
1964   vfs::FileSystem &VFS;
1965
1966 public:
1967   FilterNonExistent(StringRef Base, StringRef File, vfs::FileSystem &VFS)
1968       : Base(Base), File(File), VFS(VFS) {}
1969   bool operator()(const Multilib &M) {
1970     return !VFS.exists(Base + M.gccSuffix() + File);
1971   }
1972 };
1973 } // end anonymous namespace
1974
1975 static void addMultilibFlag(bool Enabled, const char *const Flag,
1976                             std::vector<std::string> &Flags) {
1977   if (Enabled)
1978     Flags.push_back(std::string("+") + Flag);
1979   else
1980     Flags.push_back(std::string("-") + Flag);
1981 }
1982
1983 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1984   return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1985 }
1986
1987 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1988   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1989          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1990 }
1991
1992 static bool isMips32(llvm::Triple::ArchType Arch) {
1993   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1994 }
1995
1996 static bool isMips64(llvm::Triple::ArchType Arch) {
1997   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1998 }
1999
2000 static bool isMipsEL(llvm::Triple::ArchType Arch) {
2001   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
2002 }
2003
2004 static bool isMips16(const ArgList &Args) {
2005   Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
2006   return A && A->getOption().matches(options::OPT_mips16);
2007 }
2008
2009 static bool isMicroMips(const ArgList &Args) {
2010   Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
2011   return A && A->getOption().matches(options::OPT_mmicromips);
2012 }
2013
2014 namespace {
2015 struct DetectedMultilibs {
2016   /// The set of multilibs that the detected installation supports.
2017   MultilibSet Multilibs;
2018
2019   /// The primary multilib appropriate for the given flags.
2020   Multilib SelectedMultilib;
2021
2022   /// On Biarch systems, this corresponds to the default multilib when
2023   /// targeting the non-default multilib. Otherwise, it is empty.
2024   llvm::Optional<Multilib> BiarchSibling;
2025 };
2026 } // end anonymous namespace
2027
2028 static Multilib makeMultilib(StringRef commonSuffix) {
2029   return Multilib(commonSuffix, commonSuffix, commonSuffix);
2030 }
2031
2032 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
2033                                 FilterNonExistent &NonExistent,
2034                                 DetectedMultilibs &Result) {
2035   // Check for Code Sourcery toolchain multilibs
2036   MultilibSet CSMipsMultilibs;
2037   {
2038     auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
2039
2040     auto MArchMicroMips =
2041         makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
2042
2043     auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
2044
2045     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2046
2047     auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
2048
2049     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2050
2051     auto DefaultFloat =
2052         makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
2053
2054     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2055
2056     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2057
2058     // Note that this one's osSuffix is ""
2059     auto MAbi64 = makeMultilib("")
2060                       .gccSuffix("/64")
2061                       .includeSuffix("/64")
2062                       .flag("+mabi=n64")
2063                       .flag("-mabi=n32")
2064                       .flag("-m32");
2065
2066     CSMipsMultilibs =
2067         MultilibSet()
2068             .Either(MArchMips16, MArchMicroMips, MArchDefault)
2069             .Maybe(UCLibc)
2070             .Either(SoftFloat, Nan2008, DefaultFloat)
2071             .FilterOut("/micromips/nan2008")
2072             .FilterOut("/mips16/nan2008")
2073             .Either(BigEndian, LittleEndian)
2074             .Maybe(MAbi64)
2075             .FilterOut("/mips16.*/64")
2076             .FilterOut("/micromips.*/64")
2077             .FilterOut(NonExistent)
2078             .setIncludeDirsCallback([](const Multilib &M) {
2079               std::vector<std::string> Dirs({"/include"});
2080               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2081                 Dirs.push_back(
2082                     "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
2083               else
2084                 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
2085               return Dirs;
2086             });
2087   }
2088
2089   MultilibSet DebianMipsMultilibs;
2090   {
2091     Multilib MAbiN32 =
2092         Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
2093
2094     Multilib M64 = Multilib()
2095                        .gccSuffix("/64")
2096                        .includeSuffix("/64")
2097                        .flag("+m64")
2098                        .flag("-m32")
2099                        .flag("-mabi=n32");
2100
2101     Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
2102
2103     DebianMipsMultilibs =
2104         MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
2105   }
2106
2107   // Sort candidates. Toolchain that best meets the directories tree goes first.
2108   // Then select the first toolchains matches command line flags.
2109   MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
2110   if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
2111     std::iter_swap(Candidates, Candidates + 1);
2112   for (const MultilibSet *Candidate : Candidates) {
2113     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2114       if (Candidate == &DebianMipsMultilibs)
2115         Result.BiarchSibling = Multilib();
2116       Result.Multilibs = *Candidate;
2117       return true;
2118     }
2119   }
2120   return false;
2121 }
2122
2123 static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path,
2124                                      const Multilib::flags_list &Flags,
2125                                      FilterNonExistent &NonExistent,
2126                                      DetectedMultilibs &Result) {
2127
2128   MultilibSet AndroidMipsMultilibs =
2129       MultilibSet()
2130           .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
2131           .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
2132           .FilterOut(NonExistent);
2133
2134   MultilibSet AndroidMipselMultilibs =
2135       MultilibSet()
2136           .Either(Multilib().flag("+march=mips32"),
2137                   Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2138                   Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2139           .FilterOut(NonExistent);
2140
2141   MultilibSet AndroidMips64elMultilibs =
2142       MultilibSet()
2143           .Either(
2144               Multilib().flag("+march=mips64r6"),
2145               Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
2146               Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2147               Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2148           .FilterOut(NonExistent);
2149
2150   MultilibSet *MS = &AndroidMipsMultilibs;
2151   if (VFS.exists(Path + "/mips-r6"))
2152     MS = &AndroidMipselMultilibs;
2153   else if (VFS.exists(Path + "/32"))
2154     MS = &AndroidMips64elMultilibs;
2155   if (MS->select(Flags, Result.SelectedMultilib)) {
2156     Result.Multilibs = *MS;
2157     return true;
2158   }
2159   return false;
2160 }
2161
2162 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
2163                                   FilterNonExistent &NonExistent,
2164                                   DetectedMultilibs &Result) {
2165   // Musl toolchain multilibs
2166   MultilibSet MuslMipsMultilibs;
2167   {
2168     auto MArchMipsR2 = makeMultilib("")
2169                            .osSuffix("/mips-r2-hard-musl")
2170                            .flag("+EB")
2171                            .flag("-EL")
2172                            .flag("+march=mips32r2");
2173
2174     auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
2175                              .flag("-EB")
2176                              .flag("+EL")
2177                              .flag("+march=mips32r2");
2178
2179     MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
2180
2181     // Specify the callback that computes the include directories.
2182     MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
2183       return std::vector<std::string>(
2184           {"/../sysroot" + M.osSuffix() + "/usr/include"});
2185     });
2186   }
2187   if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2188     Result.Multilibs = MuslMipsMultilibs;
2189     return true;
2190   }
2191   return false;
2192 }
2193
2194 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
2195                                  FilterNonExistent &NonExistent,
2196                                  DetectedMultilibs &Result) {
2197   // CodeScape MTI toolchain v1.2 and early.
2198   MultilibSet MtiMipsMultilibsV1;
2199   {
2200     auto MArchMips32 = makeMultilib("/mips32")
2201                            .flag("+m32")
2202                            .flag("-m64")
2203                            .flag("-mmicromips")
2204                            .flag("+march=mips32");
2205
2206     auto MArchMicroMips = makeMultilib("/micromips")
2207                               .flag("+m32")
2208                               .flag("-m64")
2209                               .flag("+mmicromips");
2210
2211     auto MArchMips64r2 = makeMultilib("/mips64r2")
2212                              .flag("-m32")
2213                              .flag("+m64")
2214                              .flag("+march=mips64r2");
2215
2216     auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
2217         "-march=mips64r2");
2218
2219     auto MArchDefault = makeMultilib("")
2220                             .flag("+m32")
2221                             .flag("-m64")
2222                             .flag("-mmicromips")
2223                             .flag("+march=mips32r2");
2224
2225     auto Mips16 = makeMultilib("/mips16").flag("+mips16");
2226
2227     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2228
2229     auto MAbi64 =
2230         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2231
2232     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2233
2234     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2235
2236     auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
2237
2238     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2239
2240     MtiMipsMultilibsV1 =
2241         MultilibSet()
2242             .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
2243                     MArchDefault)
2244             .Maybe(UCLibc)
2245             .Maybe(Mips16)
2246             .FilterOut("/mips64/mips16")
2247             .FilterOut("/mips64r2/mips16")
2248             .FilterOut("/micromips/mips16")
2249             .Maybe(MAbi64)
2250             .FilterOut("/micromips/64")
2251             .FilterOut("/mips32/64")
2252             .FilterOut("^/64")
2253             .FilterOut("/mips16/64")
2254             .Either(BigEndian, LittleEndian)
2255             .Maybe(SoftFloat)
2256             .Maybe(Nan2008)
2257             .FilterOut(".*sof/nan2008")
2258             .FilterOut(NonExistent)
2259             .setIncludeDirsCallback([](const Multilib &M) {
2260               std::vector<std::string> Dirs({"/include"});
2261               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2262                 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
2263               else
2264                 Dirs.push_back("/../../../../sysroot/usr/include");
2265               return Dirs;
2266             });
2267   }
2268
2269   // CodeScape IMG toolchain starting from v1.3.
2270   MultilibSet MtiMipsMultilibsV2;
2271   {
2272     auto BeHard = makeMultilib("/mips-r2-hard")
2273                       .flag("+EB")
2274                       .flag("-msoft-float")
2275                       .flag("-mnan=2008")
2276                       .flag("-muclibc");
2277     auto BeSoft = makeMultilib("/mips-r2-soft")
2278                       .flag("+EB")
2279                       .flag("+msoft-float")
2280                       .flag("-mnan=2008");
2281     auto ElHard = makeMultilib("/mipsel-r2-hard")
2282                       .flag("+EL")
2283                       .flag("-msoft-float")
2284                       .flag("-mnan=2008")
2285                       .flag("-muclibc");
2286     auto ElSoft = makeMultilib("/mipsel-r2-soft")
2287                       .flag("+EL")
2288                       .flag("+msoft-float")
2289                       .flag("-mnan=2008")
2290                       .flag("-mmicromips");
2291     auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
2292                          .flag("+EB")
2293                          .flag("-msoft-float")
2294                          .flag("+mnan=2008")
2295                          .flag("-muclibc");
2296     auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
2297                          .flag("+EL")
2298                          .flag("-msoft-float")
2299                          .flag("+mnan=2008")
2300                          .flag("-muclibc")
2301                          .flag("-mmicromips");
2302     auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
2303                                .flag("+EB")
2304                                .flag("-msoft-float")
2305                                .flag("+mnan=2008")
2306                                .flag("+muclibc");
2307     auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
2308                                .flag("+EL")
2309                                .flag("-msoft-float")
2310                                .flag("+mnan=2008")
2311                                .flag("+muclibc");
2312     auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
2313                             .flag("+EB")
2314                             .flag("-msoft-float")
2315                             .flag("-mnan=2008")
2316                             .flag("+muclibc");
2317     auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
2318                             .flag("+EL")
2319                             .flag("-msoft-float")
2320                             .flag("-mnan=2008")
2321                             .flag("+muclibc");
2322     auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
2323                               .flag("+EL")
2324                               .flag("-msoft-float")
2325                               .flag("+mnan=2008")
2326                               .flag("+mmicromips");
2327     auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
2328                            .flag("+EL")
2329                            .flag("+msoft-float")
2330                            .flag("-mnan=2008")
2331                            .flag("+mmicromips");
2332
2333     auto O32 =
2334         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2335     auto N32 =
2336         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2337     auto N64 =
2338         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2339
2340     MtiMipsMultilibsV2 =
2341         MultilibSet()
2342             .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
2343                      BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
2344                      ElHardUclibc, ElMicroHardNan, ElMicroSoft})
2345             .Either(O32, N32, N64)
2346             .FilterOut(NonExistent)
2347             .setIncludeDirsCallback([](const Multilib &M) {
2348               return std::vector<std::string>({"/../../../../sysroot" +
2349                                                M.includeSuffix() +
2350                                                "/../usr/include"});
2351             })
2352             .setFilePathsCallback([](const Multilib &M) {
2353               return std::vector<std::string>(
2354                   {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
2355             });
2356   }
2357   for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
2358     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2359       Result.Multilibs = *Candidate;
2360       return true;
2361     }
2362   }
2363   return false;
2364 }
2365
2366 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
2367                                  FilterNonExistent &NonExistent,
2368                                  DetectedMultilibs &Result) {
2369   // CodeScape IMG toolchain v1.2 and early.
2370   MultilibSet ImgMultilibsV1;
2371   {
2372     auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
2373
2374     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2375
2376     auto MAbi64 =
2377         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2378
2379     ImgMultilibsV1 =
2380         MultilibSet()
2381             .Maybe(Mips64r6)
2382             .Maybe(MAbi64)
2383             .Maybe(LittleEndian)
2384             .FilterOut(NonExistent)
2385             .setIncludeDirsCallback([](const Multilib &M) {
2386               return std::vector<std::string>(
2387                   {"/include", "/../../../../sysroot/usr/include"});
2388             });
2389   }
2390
2391   // CodeScape IMG toolchain starting from v1.3.
2392   MultilibSet ImgMultilibsV2;
2393   {
2394     auto BeHard = makeMultilib("/mips-r6-hard")
2395                       .flag("+EB")
2396                       .flag("-msoft-float")
2397                       .flag("-mmicromips");
2398     auto BeSoft = makeMultilib("/mips-r6-soft")
2399                       .flag("+EB")
2400                       .flag("+msoft-float")
2401                       .flag("-mmicromips");
2402     auto ElHard = makeMultilib("/mipsel-r6-hard")
2403                       .flag("+EL")
2404                       .flag("-msoft-float")
2405                       .flag("-mmicromips");
2406     auto ElSoft = makeMultilib("/mipsel-r6-soft")
2407                       .flag("+EL")
2408                       .flag("+msoft-float")
2409                       .flag("-mmicromips");
2410     auto BeMicroHard = makeMultilib("/micromips-r6-hard")
2411                            .flag("+EB")
2412                            .flag("-msoft-float")
2413                            .flag("+mmicromips");
2414     auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
2415                            .flag("+EB")
2416                            .flag("+msoft-float")
2417                            .flag("+mmicromips");
2418     auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
2419                            .flag("+EL")
2420                            .flag("-msoft-float")
2421                            .flag("+mmicromips");
2422     auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
2423                            .flag("+EL")
2424                            .flag("+msoft-float")
2425                            .flag("+mmicromips");
2426
2427     auto O32 =
2428         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2429     auto N32 =
2430         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2431     auto N64 =
2432         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2433
2434     ImgMultilibsV2 =
2435         MultilibSet()
2436             .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
2437                      ElMicroHard, ElMicroSoft})
2438             .Either(O32, N32, N64)
2439             .FilterOut(NonExistent)
2440             .setIncludeDirsCallback([](const Multilib &M) {
2441               return std::vector<std::string>({"/../../../../sysroot" +
2442                                                M.includeSuffix() +
2443                                                "/../usr/include"});
2444             })
2445             .setFilePathsCallback([](const Multilib &M) {
2446               return std::vector<std::string>(
2447                   {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
2448             });
2449   }
2450   for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
2451     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2452       Result.Multilibs = *Candidate;
2453       return true;
2454     }
2455   }
2456   return false;
2457 }
2458
2459 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
2460                               StringRef Path, const ArgList &Args,
2461                               DetectedMultilibs &Result) {
2462   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2463
2464   StringRef CPUName;
2465   StringRef ABIName;
2466   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2467
2468   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2469
2470   Multilib::flags_list Flags;
2471   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2472   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2473   addMultilibFlag(isMips16(Args), "mips16", Flags);
2474   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2475   addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2476                       CPUName == "mips32r5" || CPUName == "p5600",
2477                   "march=mips32r2", Flags);
2478   addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2479   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2480   addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2481                       CPUName == "mips64r5" || CPUName == "octeon",
2482                   "march=mips64r2", Flags);
2483   addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
2484   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2485   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2486   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2487                   Flags);
2488   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2489   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2490   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2491   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2492   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2493   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2494
2495   if (TargetTriple.isAndroid())
2496     return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
2497                                     Result);
2498
2499   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2500       TargetTriple.getOS() == llvm::Triple::Linux &&
2501       TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2502     return findMipsMuslMultilibs(Flags, NonExistent, Result);
2503
2504   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2505       TargetTriple.getOS() == llvm::Triple::Linux &&
2506       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2507     return findMipsMtiMultilibs(Flags, NonExistent, Result);
2508
2509   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2510       TargetTriple.getOS() == llvm::Triple::Linux &&
2511       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2512     return findMipsImgMultilibs(Flags, NonExistent, Result);
2513
2514   if (findMipsCsMultilibs(Flags, NonExistent, Result))
2515     return true;
2516
2517   // Fallback to the regular toolchain-tree structure.
2518   Multilib Default;
2519   Result.Multilibs.push_back(Default);
2520   Result.Multilibs.FilterOut(NonExistent);
2521
2522   if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2523     Result.BiarchSibling = Multilib();
2524     return true;
2525   }
2526
2527   return false;
2528 }
2529
2530 static void findAndroidArmMultilibs(const Driver &D,
2531                                     const llvm::Triple &TargetTriple,
2532                                     StringRef Path, const ArgList &Args,
2533                                     DetectedMultilibs &Result) {
2534   // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
2535   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2536   Multilib ArmV7Multilib = makeMultilib("/armv7-a")
2537                                .flag("+armv7")
2538                                .flag("-thumb");
2539   Multilib ThumbMultilib = makeMultilib("/thumb")
2540                                .flag("-armv7")
2541                                .flag("+thumb");
2542   Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
2543                                .flag("+armv7")
2544                                .flag("+thumb");
2545   Multilib DefaultMultilib = makeMultilib("")
2546                                .flag("-armv7")
2547                                .flag("-thumb");
2548   MultilibSet AndroidArmMultilibs =
2549       MultilibSet()
2550           .Either(ThumbMultilib, ArmV7Multilib,
2551                   ArmV7ThumbMultilib, DefaultMultilib)
2552           .FilterOut(NonExistent);
2553
2554   Multilib::flags_list Flags;
2555   llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
2556   bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
2557   bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
2558   bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
2559   bool IsThumbMode = IsThumbArch ||
2560       Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
2561       (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::IK_THUMB);
2562   bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
2563       (llvm::ARM::parseArchVersion(Arch) == 7 ||
2564        (IsArmArch && Arch == "" && IsV7SubArch));
2565   addMultilibFlag(IsArmV7Mode, "armv7", Flags);
2566   addMultilibFlag(IsThumbMode, "thumb", Flags);
2567
2568   if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
2569     Result.Multilibs = AndroidArmMultilibs;
2570 }
2571
2572 static bool findBiarchMultilibs(const Driver &D,
2573                                 const llvm::Triple &TargetTriple,
2574                                 StringRef Path, const ArgList &Args,
2575                                 bool NeedsBiarchSuffix,
2576                                 DetectedMultilibs &Result) {
2577   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2578   // in what would normally be GCCInstallPath and put the 64-bit
2579   // libs in a subdirectory named 64. The simple logic we follow is that
2580   // *if* there is a subdirectory of the right name with crtbegin.o in it,
2581   // we use that. If not, and if not a biarch triple alias, we look for
2582   // crtbegin.o without the subdirectory.
2583
2584   Multilib Default;
2585   Multilib Alt64 = Multilib()
2586                        .gccSuffix("/64")
2587                        .includeSuffix("/64")
2588                        .flag("-m32")
2589                        .flag("+m64")
2590                        .flag("-mx32");
2591   Multilib Alt32 = Multilib()
2592                        .gccSuffix("/32")
2593                        .includeSuffix("/32")
2594                        .flag("+m32")
2595                        .flag("-m64")
2596                        .flag("-mx32");
2597   Multilib Altx32 = Multilib()
2598                         .gccSuffix("/x32")
2599                         .includeSuffix("/x32")
2600                         .flag("-m32")
2601                         .flag("-m64")
2602                         .flag("+mx32");
2603
2604   // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2605   FilterNonExistent NonExistent(
2606       Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2607
2608   // Determine default multilib from: 32, 64, x32
2609   // Also handle cases such as 64 on 32, 32 on 64, etc.
2610   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2611   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2612   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2613     Want = WANT64;
2614   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2615     Want = WANT64;
2616   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2617     Want = WANT32;
2618   else {
2619     if (TargetTriple.isArch32Bit())
2620       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2621     else if (IsX32)
2622       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2623     else
2624       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2625   }
2626
2627   if (Want == WANT32)
2628     Default.flag("+m32").flag("-m64").flag("-mx32");
2629   else if (Want == WANT64)
2630     Default.flag("-m32").flag("+m64").flag("-mx32");
2631   else if (Want == WANTX32)
2632     Default.flag("-m32").flag("-m64").flag("+mx32");
2633   else
2634     return false;
2635
2636   Result.Multilibs.push_back(Default);
2637   Result.Multilibs.push_back(Alt64);
2638   Result.Multilibs.push_back(Alt32);
2639   Result.Multilibs.push_back(Altx32);
2640
2641   Result.Multilibs.FilterOut(NonExistent);
2642
2643   Multilib::flags_list Flags;
2644   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2645   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2646   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2647
2648   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2649     return false;
2650
2651   if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2652       Result.SelectedMultilib == Altx32)
2653     Result.BiarchSibling = Default;
2654
2655   return true;
2656 }
2657
2658 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2659     const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2660     const std::string &LibDir, StringRef CandidateTriple,
2661     bool NeedsBiarchSuffix) {
2662   // Solaris is a special case. The GCC installation is under
2663   // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2664   // need to iterate twice.
2665   std::error_code EC;
2666   for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2667        !EC && LI != LE; LI = LI.increment(EC)) {
2668     StringRef VersionText = llvm::sys::path::filename(LI->getName());
2669     GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2670
2671     if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2672       if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2673         continue; // Saw this path before; no need to look at it again.
2674     if (CandidateVersion.isOlderThan(4, 1, 1))
2675       continue;
2676     if (CandidateVersion <= Version)
2677       continue;
2678
2679     GCCInstallPath =
2680         LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2681     if (!D.getVFS().exists(GCCInstallPath))
2682       continue;
2683
2684     // If we make it here there has to be at least one GCC version, let's just
2685     // use the latest one.
2686     std::error_code EEC;
2687     for (vfs::directory_iterator
2688              LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2689              LLE;
2690          !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2691
2692       StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2693       GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2694
2695       if (CandidateSubVersion > Version)
2696         Version = CandidateSubVersion;
2697     }
2698
2699     GCCTriple.setTriple(CandidateTriple);
2700
2701     GCCInstallPath += "/" + Version.Text;
2702     GCCParentLibPath = GCCInstallPath + "/../../../../";
2703
2704     IsValid = true;
2705   }
2706 }
2707
2708 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2709     const llvm::Triple &TargetTriple, const ArgList &Args,
2710     StringRef Path, bool NeedsBiarchSuffix) {
2711   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2712   DetectedMultilibs Detected;
2713
2714   // Android standalone toolchain could have multilibs for ARM and Thumb.
2715   // Debian mips multilibs behave more like the rest of the biarch ones,
2716   // so handle them there
2717   if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2718     // It should also work without multilibs in a simplified toolchain.
2719     findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2720   } else if (isMipsArch(TargetArch)) {
2721     if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2722       return false;
2723   } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2724                                   NeedsBiarchSuffix, Detected)) {
2725     return false;
2726   }
2727
2728   Multilibs = Detected.Multilibs;
2729   SelectedMultilib = Detected.SelectedMultilib;
2730   BiarchSibling = Detected.BiarchSibling;
2731
2732   return true;
2733 }
2734
2735 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2736     const llvm::Triple &TargetTriple, const ArgList &Args,
2737     const std::string &LibDir, StringRef CandidateTriple,
2738     bool NeedsBiarchSuffix) {
2739   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2740   // There are various different suffixes involving the triple we
2741   // check for. We also record what is necessary to walk from each back
2742   // up to the lib directory. Specifically, the number of "up" steps
2743   // in the second half of each row is 1 + the number of path separators
2744   // in the first half.
2745   const std::string LibAndInstallSuffixes[][2] = {
2746       {"/gcc/" + CandidateTriple.str(), "/../../.."},
2747
2748       // Debian puts cross-compilers in gcc-cross
2749       {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2750
2751       {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2752        "/../../../.."},
2753
2754       // The Freescale PPC SDK has the gcc libraries in
2755       // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2756       {"/" + CandidateTriple.str(), "/../.."},
2757
2758       // Ubuntu has a strange mis-matched pair of triples that this happens to
2759       // match.
2760       // FIXME: It may be worthwhile to generalize this and look for a second
2761       // triple.
2762       {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2763
2764   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2765     scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2766                                   NeedsBiarchSuffix);
2767     return;
2768   }
2769
2770   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2771   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2772                                    (TargetArch != llvm::Triple::x86));
2773   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2774     StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2775     std::error_code EC;
2776     for (vfs::directory_iterator
2777              LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2778              LE;
2779          !EC && LI != LE; LI = LI.increment(EC)) {
2780       StringRef VersionText = llvm::sys::path::filename(LI->getName());
2781       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2782       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2783         if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2784           continue; // Saw this path before; no need to look at it again.
2785       if (CandidateVersion.isOlderThan(4, 1, 1))
2786         continue;
2787       if (CandidateVersion <= Version)
2788         continue;
2789
2790       if (!ScanGCCForMultilibs(TargetTriple, Args, LI->getName(),
2791                                NeedsBiarchSuffix))
2792         continue;
2793
2794       Version = CandidateVersion;
2795       GCCTriple.setTriple(CandidateTriple);
2796       // FIXME: We hack together the directory name here instead of
2797       // using LI to ensure stable path separators across Windows and
2798       // Linux.
2799       GCCInstallPath =
2800           LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2801       GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2802       IsValid = true;
2803     }
2804   }
2805 }
2806
2807 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2808     const llvm::Triple &TargetTriple, const ArgList &Args,
2809     StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2810   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2811       D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2812                                   CandidateTriple.str());
2813   if (File) {
2814     SmallVector<StringRef, 2> Lines;
2815     File.get()->getBuffer().split(Lines, "\n");
2816     for (StringRef Line : Lines) {
2817       // CURRENT=triple-version
2818       if (Line.consume_front("CURRENT=")) {
2819         const std::pair<StringRef, StringRef> ActiveVersion =
2820           Line.rsplit('-');
2821         // Note: Strictly speaking, we should be reading
2822         // /etc/env.d/gcc/${CURRENT} now. However, the file doesn't
2823         // contain anything new or especially useful to us.
2824         const std::string GentooPath = D.SysRoot + "/usr/lib/gcc/" +
2825                                        ActiveVersion.first.str() + "/" +
2826                                        ActiveVersion.second.str();
2827         if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2828           if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2829                                    NeedsBiarchSuffix))
2830             return false;
2831
2832           Version = GCCVersion::Parse(ActiveVersion.second);
2833           GCCInstallPath = GentooPath;
2834           GCCParentLibPath = GentooPath + "/../../..";
2835           GCCTriple.setTriple(ActiveVersion.first);
2836           IsValid = true;
2837           return true;
2838         }
2839       }
2840     }
2841   }
2842
2843   return false;
2844 }
2845
2846 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2847                          const ArgList &Args)
2848     : ToolChain(D, Triple, Args), GCCInstallation(D),
2849       CudaInstallation(D, Triple, Args) {
2850   getProgramPaths().push_back(getDriver().getInstalledDir());
2851   if (getDriver().getInstalledDir() != getDriver().Dir)
2852     getProgramPaths().push_back(getDriver().Dir);
2853 }
2854
2855 Generic_GCC::~Generic_GCC() {}
2856
2857 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2858   switch (AC) {
2859   case Action::PreprocessJobClass:
2860     if (!Preprocess)
2861       Preprocess.reset(new tools::gcc::Preprocessor(*this));
2862     return Preprocess.get();
2863   case Action::CompileJobClass:
2864     if (!Compile)
2865       Compile.reset(new tools::gcc::Compiler(*this));
2866     return Compile.get();
2867   default:
2868     return ToolChain::getTool(AC);
2869   }
2870 }
2871
2872 Tool *Generic_GCC::buildAssembler() const {
2873   return new tools::gnutools::Assembler(*this);
2874 }
2875
2876 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2877
2878 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2879   // Print the information about how we detected the GCC installation.
2880   GCCInstallation.print(OS);
2881   CudaInstallation.print(OS);
2882 }
2883
2884 bool Generic_GCC::IsUnwindTablesDefault() const {
2885   return getArch() == llvm::Triple::x86_64;
2886 }
2887
2888 bool Generic_GCC::isPICDefault() const {
2889   switch (getArch()) {
2890   case llvm::Triple::x86_64:
2891     return getTriple().isOSWindows();
2892   case llvm::Triple::ppc64:
2893   case llvm::Triple::ppc64le:
2894     return !getTriple().isOSBinFormatMachO() && !getTriple().isMacOSX();
2895   default:
2896     return false;
2897   }
2898 }
2899
2900 bool Generic_GCC::isPIEDefault() const { return false; }
2901
2902 bool Generic_GCC::isPICDefaultForced() const {
2903   return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2904 }
2905
2906 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2907   switch (getTriple().getArch()) {
2908   case llvm::Triple::x86:
2909   case llvm::Triple::x86_64:
2910   case llvm::Triple::aarch64:
2911   case llvm::Triple::aarch64_be:
2912   case llvm::Triple::arm:
2913   case llvm::Triple::armeb:
2914   case llvm::Triple::bpfel:
2915   case llvm::Triple::bpfeb:
2916   case llvm::Triple::thumb:
2917   case llvm::Triple::thumbeb:
2918   case llvm::Triple::ppc:
2919   case llvm::Triple::ppc64:
2920   case llvm::Triple::ppc64le:
2921   case llvm::Triple::systemz:
2922   case llvm::Triple::mips:
2923   case llvm::Triple::mipsel:
2924     return true;
2925   case llvm::Triple::mips64:
2926   case llvm::Triple::mips64el:
2927     // Enabled for Debian mips64/mips64el only. Other targets are unable to
2928     // distinguish N32 from N64.
2929     if (getTriple().getEnvironment() == llvm::Triple::GNUABI64)
2930       return true;
2931     return false;
2932   default:
2933     return false;
2934   }
2935 }
2936
2937 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2938                                                ArgStringList &CC1Args) const {
2939   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2940       DriverArgs.hasArg(options::OPT_nostdincxx))
2941     return;
2942
2943   switch (GetCXXStdlibType(DriverArgs)) {
2944   case ToolChain::CST_Libcxx: {
2945     std::string Path = findLibCxxIncludePath();
2946     if (!Path.empty())
2947       addSystemInclude(DriverArgs, CC1Args, Path);
2948     break;
2949   }
2950
2951   case ToolChain::CST_Libstdcxx:
2952     addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2953     break;
2954   }
2955 }
2956
2957 std::string Generic_GCC::findLibCxxIncludePath() const {
2958   // FIXME: The Linux behavior would probaby be a better approach here.
2959   return getDriver().SysRoot + "/usr/include/c++/v1";
2960 }
2961
2962 void
2963 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2964                                       llvm::opt::ArgStringList &CC1Args) const {
2965   // By default, we don't assume we know where libstdc++ might be installed.
2966   // FIXME: If we have a valid GCCInstallation, use it.
2967 }
2968
2969 /// \brief Helper to add the variant paths of a libstdc++ installation.
2970 bool Generic_GCC::addLibStdCXXIncludePaths(
2971     Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2972     StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2973     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2974   if (!getVFS().exists(Base + Suffix))
2975     return false;
2976
2977   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2978
2979   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2980   // that path exists or we have neither a GCC nor target multiarch triple, use
2981   // this vanilla search path.
2982   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2983       getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2984     addSystemInclude(DriverArgs, CC1Args,
2985                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2986   } else {
2987     // Otherwise try to use multiarch naming schemes which have normalized the
2988     // triples and put the triple before the suffix.
2989     //
2990     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2991     // the target triple, so we support that here.
2992     addSystemInclude(DriverArgs, CC1Args,
2993                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2994     addSystemInclude(DriverArgs, CC1Args,
2995                      Base + "/" + TargetMultiarchTriple + Suffix);
2996   }
2997
2998   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2999   return true;
3000 }
3001
3002 llvm::opt::DerivedArgList *
3003 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3004                            Action::OffloadKind DeviceOffloadKind) const {
3005
3006   // If this tool chain is used for an OpenMP offloading device we have to make
3007   // sure we always generate a shared library regardless of the commands the
3008   // user passed to the host. This is required because the runtime library
3009   // is required to load the device image dynamically at run time.
3010   if (DeviceOffloadKind == Action::OFK_OpenMP) {
3011     DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3012     const OptTable &Opts = getDriver().getOpts();
3013
3014     // Request the shared library. Given that these options are decided
3015     // implicitly, they do not refer to any base argument.
3016     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3017     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3018
3019     // Filter all the arguments we don't care passing to the offloading
3020     // toolchain as they can mess up with the creation of a shared library.
3021     for (auto *A : Args) {
3022       switch ((options::ID)A->getOption().getID()) {
3023       default:
3024         DAL->append(A);
3025         break;
3026       case options::OPT_shared:
3027       case options::OPT_dynamic:
3028       case options::OPT_static:
3029       case options::OPT_fPIC:
3030       case options::OPT_fno_PIC:
3031       case options::OPT_fpic:
3032       case options::OPT_fno_pic:
3033       case options::OPT_fPIE:
3034       case options::OPT_fno_PIE:
3035       case options::OPT_fpie:
3036       case options::OPT_fno_pie:
3037         break;
3038       }
3039     }
3040     return DAL;
3041   }
3042   return nullptr;
3043 }
3044
3045 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3046                                         ArgStringList &CC1Args) const {
3047   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
3048   bool UseInitArrayDefault =
3049       getTriple().getArch() == llvm::Triple::aarch64 ||
3050       getTriple().getArch() == llvm::Triple::aarch64_be ||
3051       (getTriple().getOS() == llvm::Triple::Linux &&
3052        (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
3053       getTriple().getOS() == llvm::Triple::NaCl ||
3054       (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
3055        !getTriple().hasEnvironment());
3056
3057   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
3058                          options::OPT_fno_use_init_array, UseInitArrayDefault))
3059     CC1Args.push_back("-fuse-init-array");
3060 }
3061
3062 /// Mips Toolchain
3063 MipsLLVMToolChain::MipsLLVMToolChain(const Driver &D,
3064                                      const llvm::Triple &Triple,
3065                                      const ArgList &Args)
3066     : Linux(D, Triple, Args) {
3067   // Select the correct multilib according to the given arguments.
3068   DetectedMultilibs Result;
3069   findMIPSMultilibs(D, Triple, "", Args, Result);
3070   Multilibs = Result.Multilibs;
3071   SelectedMultilib = Result.SelectedMultilib;
3072
3073   // Find out the library suffix based on the ABI.
3074   LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
3075   getFilePaths().clear();
3076   getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
3077 }
3078
3079 void MipsLLVMToolChain::AddClangSystemIncludeArgs(
3080     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
3081   if (DriverArgs.hasArg(options::OPT_nostdinc))
3082     return;
3083
3084   const Driver &D = getDriver();
3085
3086   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3087     SmallString<128> P(D.ResourceDir);
3088     llvm::sys::path::append(P, "include");
3089     addSystemInclude(DriverArgs, CC1Args, P);
3090   }
3091
3092   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3093     return;
3094
3095   const auto &Callback = Multilibs.includeDirsCallback();
3096   if (Callback) {
3097     for (const auto &Path : Callback(SelectedMultilib))
3098       addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3099                                       D.getInstalledDir() + Path);
3100   }
3101 }
3102
3103 Tool *MipsLLVMToolChain::buildLinker() const {
3104   return new tools::gnutools::Linker(*this);
3105 }
3106
3107 std::string MipsLLVMToolChain::computeSysRoot() const {
3108   if (!getDriver().SysRoot.empty())
3109     return getDriver().SysRoot + SelectedMultilib.osSuffix();
3110
3111   const std::string InstalledDir(getDriver().getInstalledDir());
3112   std::string SysRootPath =
3113       InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
3114   if (llvm::sys::fs::exists(SysRootPath))
3115     return SysRootPath;
3116
3117   return std::string();
3118 }
3119
3120 ToolChain::CXXStdlibType
3121 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
3122   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3123   if (A) {
3124     StringRef Value = A->getValue();
3125     if (Value != "libc++")
3126       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
3127           << A->getAsString(Args);
3128   }
3129
3130   return ToolChain::CST_Libcxx;
3131 }
3132
3133 std::string MipsLLVMToolChain::findLibCxxIncludePath() const {
3134   if (const auto &Callback = Multilibs.includeDirsCallback()) {
3135     for (std::string Path : Callback(SelectedMultilib)) {
3136       Path = getDriver().getInstalledDir() + Path + "/c++/v1";
3137       if (llvm::sys::fs::exists(Path)) {
3138         return Path;
3139       }
3140     }
3141   }
3142   return "";
3143 }
3144
3145 void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3146                                             ArgStringList &CmdArgs) const {
3147   assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
3148          "Only -lc++ (aka libxx) is suported in this toolchain.");
3149
3150   CmdArgs.push_back("-lc++");
3151   CmdArgs.push_back("-lc++abi");
3152   CmdArgs.push_back("-lunwind");
3153 }
3154
3155 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
3156                                              StringRef Component,
3157                                              bool Shared) const {
3158   SmallString<128> Path(getDriver().ResourceDir);
3159   llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
3160                           getOS());
3161   llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
3162                                       "mips" + (Shared ? ".so" : ".a")));
3163   return Path.str();
3164 }
3165
3166 /// Hexagon Toolchain
3167
3168 std::string HexagonToolChain::getHexagonTargetDir(
3169       const std::string &InstalledDir,
3170       const SmallVectorImpl<std::string> &PrefixDirs) const {
3171   std::string InstallRelDir;
3172   const Driver &D = getDriver();
3173
3174   // Locate the rest of the toolchain ...
3175   for (auto &I : PrefixDirs)
3176     if (D.getVFS().exists(I))
3177       return I;
3178
3179   if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
3180     return InstallRelDir;
3181
3182   return InstalledDir;
3183 }
3184
3185 Optional<unsigned> HexagonToolChain::getSmallDataThreshold(
3186       const ArgList &Args) {
3187   StringRef Gn = "";
3188   if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
3189                                options::OPT_msmall_data_threshold_EQ)) {
3190     Gn = A->getValue();
3191   } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
3192                              options::OPT_fPIC)) {
3193     Gn = "0";
3194   }
3195
3196   unsigned G;
3197   if (!Gn.getAsInteger(10, G))
3198     return G;
3199
3200   return None;
3201 }
3202
3203 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
3204       ToolChain::path_list &LibPaths) const {
3205   const Driver &D = getDriver();
3206
3207   //----------------------------------------------------------------------------
3208   // -L Args
3209   //----------------------------------------------------------------------------
3210   for (Arg *A : Args.filtered(options::OPT_L))
3211     for (const char *Value : A->getValues())
3212       LibPaths.push_back(Value);
3213
3214   //----------------------------------------------------------------------------
3215   // Other standard paths
3216   //----------------------------------------------------------------------------
3217   std::vector<std::string> RootDirs;
3218   std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
3219             std::back_inserter(RootDirs));
3220
3221   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3222                                               D.PrefixDirs);
3223   if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
3224     RootDirs.push_back(TargetDir);
3225
3226   bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
3227   // Assume G0 with -shared.
3228   bool HasG0 = Args.hasArg(options::OPT_shared);
3229   if (auto G = getSmallDataThreshold(Args))
3230     HasG0 = G.getValue() == 0;
3231
3232   const std::string CpuVer = GetTargetCPUVersion(Args).str();
3233   for (auto &Dir : RootDirs) {
3234     std::string LibDir = Dir + "/hexagon/lib";
3235     std::string LibDirCpu = LibDir + '/' + CpuVer;
3236     if (HasG0) {
3237       if (HasPIC)
3238         LibPaths.push_back(LibDirCpu + "/G0/pic");
3239       LibPaths.push_back(LibDirCpu + "/G0");
3240     }
3241     LibPaths.push_back(LibDirCpu);
3242     LibPaths.push_back(LibDir);
3243   }
3244 }
3245
3246 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
3247                                    const llvm::opt::ArgList &Args)
3248     : Linux(D, Triple, Args) {
3249   const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3250                                                     D.PrefixDirs);
3251
3252   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
3253   // program paths
3254   const std::string BinDir(TargetDir + "/bin");
3255   if (D.getVFS().exists(BinDir))
3256     getProgramPaths().push_back(BinDir);
3257
3258   ToolChain::path_list &LibPaths = getFilePaths();
3259
3260   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
3261   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
3262   // support 'linux' we'll need to fix this up
3263   LibPaths.clear();
3264   getHexagonLibraryPaths(Args, LibPaths);
3265 }
3266
3267 HexagonToolChain::~HexagonToolChain() {}
3268
3269 Tool *HexagonToolChain::buildAssembler() const {
3270   return new tools::hexagon::Assembler(*this);
3271 }
3272
3273 Tool *HexagonToolChain::buildLinker() const {
3274   return new tools::hexagon::Linker(*this);
3275 }
3276
3277 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3278                                                  ArgStringList &CC1Args) const {
3279   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3280       DriverArgs.hasArg(options::OPT_nostdlibinc))
3281     return;
3282
3283   const Driver &D = getDriver();
3284   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3285                                               D.PrefixDirs);
3286   addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
3287 }
3288
3289
3290 void HexagonToolChain::addLibStdCxxIncludePaths(
3291     const llvm::opt::ArgList &DriverArgs,
3292     llvm::opt::ArgStringList &CC1Args) const {
3293   const Driver &D = getDriver();
3294   std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
3295   addLibStdCXXIncludePaths(TargetDir, "/hexagon/include/c++", "", "", "", "",
3296                            DriverArgs, CC1Args);
3297 }
3298
3299 ToolChain::CXXStdlibType
3300 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
3301   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3302   if (!A)
3303     return ToolChain::CST_Libstdcxx;
3304
3305   StringRef Value = A->getValue();
3306   if (Value != "libstdc++")
3307     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3308
3309   return ToolChain::CST_Libstdcxx;
3310 }
3311
3312 //
3313 // Returns the default CPU for Hexagon. This is the default compilation target
3314 // if no Hexagon processor is selected at the command-line.
3315 //
3316 const StringRef HexagonToolChain::GetDefaultCPU() {
3317   return "hexagonv60";
3318 }
3319
3320 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
3321   Arg *CpuArg = nullptr;
3322   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ, options::OPT_march_EQ))
3323     CpuArg = A;
3324
3325   StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
3326   if (CPU.startswith("hexagon"))
3327     return CPU.substr(sizeof("hexagon") - 1);
3328   return CPU;
3329 }
3330 // End Hexagon
3331
3332 /// AMDGPU Toolchain
3333 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
3334                                  const ArgList &Args)
3335   : Generic_ELF(D, Triple, Args) { }
3336
3337 Tool *AMDGPUToolChain::buildLinker() const {
3338   return new tools::amdgpu::Linker(*this);
3339 }
3340 // End AMDGPU
3341
3342 /// NaCl Toolchain
3343 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
3344                              const ArgList &Args)
3345     : Generic_ELF(D, Triple, Args) {
3346
3347   // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
3348   // default paths, and must instead only use the paths provided
3349   // with this toolchain based on architecture.
3350   path_list &file_paths = getFilePaths();
3351   path_list &prog_paths = getProgramPaths();
3352
3353   file_paths.clear();
3354   prog_paths.clear();
3355
3356   // Path for library files (libc.a, ...)
3357   std::string FilePath(getDriver().Dir + "/../");
3358
3359   // Path for tools (clang, ld, etc..)
3360   std::string ProgPath(getDriver().Dir + "/../");
3361
3362   // Path for toolchain libraries (libgcc.a, ...)
3363   std::string ToolPath(getDriver().ResourceDir + "/lib/");
3364
3365   switch (Triple.getArch()) {
3366   case llvm::Triple::x86:
3367     file_paths.push_back(FilePath + "x86_64-nacl/lib32");
3368     file_paths.push_back(FilePath + "i686-nacl/usr/lib");
3369     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3370     file_paths.push_back(ToolPath + "i686-nacl");
3371     break;
3372   case llvm::Triple::x86_64:
3373     file_paths.push_back(FilePath + "x86_64-nacl/lib");
3374     file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
3375     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3376     file_paths.push_back(ToolPath + "x86_64-nacl");
3377     break;
3378   case llvm::Triple::arm:
3379     file_paths.push_back(FilePath + "arm-nacl/lib");
3380     file_paths.push_back(FilePath + "arm-nacl/usr/lib");
3381     prog_paths.push_back(ProgPath + "arm-nacl/bin");
3382     file_paths.push_back(ToolPath + "arm-nacl");
3383     break;
3384   case llvm::Triple::mipsel:
3385     file_paths.push_back(FilePath + "mipsel-nacl/lib");
3386     file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
3387     prog_paths.push_back(ProgPath + "bin");
3388     file_paths.push_back(ToolPath + "mipsel-nacl");
3389     break;
3390   default:
3391     break;
3392   }
3393
3394   NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
3395 }
3396
3397 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3398                                               ArgStringList &CC1Args) const {
3399   const Driver &D = getDriver();
3400   if (DriverArgs.hasArg(options::OPT_nostdinc))
3401     return;
3402
3403   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3404     SmallString<128> P(D.ResourceDir);
3405     llvm::sys::path::append(P, "include");
3406     addSystemInclude(DriverArgs, CC1Args, P.str());
3407   }
3408
3409   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3410     return;
3411
3412   SmallString<128> P(D.Dir + "/../");
3413   switch (getTriple().getArch()) {
3414   case llvm::Triple::x86:
3415     // x86 is special because multilib style uses x86_64-nacl/include for libc
3416     // headers but the SDK wants i686-nacl/usr/include. The other architectures
3417     // have the same substring.
3418     llvm::sys::path::append(P, "i686-nacl/usr/include");
3419     addSystemInclude(DriverArgs, CC1Args, P.str());
3420     llvm::sys::path::remove_filename(P);
3421     llvm::sys::path::remove_filename(P);
3422     llvm::sys::path::remove_filename(P);
3423     llvm::sys::path::append(P, "x86_64-nacl/include");
3424     addSystemInclude(DriverArgs, CC1Args, P.str());
3425     return;
3426   case llvm::Triple::arm:
3427     llvm::sys::path::append(P, "arm-nacl/usr/include");
3428     break;
3429   case llvm::Triple::x86_64:
3430     llvm::sys::path::append(P, "x86_64-nacl/usr/include");
3431     break;
3432   case llvm::Triple::mipsel:
3433     llvm::sys::path::append(P, "mipsel-nacl/usr/include");
3434     break;
3435   default:
3436     return;
3437   }
3438
3439   addSystemInclude(DriverArgs, CC1Args, P.str());
3440   llvm::sys::path::remove_filename(P);
3441   llvm::sys::path::remove_filename(P);
3442   llvm::sys::path::append(P, "include");
3443   addSystemInclude(DriverArgs, CC1Args, P.str());
3444 }
3445
3446 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3447                                         ArgStringList &CmdArgs) const {
3448   // Check for -stdlib= flags. We only support libc++ but this consumes the arg
3449   // if the value is libc++, and emits an error for other values.
3450   GetCXXStdlibType(Args);
3451   CmdArgs.push_back("-lc++");
3452 }
3453
3454 std::string NaClToolChain::findLibCxxIncludePath() const {
3455   const Driver &D = getDriver();
3456
3457   SmallString<128> P(D.Dir + "/../");
3458   switch (getTriple().getArch()) {
3459   case llvm::Triple::arm:
3460     llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
3461     return P.str();
3462   case llvm::Triple::x86:
3463     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3464     return P.str();
3465   case llvm::Triple::x86_64:
3466     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3467     return P.str();
3468   case llvm::Triple::mipsel:
3469     llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
3470     return P.str();
3471   default:
3472     return "";
3473   }
3474 }
3475
3476 ToolChain::CXXStdlibType
3477 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
3478   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3479     StringRef Value = A->getValue();
3480     if (Value == "libc++")
3481       return ToolChain::CST_Libcxx;
3482     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3483   }
3484
3485   return ToolChain::CST_Libcxx;
3486 }
3487
3488 std::string
3489 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
3490                                            types::ID InputType) const {
3491   llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
3492   if (TheTriple.getArch() == llvm::Triple::arm &&
3493       TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
3494     TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
3495   return TheTriple.getTriple();
3496 }
3497
3498 Tool *NaClToolChain::buildLinker() const {
3499   return new tools::nacltools::Linker(*this);
3500 }
3501
3502 Tool *NaClToolChain::buildAssembler() const {
3503   if (getTriple().getArch() == llvm::Triple::arm)
3504     return new tools::nacltools::AssemblerARM(*this);
3505   return new tools::gnutools::Assembler(*this);
3506 }
3507 // End NaCl
3508
3509 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
3510 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
3511 /// Currently does not support anything else but compilation.
3512
3513 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
3514                            const ArgList &Args)
3515     : ToolChain(D, Triple, Args) {
3516   // Path mangling to find libexec
3517   std::string Path(getDriver().Dir);
3518
3519   Path += "/../libexec";
3520   getProgramPaths().push_back(Path);
3521 }
3522
3523 TCEToolChain::~TCEToolChain() {}
3524
3525 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
3526
3527 bool TCEToolChain::isPICDefault() const { return false; }
3528
3529 bool TCEToolChain::isPIEDefault() const { return false; }
3530
3531 bool TCEToolChain::isPICDefaultForced() const { return false; }
3532
3533 TCELEToolChain::TCELEToolChain(const Driver &D, const llvm::Triple& Triple,
3534                                const ArgList &Args)
3535   : TCEToolChain(D, Triple, Args) {
3536 }
3537
3538 TCELEToolChain::~TCELEToolChain() {}
3539
3540 // CloudABI - CloudABI tool chain which can call ld(1) directly.
3541
3542 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
3543                    const ArgList &Args)
3544     : Generic_ELF(D, Triple, Args) {
3545   SmallString<128> P(getDriver().Dir);
3546   llvm::sys::path::append(P, "..", getTriple().str(), "lib");
3547   getFilePaths().push_back(P.str());
3548 }
3549
3550 std::string CloudABI::findLibCxxIncludePath() const {
3551   SmallString<128> P(getDriver().Dir);
3552   llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
3553   return P.str();
3554 }
3555
3556 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
3557                                    ArgStringList &CmdArgs) const {
3558   CmdArgs.push_back("-lc++");
3559   CmdArgs.push_back("-lc++abi");
3560   CmdArgs.push_back("-lunwind");
3561 }
3562
3563 Tool *CloudABI::buildLinker() const {
3564   return new tools::cloudabi::Linker(*this);
3565 }
3566
3567 bool CloudABI::isPIEDefault() const {
3568   // Only enable PIE on architectures that support PC-relative
3569   // addressing. PC-relative addressing is required, as the process
3570   // startup code must be able to relocate itself.
3571   switch (getTriple().getArch()) {
3572   case llvm::Triple::aarch64:
3573   case llvm::Triple::x86_64:
3574     return true;
3575   default:
3576     return false;
3577   }
3578 }
3579
3580 SanitizerMask CloudABI::getSupportedSanitizers() const {
3581   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3582   Res |= SanitizerKind::SafeStack;
3583   return Res;
3584 }
3585
3586 SanitizerMask CloudABI::getDefaultSanitizers() const {
3587   return SanitizerKind::SafeStack;
3588 }
3589
3590 /// Haiku - Haiku tool chain which can call as(1) and ld(1) directly.
3591
3592 Haiku::Haiku(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3593   : Generic_ELF(D, Triple, Args) {
3594
3595 }
3596
3597 std::string Haiku::findLibCxxIncludePath() const {
3598   return getDriver().SysRoot + "/system/develop/headers/c++/v1";
3599 }
3600
3601 void Haiku::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3602                                      llvm::opt::ArgStringList &CC1Args) const {
3603   addLibStdCXXIncludePaths(getDriver().SysRoot, "/system/develop/headers/c++",
3604                            getTriple().str(), "", "", "", DriverArgs, CC1Args);
3605 }
3606
3607 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
3608
3609 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
3610                  const ArgList &Args)
3611     : Generic_ELF(D, Triple, Args) {
3612   getFilePaths().push_back(getDriver().Dir + "/../lib");
3613   getFilePaths().push_back("/usr/lib");
3614 }
3615
3616 Tool *OpenBSD::buildAssembler() const {
3617   return new tools::openbsd::Assembler(*this);
3618 }
3619
3620 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
3621
3622 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
3623
3624 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3625     : Generic_ELF(D, Triple, Args) {
3626   getFilePaths().push_back(getDriver().Dir + "/../lib");
3627   getFilePaths().push_back("/usr/lib");
3628 }
3629
3630 Tool *Bitrig::buildAssembler() const {
3631   return new tools::bitrig::Assembler(*this);
3632 }
3633
3634 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3635
3636 ToolChain::CXXStdlibType Bitrig::GetDefaultCXXStdlibType() const {
3637   return ToolChain::CST_Libcxx;
3638 }
3639
3640 void Bitrig::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3641                                       llvm::opt::ArgStringList &CC1Args) const {
3642   std::string Triple = getTriple().str();
3643   if (StringRef(Triple).startswith("amd64"))
3644     Triple = "x86_64" + Triple.substr(5);
3645   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/stdc++",
3646                            Triple, "", "", "", DriverArgs, CC1Args);
3647 }
3648
3649 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3650                                  ArgStringList &CmdArgs) const {
3651   switch (GetCXXStdlibType(Args)) {
3652   case ToolChain::CST_Libcxx:
3653     CmdArgs.push_back("-lc++");
3654     CmdArgs.push_back("-lc++abi");
3655     CmdArgs.push_back("-lpthread");
3656     break;
3657   case ToolChain::CST_Libstdcxx:
3658     CmdArgs.push_back("-lstdc++");
3659     break;
3660   }
3661 }
3662
3663 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3664
3665 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3666                  const ArgList &Args)
3667     : Generic_ELF(D, Triple, Args) {
3668
3669   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3670   // back to '/usr/lib' if it doesn't exist.
3671   if ((Triple.getArch() == llvm::Triple::x86 ||
3672        Triple.getArch() == llvm::Triple::ppc) &&
3673       D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3674     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3675   else
3676     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3677 }
3678
3679 ToolChain::CXXStdlibType FreeBSD::GetDefaultCXXStdlibType() const {
3680   if (getTriple().getOSMajorVersion() >= 10)
3681     return ToolChain::CST_Libcxx;
3682   return ToolChain::CST_Libstdcxx;
3683 }
3684
3685 void FreeBSD::addLibStdCxxIncludePaths(
3686     const llvm::opt::ArgList &DriverArgs,
3687     llvm::opt::ArgStringList &CC1Args) const {
3688   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/4.2", "", "",
3689                            "", "", DriverArgs, CC1Args);
3690 }
3691
3692 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
3693                                   ArgStringList &CmdArgs) const {
3694   CXXStdlibType Type = GetCXXStdlibType(Args);
3695   bool Profiling = Args.hasArg(options::OPT_pg);
3696
3697   switch (Type) {
3698   case ToolChain::CST_Libcxx:
3699     CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
3700     break;
3701
3702   case ToolChain::CST_Libstdcxx:
3703     CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++");
3704     break;
3705   }
3706 }
3707
3708 Tool *FreeBSD::buildAssembler() const {
3709   return new tools::freebsd::Assembler(*this);
3710 }
3711
3712 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3713
3714 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3715   // FreeBSD uses SjLj exceptions on ARM oabi.
3716   switch (getTriple().getEnvironment()) {
3717   case llvm::Triple::GNUEABIHF:
3718   case llvm::Triple::GNUEABI:
3719   case llvm::Triple::EABI:
3720     return false;
3721
3722   default:
3723     return (getTriple().getArch() == llvm::Triple::arm ||
3724             getTriple().getArch() == llvm::Triple::thumb);
3725   }
3726 }
3727
3728 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3729
3730 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3731
3732 SanitizerMask FreeBSD::getSupportedSanitizers() const {
3733   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3734   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3735   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3736                         getTriple().getArch() == llvm::Triple::mips64el;
3737   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3738   Res |= SanitizerKind::Address;
3739   Res |= SanitizerKind::Vptr;
3740   if (IsX86_64 || IsMIPS64) {
3741     Res |= SanitizerKind::Leak;
3742     Res |= SanitizerKind::Thread;
3743   }
3744   if (IsX86 || IsX86_64) {
3745     Res |= SanitizerKind::SafeStack;
3746   }
3747   return Res;
3748 }
3749
3750 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3751
3752 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3753     : Generic_ELF(D, Triple, Args) {
3754   if (getDriver().UseStdLib) {
3755     // When targeting a 32-bit platform, try the special directory used on
3756     // 64-bit hosts, and only fall back to the main library directory if that
3757     // doesn't work.
3758     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3759     // what all logic is needed to emulate the '=' prefix here.
3760     switch (Triple.getArch()) {
3761     case llvm::Triple::x86:
3762       getFilePaths().push_back("=/usr/lib/i386");
3763       break;
3764     case llvm::Triple::arm:
3765     case llvm::Triple::armeb:
3766     case llvm::Triple::thumb:
3767     case llvm::Triple::thumbeb:
3768       switch (Triple.getEnvironment()) {
3769       case llvm::Triple::EABI:
3770       case llvm::Triple::GNUEABI:
3771         getFilePaths().push_back("=/usr/lib/eabi");
3772         break;
3773       case llvm::Triple::EABIHF:
3774       case llvm::Triple::GNUEABIHF:
3775         getFilePaths().push_back("=/usr/lib/eabihf");
3776         break;
3777       default:
3778         getFilePaths().push_back("=/usr/lib/oabi");
3779         break;
3780       }
3781       break;
3782     case llvm::Triple::mips64:
3783     case llvm::Triple::mips64el:
3784       if (tools::mips::hasMipsAbiArg(Args, "o32"))
3785         getFilePaths().push_back("=/usr/lib/o32");
3786       else if (tools::mips::hasMipsAbiArg(Args, "64"))
3787         getFilePaths().push_back("=/usr/lib/64");
3788       break;
3789     case llvm::Triple::ppc:
3790       getFilePaths().push_back("=/usr/lib/powerpc");
3791       break;
3792     case llvm::Triple::sparc:
3793       getFilePaths().push_back("=/usr/lib/sparc");
3794       break;
3795     default:
3796       break;
3797     }
3798
3799     getFilePaths().push_back("=/usr/lib");
3800   }
3801 }
3802
3803 Tool *NetBSD::buildAssembler() const {
3804   return new tools::netbsd::Assembler(*this);
3805 }
3806
3807 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3808
3809 ToolChain::CXXStdlibType NetBSD::GetDefaultCXXStdlibType() const {
3810   unsigned Major, Minor, Micro;
3811   getTriple().getOSVersion(Major, Minor, Micro);
3812   if (Major >= 7 || Major == 0) {
3813     switch (getArch()) {
3814     case llvm::Triple::aarch64:
3815     case llvm::Triple::arm:
3816     case llvm::Triple::armeb:
3817     case llvm::Triple::thumb:
3818     case llvm::Triple::thumbeb:
3819     case llvm::Triple::ppc:
3820     case llvm::Triple::ppc64:
3821     case llvm::Triple::ppc64le:
3822     case llvm::Triple::sparc:
3823     case llvm::Triple::sparcv9:
3824     case llvm::Triple::x86:
3825     case llvm::Triple::x86_64:
3826       return ToolChain::CST_Libcxx;
3827     default:
3828       break;
3829     }
3830   }
3831   return ToolChain::CST_Libstdcxx;
3832 }
3833
3834 std::string NetBSD::findLibCxxIncludePath() const {
3835   return getDriver().SysRoot + "/usr/include/c++/";
3836 }
3837
3838 void NetBSD::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3839                                       llvm::opt::ArgStringList &CC1Args) const {
3840   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/g++", "", "", "",
3841                            "", DriverArgs, CC1Args);
3842 }
3843
3844 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3845
3846 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3847     : Generic_ELF(D, Triple, Args) {
3848   getFilePaths().push_back(getDriver().Dir + "/../lib");
3849   getFilePaths().push_back("/usr/lib");
3850 }
3851
3852 Tool *Minix::buildAssembler() const {
3853   return new tools::minix::Assembler(*this);
3854 }
3855
3856 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3857
3858 static void addPathIfExists(const Driver &D, const Twine &Path,
3859                             ToolChain::path_list &Paths) {
3860   if (D.getVFS().exists(Path))
3861     Paths.push_back(Path.str());
3862 }
3863
3864 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3865
3866 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3867                  const ArgList &Args)
3868     : Generic_GCC(D, Triple, Args) {
3869
3870   GCCInstallation.init(Triple, Args);
3871
3872   path_list &Paths = getFilePaths();
3873   if (GCCInstallation.isValid())
3874     addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
3875
3876   addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3877   if (getDriver().getInstalledDir() != getDriver().Dir)
3878     addPathIfExists(D, getDriver().Dir, Paths);
3879
3880   addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3881
3882   std::string LibPath = "/usr/lib/";
3883   switch (Triple.getArch()) {
3884   case llvm::Triple::x86:
3885   case llvm::Triple::sparc:
3886     break;
3887   case llvm::Triple::x86_64:
3888     LibPath += "amd64/";
3889     break;
3890   case llvm::Triple::sparcv9:
3891     LibPath += "sparcv9/";
3892     break;
3893   default:
3894     llvm_unreachable("Unsupported architecture");
3895   }
3896
3897   addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3898 }
3899
3900 Tool *Solaris::buildAssembler() const {
3901   return new tools::solaris::Assembler(*this);
3902 }
3903
3904 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3905
3906 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3907                                            ArgStringList &CC1Args) const {
3908   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3909       DriverArgs.hasArg(options::OPT_nostdincxx))
3910     return;
3911
3912   // Include the support directory for things like xlocale and fudged system
3913   // headers.
3914   // FIXME: This is a weird mix of libc++ and libstdc++. We should also be
3915   // checking the value of -stdlib= here and adding the includes for libc++
3916   // rather than libstdc++ if it's requested.
3917   addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3918
3919   if (GCCInstallation.isValid()) {
3920     GCCVersion Version = GCCInstallation.getVersion();
3921     addSystemInclude(DriverArgs, CC1Args,
3922                      getDriver().SysRoot + "/usr/gcc/" +
3923                      Version.MajorStr + "." +
3924                      Version.MinorStr +
3925                      "/include/c++/" + Version.Text);
3926     addSystemInclude(DriverArgs, CC1Args,
3927                      getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3928                      "." + Version.MinorStr + "/include/c++/" +
3929                      Version.Text + "/" +
3930                      GCCInstallation.getTriple().str());
3931   }
3932 }
3933
3934 /// \brief Get our best guess at the multiarch triple for a target.
3935 ///
3936 /// Debian-based systems are starting to use a multiarch setup where they use
3937 /// a target-triple directory in the library and header search paths.
3938 /// Unfortunately, this triple does not align with the vanilla target triple,
3939 /// so we provide a rough mapping here.
3940 static std::string getMultiarchTriple(const Driver &D,
3941                                       const llvm::Triple &TargetTriple,
3942                                       StringRef SysRoot) {
3943   llvm::Triple::EnvironmentType TargetEnvironment =
3944       TargetTriple.getEnvironment();
3945
3946   // For most architectures, just use whatever we have rather than trying to be
3947   // clever.
3948   switch (TargetTriple.getArch()) {
3949   default:
3950     break;
3951
3952   // We use the existence of '/lib/<triple>' as a directory to detect some
3953   // common linux triples that don't quite match the Clang triple for both
3954   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3955   // regardless of what the actual target triple is.
3956   case llvm::Triple::arm:
3957   case llvm::Triple::thumb:
3958     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3959       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3960         return "arm-linux-gnueabihf";
3961     } else {
3962       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3963         return "arm-linux-gnueabi";
3964     }
3965     break;
3966   case llvm::Triple::armeb:
3967   case llvm::Triple::thumbeb:
3968     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3969       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3970         return "armeb-linux-gnueabihf";
3971     } else {
3972       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3973         return "armeb-linux-gnueabi";
3974     }
3975     break;
3976   case llvm::Triple::x86:
3977     if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3978       return "i386-linux-gnu";
3979     break;
3980   case llvm::Triple::x86_64:
3981     // We don't want this for x32, otherwise it will match x86_64 libs
3982     if (TargetEnvironment != llvm::Triple::GNUX32 &&
3983         D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3984       return "x86_64-linux-gnu";
3985     break;
3986   case llvm::Triple::aarch64:
3987     if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3988       return "aarch64-linux-gnu";
3989     break;
3990   case llvm::Triple::aarch64_be:
3991     if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3992       return "aarch64_be-linux-gnu";
3993     break;
3994   case llvm::Triple::mips:
3995     if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3996       return "mips-linux-gnu";
3997     break;
3998   case llvm::Triple::mipsel:
3999     if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
4000       return "mipsel-linux-gnu";
4001     break;
4002   case llvm::Triple::mips64:
4003     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
4004       return "mips64-linux-gnu";
4005     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
4006       return "mips64-linux-gnuabi64";
4007     break;
4008   case llvm::Triple::mips64el:
4009     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
4010       return "mips64el-linux-gnu";
4011     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
4012       return "mips64el-linux-gnuabi64";
4013     break;
4014   case llvm::Triple::ppc:
4015     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
4016       return "powerpc-linux-gnuspe";
4017     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
4018       return "powerpc-linux-gnu";
4019     break;
4020   case llvm::Triple::ppc64:
4021     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
4022       return "powerpc64-linux-gnu";
4023     break;
4024   case llvm::Triple::ppc64le:
4025     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
4026       return "powerpc64le-linux-gnu";
4027     break;
4028   case llvm::Triple::sparc:
4029     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
4030       return "sparc-linux-gnu";
4031     break;
4032   case llvm::Triple::sparcv9:
4033     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
4034       return "sparc64-linux-gnu";
4035     break;
4036   case llvm::Triple::systemz:
4037     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
4038       return "s390x-linux-gnu";
4039     break;
4040   }
4041   return TargetTriple.str();
4042 }
4043
4044 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
4045   if (isMipsArch(Triple.getArch())) {
4046     if (Triple.isAndroid()) {
4047       StringRef CPUName;
4048       StringRef ABIName;
4049       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4050       if (CPUName == "mips32r6")
4051         return "libr6";
4052       if (CPUName == "mips32r2")
4053         return "libr2";
4054     }
4055     // lib32 directory has a special meaning on MIPS targets.
4056     // It contains N32 ABI binaries. Use this folder if produce
4057     // code for N32 ABI only.
4058     if (tools::mips::hasMipsAbiArg(Args, "n32"))
4059       return "lib32";
4060     return Triple.isArch32Bit() ? "lib" : "lib64";
4061   }
4062
4063   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
4064   // using that variant while targeting other architectures causes problems
4065   // because the libraries are laid out in shared system roots that can't cope
4066   // with a 'lib32' library search path being considered. So we only enable
4067   // them when we know we may need it.
4068   //
4069   // FIXME: This is a bit of a hack. We should really unify this code for
4070   // reasoning about oslibdir spellings with the lib dir spellings in the
4071   // GCCInstallationDetector, but that is a more significant refactoring.
4072   if (Triple.getArch() == llvm::Triple::x86 ||
4073       Triple.getArch() == llvm::Triple::ppc)
4074     return "lib32";
4075
4076   if (Triple.getArch() == llvm::Triple::x86_64 &&
4077       Triple.getEnvironment() == llvm::Triple::GNUX32)
4078     return "libx32";
4079
4080   return Triple.isArch32Bit() ? "lib" : "lib64";
4081 }
4082
4083 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
4084                                   const Multilib &Multilib,
4085                                   StringRef InstallPath,
4086                                   ToolChain::path_list &Paths) {
4087   if (const auto &PathsCallback = Multilibs.filePathsCallback())
4088     for (const auto &Path : PathsCallback(Multilib))
4089       addPathIfExists(D, InstallPath + Path, Paths);
4090 }
4091
4092 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4093     : Generic_ELF(D, Triple, Args) {
4094   GCCInstallation.init(Triple, Args);
4095   Multilibs = GCCInstallation.getMultilibs();
4096   llvm::Triple::ArchType Arch = Triple.getArch();
4097   std::string SysRoot = computeSysRoot();
4098
4099   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
4100   // least) put various tools in a triple-prefixed directory off of the parent
4101   // of the GCC installation. We use the GCC triple here to ensure that we end
4102   // up with tools that support the same amount of cross compiling as the
4103   // detected GCC installation. For example, if we find a GCC installation
4104   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
4105   // used to target i386.
4106   // FIXME: This seems unlikely to be Linux-specific.
4107   ToolChain::path_list &PPaths = getProgramPaths();
4108   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
4109                          GCCInstallation.getTriple().str() + "/bin")
4110                        .str());
4111
4112   Distro Distro(D.getVFS());
4113
4114   if (Distro.IsOpenSUSE() || Distro.IsUbuntu()) {
4115     ExtraOpts.push_back("-z");
4116     ExtraOpts.push_back("relro");
4117   }
4118
4119   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
4120     ExtraOpts.push_back("-X");
4121
4122   const bool IsAndroid = Triple.isAndroid();
4123   const bool IsMips = isMipsArch(Arch);
4124
4125   if (IsMips && !SysRoot.empty())
4126     ExtraOpts.push_back("--sysroot=" + SysRoot);
4127
4128   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
4129   // and the MIPS ABI require .dynsym to be sorted in different ways.
4130   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
4131   // ABI requires a mapping between the GOT and the symbol table.
4132   // Android loader does not support .gnu.hash.
4133   if (!IsMips && !IsAndroid) {
4134     if (Distro.IsRedhat() || Distro.IsOpenSUSE() ||
4135         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick))
4136       ExtraOpts.push_back("--hash-style=gnu");
4137
4138     if (Distro.IsDebian() || Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
4139         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic)
4140       ExtraOpts.push_back("--hash-style=both");
4141   }
4142
4143   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
4144     ExtraOpts.push_back("--no-add-needed");
4145
4146 #ifdef ENABLE_LINKER_BUILD_ID
4147   ExtraOpts.push_back("--build-id");
4148 #endif
4149
4150   if (Distro.IsOpenSUSE())
4151     ExtraOpts.push_back("--enable-new-dtags");
4152
4153   // The selection of paths to try here is designed to match the patterns which
4154   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
4155   // This was determined by running GCC in a fake filesystem, creating all
4156   // possible permutations of these directories, and seeing which ones it added
4157   // to the link paths.
4158   path_list &Paths = getFilePaths();
4159
4160   const std::string OSLibDir = getOSLibDir(Triple, Args);
4161   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
4162
4163   // Add the multilib suffixed paths where they are available.
4164   if (GCCInstallation.isValid()) {
4165     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4166     const std::string &LibPath = GCCInstallation.getParentLibPath();
4167     const Multilib &Multilib = GCCInstallation.getMultilib();
4168     const MultilibSet &Multilibs = GCCInstallation.getMultilibs();
4169
4170     // Add toolchain / multilib specific file paths.
4171     addMultilibsFilePaths(D, Multilibs, Multilib,
4172                           GCCInstallation.getInstallPath(), Paths);
4173
4174     // Sourcery CodeBench MIPS toolchain holds some libraries under
4175     // a biarch-like suffix of the GCC installation.
4176     addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
4177                     Paths);
4178
4179     // GCC cross compiling toolchains will install target libraries which ship
4180     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
4181     // any part of the GCC installation in
4182     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
4183     // debatable, but is the reality today. We need to search this tree even
4184     // when we have a sysroot somewhere else. It is the responsibility of
4185     // whomever is doing the cross build targeting a sysroot using a GCC
4186     // installation that is *not* within the system root to ensure two things:
4187     //
4188     //  1) Any DSOs that are linked in from this tree or from the install path
4189     //     above must be present on the system root and found via an
4190     //     appropriate rpath.
4191     //  2) There must not be libraries installed into
4192     //     <prefix>/<triple>/<libdir> unless they should be preferred over
4193     //     those within the system root.
4194     //
4195     // Note that this matches the GCC behavior. See the below comment for where
4196     // Clang diverges from GCC's behavior.
4197     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
4198                            OSLibDir + Multilib.osSuffix(),
4199                     Paths);
4200
4201     // If the GCC installation we found is inside of the sysroot, we want to
4202     // prefer libraries installed in the parent prefix of the GCC installation.
4203     // It is important to *not* use these paths when the GCC installation is
4204     // outside of the system root as that can pick up unintended libraries.
4205     // This usually happens when there is an external cross compiler on the
4206     // host system, and a more minimal sysroot available that is the target of
4207     // the cross. Note that GCC does include some of these directories in some
4208     // configurations but this seems somewhere between questionable and simply
4209     // a bug.
4210     if (StringRef(LibPath).startswith(SysRoot)) {
4211       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
4212       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
4213     }
4214   }
4215
4216   // Similar to the logic for GCC above, if we currently running Clang inside
4217   // of the requested system root, add its parent library paths to
4218   // those searched.
4219   // FIXME: It's not clear whether we should use the driver's installed
4220   // directory ('Dir' below) or the ResourceDir.
4221   if (StringRef(D.Dir).startswith(SysRoot)) {
4222     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
4223     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
4224   }
4225
4226   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
4227   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
4228   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
4229   addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
4230
4231   // Try walking via the GCC triple path in case of biarch or multiarch GCC
4232   // installations with strange symlinks.
4233   if (GCCInstallation.isValid()) {
4234     addPathIfExists(D,
4235                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
4236                         "/../../" + OSLibDir,
4237                     Paths);
4238
4239     // Add the 'other' biarch variant path
4240     Multilib BiarchSibling;
4241     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
4242       addPathIfExists(D, GCCInstallation.getInstallPath() +
4243                              BiarchSibling.gccSuffix(),
4244                       Paths);
4245     }
4246
4247     // See comments above on the multilib variant for details of why this is
4248     // included even from outside the sysroot.
4249     const std::string &LibPath = GCCInstallation.getParentLibPath();
4250     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4251     const Multilib &Multilib = GCCInstallation.getMultilib();
4252     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
4253                            Multilib.osSuffix(),
4254                     Paths);
4255
4256     // See comments above on the multilib variant for details of why this is
4257     // only included from within the sysroot.
4258     if (StringRef(LibPath).startswith(SysRoot))
4259       addPathIfExists(D, LibPath, Paths);
4260   }
4261
4262   // Similar to the logic for GCC above, if we are currently running Clang
4263   // inside of the requested system root, add its parent library path to those
4264   // searched.
4265   // FIXME: It's not clear whether we should use the driver's installed
4266   // directory ('Dir' below) or the ResourceDir.
4267   if (StringRef(D.Dir).startswith(SysRoot))
4268     addPathIfExists(D, D.Dir + "/../lib", Paths);
4269
4270   addPathIfExists(D, SysRoot + "/lib", Paths);
4271   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
4272 }
4273
4274 bool Linux::HasNativeLLVMSupport() const { return true; }
4275
4276 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
4277
4278 Tool *Linux::buildAssembler() const {
4279   return new tools::gnutools::Assembler(*this);
4280 }
4281
4282 std::string Linux::computeSysRoot() const {
4283   if (!getDriver().SysRoot.empty())
4284     return getDriver().SysRoot;
4285
4286   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
4287     return std::string();
4288
4289   // Standalone MIPS toolchains use different names for sysroot folder
4290   // and put it into different places. Here we try to check some known
4291   // variants.
4292
4293   const StringRef InstallDir = GCCInstallation.getInstallPath();
4294   const StringRef TripleStr = GCCInstallation.getTriple().str();
4295   const Multilib &Multilib = GCCInstallation.getMultilib();
4296
4297   std::string Path =
4298       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
4299           .str();
4300
4301   if (getVFS().exists(Path))
4302     return Path;
4303
4304   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
4305
4306   if (getVFS().exists(Path))
4307     return Path;
4308
4309   return std::string();
4310 }
4311
4312 std::string Linux::getDynamicLinker(const ArgList &Args) const {
4313   const llvm::Triple::ArchType Arch = getArch();
4314   const llvm::Triple &Triple = getTriple();
4315
4316   const Distro Distro(getDriver().getVFS());
4317
4318   if (Triple.isAndroid())
4319     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
4320
4321   if (Triple.isMusl()) {
4322     std::string ArchName;
4323     bool IsArm = false;
4324
4325     switch (Arch) {
4326     case llvm::Triple::arm:
4327     case llvm::Triple::thumb:
4328       ArchName = "arm";
4329       IsArm = true;
4330       break;
4331     case llvm::Triple::armeb:
4332     case llvm::Triple::thumbeb:
4333       ArchName = "armeb";
4334       IsArm = true;
4335       break;
4336     default:
4337       ArchName = Triple.getArchName().str();
4338     }
4339     if (IsArm &&
4340         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
4341          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
4342       ArchName += "hf";
4343
4344     return "/lib/ld-musl-" + ArchName + ".so.1";
4345   }
4346
4347   std::string LibDir;
4348   std::string Loader;
4349
4350   switch (Arch) {
4351   default:
4352     llvm_unreachable("unsupported architecture");
4353
4354   case llvm::Triple::aarch64:
4355     LibDir = "lib";
4356     Loader = "ld-linux-aarch64.so.1";
4357     break;
4358   case llvm::Triple::aarch64_be:
4359     LibDir = "lib";
4360     Loader = "ld-linux-aarch64_be.so.1";
4361     break;
4362   case llvm::Triple::arm:
4363   case llvm::Triple::thumb:
4364   case llvm::Triple::armeb:
4365   case llvm::Triple::thumbeb: {
4366     const bool HF =
4367         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
4368         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
4369
4370     LibDir = "lib";
4371     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
4372     break;
4373   }
4374   case llvm::Triple::mips:
4375   case llvm::Triple::mipsel:
4376   case llvm::Triple::mips64:
4377   case llvm::Triple::mips64el: {
4378     bool LE = (Triple.getArch() == llvm::Triple::mipsel) ||
4379               (Triple.getArch() == llvm::Triple::mips64el);
4380     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
4381
4382     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
4383
4384     if (tools::mips::isUCLibc(Args))
4385       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
4386     else if (!Triple.hasEnvironment() &&
4387              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
4388       Loader = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
4389     else
4390       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
4391
4392     break;
4393   }
4394   case llvm::Triple::ppc:
4395     LibDir = "lib";
4396     Loader = "ld.so.1";
4397     break;
4398   case llvm::Triple::ppc64:
4399     LibDir = "lib64";
4400     Loader =
4401         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
4402     break;
4403   case llvm::Triple::ppc64le:
4404     LibDir = "lib64";
4405     Loader =
4406         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
4407     break;
4408   case llvm::Triple::sparc:
4409   case llvm::Triple::sparcel:
4410     LibDir = "lib";
4411     Loader = "ld-linux.so.2";
4412     break;
4413   case llvm::Triple::sparcv9:
4414     LibDir = "lib64";
4415     Loader = "ld-linux.so.2";
4416     break;
4417   case llvm::Triple::systemz:
4418     LibDir = "lib";
4419     Loader = "ld64.so.1";
4420     break;
4421   case llvm::Triple::x86:
4422     LibDir = "lib";
4423     Loader = "ld-linux.so.2";
4424     break;
4425   case llvm::Triple::x86_64: {
4426     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
4427
4428     LibDir = X32 ? "libx32" : "lib64";
4429     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
4430     break;
4431   }
4432   }
4433
4434   if (Distro == Distro::Exherbo && (Triple.getVendor() == llvm::Triple::UnknownVendor ||
4435                                     Triple.getVendor() == llvm::Triple::PC))
4436     return "/usr/" + Triple.str() + "/lib/" + Loader;
4437   return "/" + LibDir + "/" + Loader;
4438 }
4439
4440 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4441                                       ArgStringList &CC1Args) const {
4442   const Driver &D = getDriver();
4443   std::string SysRoot = computeSysRoot();
4444
4445   if (DriverArgs.hasArg(options::OPT_nostdinc))
4446     return;
4447
4448   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
4449     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
4450
4451   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4452     SmallString<128> P(D.ResourceDir);
4453     llvm::sys::path::append(P, "include");
4454     addSystemInclude(DriverArgs, CC1Args, P);
4455   }
4456
4457   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4458     return;
4459
4460   // Check for configure-time C include directories.
4461   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4462   if (CIncludeDirs != "") {
4463     SmallVector<StringRef, 5> dirs;
4464     CIncludeDirs.split(dirs, ":");
4465     for (StringRef dir : dirs) {
4466       StringRef Prefix =
4467           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
4468       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4469     }
4470     return;
4471   }
4472
4473   // Lacking those, try to detect the correct set of system includes for the
4474   // target triple.
4475
4476   // Add include directories specific to the selected multilib set and multilib.
4477   if (GCCInstallation.isValid()) {
4478     const auto &Callback = Multilibs.includeDirsCallback();
4479     if (Callback) {
4480       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
4481         addExternCSystemIncludeIfExists(
4482             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
4483     }
4484   }
4485
4486   // Implement generic Debian multiarch support.
4487   const StringRef X86_64MultiarchIncludeDirs[] = {
4488       "/usr/include/x86_64-linux-gnu",
4489
4490       // FIXME: These are older forms of multiarch. It's not clear that they're
4491       // in use in any released version of Debian, so we should consider
4492       // removing them.
4493       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
4494   const StringRef X86MultiarchIncludeDirs[] = {
4495       "/usr/include/i386-linux-gnu",
4496
4497       // FIXME: These are older forms of multiarch. It's not clear that they're
4498       // in use in any released version of Debian, so we should consider
4499       // removing them.
4500       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
4501       "/usr/include/i486-linux-gnu"};
4502   const StringRef AArch64MultiarchIncludeDirs[] = {
4503       "/usr/include/aarch64-linux-gnu"};
4504   const StringRef ARMMultiarchIncludeDirs[] = {
4505       "/usr/include/arm-linux-gnueabi"};
4506   const StringRef ARMHFMultiarchIncludeDirs[] = {
4507       "/usr/include/arm-linux-gnueabihf"};
4508   const StringRef ARMEBMultiarchIncludeDirs[] = {
4509       "/usr/include/armeb-linux-gnueabi"};
4510   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
4511       "/usr/include/armeb-linux-gnueabihf"};
4512   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
4513   const StringRef MIPSELMultiarchIncludeDirs[] = {
4514       "/usr/include/mipsel-linux-gnu"};
4515   const StringRef MIPS64MultiarchIncludeDirs[] = {
4516       "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
4517   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
4518       "/usr/include/mips64el-linux-gnu",
4519       "/usr/include/mips64el-linux-gnuabi64"};
4520   const StringRef PPCMultiarchIncludeDirs[] = {
4521       "/usr/include/powerpc-linux-gnu"};
4522   const StringRef PPC64MultiarchIncludeDirs[] = {
4523       "/usr/include/powerpc64-linux-gnu"};
4524   const StringRef PPC64LEMultiarchIncludeDirs[] = {
4525       "/usr/include/powerpc64le-linux-gnu"};
4526   const StringRef SparcMultiarchIncludeDirs[] = {
4527       "/usr/include/sparc-linux-gnu"};
4528   const StringRef Sparc64MultiarchIncludeDirs[] = {
4529       "/usr/include/sparc64-linux-gnu"};
4530   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
4531       "/usr/include/s390x-linux-gnu"};
4532   ArrayRef<StringRef> MultiarchIncludeDirs;
4533   switch (getTriple().getArch()) {
4534   case llvm::Triple::x86_64:
4535     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
4536     break;
4537   case llvm::Triple::x86:
4538     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
4539     break;
4540   case llvm::Triple::aarch64:
4541   case llvm::Triple::aarch64_be:
4542     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
4543     break;
4544   case llvm::Triple::arm:
4545   case llvm::Triple::thumb:
4546     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4547       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
4548     else
4549       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
4550     break;
4551   case llvm::Triple::armeb:
4552   case llvm::Triple::thumbeb:
4553     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4554       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
4555     else
4556       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
4557     break;
4558   case llvm::Triple::mips:
4559     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
4560     break;
4561   case llvm::Triple::mipsel:
4562     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
4563     break;
4564   case llvm::Triple::mips64:
4565     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
4566     break;
4567   case llvm::Triple::mips64el:
4568     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
4569     break;
4570   case llvm::Triple::ppc:
4571     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
4572     break;
4573   case llvm::Triple::ppc64:
4574     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
4575     break;
4576   case llvm::Triple::ppc64le:
4577     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
4578     break;
4579   case llvm::Triple::sparc:
4580     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
4581     break;
4582   case llvm::Triple::sparcv9:
4583     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
4584     break;
4585   case llvm::Triple::systemz:
4586     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4587     break;
4588   default:
4589     break;
4590   }
4591   for (StringRef Dir : MultiarchIncludeDirs) {
4592     if (D.getVFS().exists(SysRoot + Dir)) {
4593       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4594       break;
4595     }
4596   }
4597
4598   if (getTriple().getOS() == llvm::Triple::RTEMS)
4599     return;
4600
4601   // Add an include of '/include' directly. This isn't provided by default by
4602   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4603   // add even when Clang is acting as-if it were a system compiler.
4604   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4605
4606   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4607 }
4608
4609 static std::string DetectLibcxxIncludePath(StringRef base) {
4610   std::error_code EC;
4611   int MaxVersion = 0;
4612   std::string MaxVersionString = "";
4613   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4614        LI = LI.increment(EC)) {
4615     StringRef VersionText = llvm::sys::path::filename(LI->path());
4616     int Version;
4617     if (VersionText[0] == 'v' &&
4618         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4619       if (Version > MaxVersion) {
4620         MaxVersion = Version;
4621         MaxVersionString = VersionText;
4622       }
4623     }
4624   }
4625   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4626 }
4627
4628 std::string Linux::findLibCxxIncludePath() const {
4629   const std::string LibCXXIncludePathCandidates[] = {
4630       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4631       // If this is a development, non-installed, clang, libcxx will
4632       // not be found at ../include/c++ but it likely to be found at
4633       // one of the following two locations:
4634       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/local/include/c++"),
4635       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++") };
4636   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4637     if (IncludePath.empty() || !getVFS().exists(IncludePath))
4638       continue;
4639     // Use the first candidate that exists.
4640     return IncludePath;
4641   }
4642   return "";
4643 }
4644
4645 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
4646                                      llvm::opt::ArgStringList &CC1Args) const {
4647   // We need a detected GCC installation on Linux to provide libstdc++'s
4648   // headers.
4649   if (!GCCInstallation.isValid())
4650     return;
4651
4652   // By default, look for the C++ headers in an include directory adjacent to
4653   // the lib directory of the GCC installation. Note that this is expect to be
4654   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4655   StringRef LibDir = GCCInstallation.getParentLibPath();
4656   StringRef InstallDir = GCCInstallation.getInstallPath();
4657   StringRef TripleStr = GCCInstallation.getTriple().str();
4658   const Multilib &Multilib = GCCInstallation.getMultilib();
4659   const std::string GCCMultiarchTriple = getMultiarchTriple(
4660       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
4661   const std::string TargetMultiarchTriple =
4662       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
4663   const GCCVersion &Version = GCCInstallation.getVersion();
4664
4665   // The primary search for libstdc++ supports multiarch variants.
4666   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4667                                "/c++/" + Version.Text, TripleStr,
4668                                GCCMultiarchTriple, TargetMultiarchTriple,
4669                                Multilib.includeSuffix(), DriverArgs, CC1Args))
4670     return;
4671
4672   // Otherwise, fall back on a bunch of options which don't use multiarch
4673   // layouts for simplicity.
4674   const std::string LibStdCXXIncludePathCandidates[] = {
4675       // Gentoo is weird and places its headers inside the GCC install,
4676       // so if the first attempt to find the headers fails, try these patterns.
4677       InstallDir.str() + "/include/g++-v" + Version.Text,
4678       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4679           Version.MinorStr,
4680       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4681       // Android standalone toolchain has C++ headers in yet another place.
4682       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4683       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4684       // without a subdirectory corresponding to the gcc version.
4685       LibDir.str() + "/../include/c++",
4686   };
4687
4688   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4689     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4690                                  /*GCCMultiarchTriple*/ "",
4691                                  /*TargetMultiarchTriple*/ "",
4692                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
4693       break;
4694   }
4695 }
4696
4697 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4698                                ArgStringList &CC1Args) const {
4699   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4700 }
4701
4702 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
4703                                 ArgStringList &CC1Args) const {
4704   if (GCCInstallation.isValid()) {
4705     CC1Args.push_back("-isystem");
4706     CC1Args.push_back(DriverArgs.MakeArgString(
4707         GCCInstallation.getParentLibPath() + "/../" +
4708         GCCInstallation.getTriple().str() + "/include"));
4709   }
4710 }
4711
4712 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
4713
4714 SanitizerMask Linux::getSupportedSanitizers() const {
4715   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4716   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4717   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4718                         getTriple().getArch() == llvm::Triple::mips64el;
4719   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4720                            getTriple().getArch() == llvm::Triple::ppc64le;
4721   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4722                          getTriple().getArch() == llvm::Triple::aarch64_be;
4723   SanitizerMask Res = ToolChain::getSupportedSanitizers();
4724   Res |= SanitizerKind::Address;
4725   Res |= SanitizerKind::KernelAddress;
4726   Res |= SanitizerKind::Vptr;
4727   Res |= SanitizerKind::SafeStack;
4728   if (IsX86_64 || IsMIPS64 || IsAArch64)
4729     Res |= SanitizerKind::DataFlow;
4730   if (IsX86_64 || IsMIPS64 || IsAArch64)
4731     Res |= SanitizerKind::Leak;
4732   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4733     Res |= SanitizerKind::Thread;
4734   if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4735     Res |= SanitizerKind::Memory;
4736   if (IsX86_64 || IsMIPS64)
4737     Res |= SanitizerKind::Efficiency;
4738   if (IsX86 || IsX86_64) {
4739     Res |= SanitizerKind::Function;
4740   }
4741   return Res;
4742 }
4743
4744 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4745                              llvm::opt::ArgStringList &CmdArgs) const {
4746   if (!needsProfileRT(Args)) return;
4747
4748   // Add linker option -u__llvm_runtime_variable to cause runtime
4749   // initialization module to be linked in.
4750   if (!Args.hasArg(options::OPT_coverage))
4751     CmdArgs.push_back(Args.MakeArgString(
4752         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4753   ToolChain::addProfileRTLibs(Args, CmdArgs);
4754 }
4755
4756 /// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
4757
4758 Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
4759                  const ArgList &Args)
4760     : Generic_ELF(D, Triple, Args) {
4761
4762   getFilePaths().push_back(D.SysRoot + "/lib");
4763   getFilePaths().push_back(D.ResourceDir + "/lib/fuchsia");
4764 }
4765
4766 Tool *Fuchsia::buildAssembler() const {
4767   return new tools::gnutools::Assembler(*this);
4768 }
4769
4770 Tool *Fuchsia::buildLinker() const {
4771   return new tools::fuchsia::Linker(*this);
4772 }
4773
4774 ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
4775     const ArgList &Args) const {
4776   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
4777     StringRef Value = A->getValue();
4778     if (Value != "compiler-rt")
4779       getDriver().Diag(diag::err_drv_invalid_rtlib_name)
4780         << A->getAsString(Args);
4781   }
4782
4783   return ToolChain::RLT_CompilerRT;
4784 }
4785
4786 ToolChain::CXXStdlibType
4787 Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
4788   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
4789     StringRef Value = A->getValue();
4790     if (Value != "libc++")
4791       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
4792         << A->getAsString(Args);
4793   }
4794
4795   return ToolChain::CST_Libcxx;
4796 }
4797
4798 void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
4799                                     ArgStringList &CC1Args) const {
4800   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4801                          options::OPT_fno_use_init_array, true))
4802     CC1Args.push_back("-fuse-init-array");
4803 }
4804
4805 void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4806                                         ArgStringList &CC1Args) const {
4807   const Driver &D = getDriver();
4808
4809   if (DriverArgs.hasArg(options::OPT_nostdinc))
4810     return;
4811
4812   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4813     SmallString<128> P(D.ResourceDir);
4814     llvm::sys::path::append(P, "include");
4815     addSystemInclude(DriverArgs, CC1Args, P);
4816   }
4817
4818   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4819     return;
4820
4821   // Check for configure-time C include directories.
4822   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4823   if (CIncludeDirs != "") {
4824     SmallVector<StringRef, 5> dirs;
4825     CIncludeDirs.split(dirs, ":");
4826     for (StringRef dir : dirs) {
4827       StringRef Prefix =
4828           llvm::sys::path::is_absolute(dir) ? StringRef(D.SysRoot) : "";
4829       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4830     }
4831     return;
4832   }
4833
4834   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
4835 }
4836
4837 std::string Fuchsia::findLibCxxIncludePath() const {
4838   return getDriver().SysRoot + "/include/c++/v1";
4839 }
4840
4841 void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
4842                                   ArgStringList &CmdArgs) const {
4843   (void) GetCXXStdlibType(Args);
4844   CmdArgs.push_back("-lc++");
4845   CmdArgs.push_back("-lc++abi");
4846   CmdArgs.push_back("-lunwind");
4847 }
4848
4849 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4850
4851 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4852                      const ArgList &Args)
4853     : Generic_ELF(D, Triple, Args) {
4854
4855   // Path mangling to find libexec
4856   getProgramPaths().push_back(getDriver().getInstalledDir());
4857   if (getDriver().getInstalledDir() != getDriver().Dir)
4858     getProgramPaths().push_back(getDriver().Dir);
4859
4860   getFilePaths().push_back(getDriver().Dir + "/../lib");
4861   getFilePaths().push_back("/usr/lib");
4862   getFilePaths().push_back("/usr/lib/gcc50");
4863 }
4864
4865 Tool *DragonFly::buildAssembler() const {
4866   return new tools::dragonfly::Assembler(*this);
4867 }
4868
4869 Tool *DragonFly::buildLinker() const {
4870   return new tools::dragonfly::Linker(*this);
4871 }
4872
4873 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
4874 /// which isn't properly a linker but nonetheless performs the step of stitching
4875 /// together object files from the assembler into a single blob.
4876
4877 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4878                              const ToolChain &HostTC, const ArgList &Args)
4879     : ToolChain(D, Triple, Args), HostTC(HostTC),
4880       CudaInstallation(D, HostTC.getTriple(), Args) {
4881   if (CudaInstallation.isValid())
4882     getProgramPaths().push_back(CudaInstallation.getBinPath());
4883 }
4884
4885 void CudaToolChain::addClangTargetOptions(
4886     const llvm::opt::ArgList &DriverArgs,
4887     llvm::opt::ArgStringList &CC1Args) const {
4888   HostTC.addClangTargetOptions(DriverArgs, CC1Args);
4889
4890   CC1Args.push_back("-fcuda-is-device");
4891
4892   if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
4893                          options::OPT_fno_cuda_flush_denormals_to_zero, false))
4894     CC1Args.push_back("-fcuda-flush-denormals-to-zero");
4895
4896   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
4897                          options::OPT_fno_cuda_approx_transcendentals, false))
4898     CC1Args.push_back("-fcuda-approx-transcendentals");
4899
4900   if (DriverArgs.hasArg(options::OPT_nocudalib))
4901     return;
4902
4903   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4904   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
4905   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
4906
4907   if (LibDeviceFile.empty()) {
4908     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
4909     return;
4910   }
4911
4912   CC1Args.push_back("-mlink-cuda-bitcode");
4913   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4914
4915   // Libdevice in CUDA-7.0 requires PTX version that's more recent
4916   // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4917   // came with CUDA-7.0.
4918   CC1Args.push_back("-target-feature");
4919   CC1Args.push_back("+ptx42");
4920 }
4921
4922 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
4923                                        ArgStringList &CC1Args) const {
4924   // Check our CUDA version if we're going to include the CUDA headers.
4925   if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
4926       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
4927     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4928     assert(!Arch.empty() && "Must have an explicit GPU arch.");
4929     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
4930   }
4931   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4932 }
4933
4934 llvm::opt::DerivedArgList *
4935 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4936                              StringRef BoundArch,
4937                              Action::OffloadKind DeviceOffloadKind) const {
4938   DerivedArgList *DAL =
4939       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
4940   if (!DAL)
4941     DAL = new DerivedArgList(Args.getBaseArgs());
4942
4943   const OptTable &Opts = getDriver().getOpts();
4944
4945   for (Arg *A : Args) {
4946     if (A->getOption().matches(options::OPT_Xarch__)) {
4947       // Skip this argument unless the architecture matches BoundArch
4948       if (BoundArch.empty() || A->getValue(0) != BoundArch)
4949         continue;
4950
4951       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4952       unsigned Prev = Index;
4953       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4954
4955       // If the argument parsing failed or more than one argument was
4956       // consumed, the -Xarch_ argument's parameter tried to consume
4957       // extra arguments. Emit an error and ignore.
4958       //
4959       // We also want to disallow any options which would alter the
4960       // driver behavior; that isn't going to work in our model. We
4961       // use isDriverOption() as an approximation, although things
4962       // like -O4 are going to slip through.
4963       if (!XarchArg || Index > Prev + 1) {
4964         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4965             << A->getAsString(Args);
4966         continue;
4967       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4968         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4969             << A->getAsString(Args);
4970         continue;
4971       }
4972       XarchArg->setBaseArg(A);
4973       A = XarchArg.release();
4974       DAL->AddSynthesizedArg(A);
4975     }
4976     DAL->append(A);
4977   }
4978
4979   if (!BoundArch.empty()) {
4980     DAL->eraseArg(options::OPT_march_EQ);
4981     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4982   }
4983   return DAL;
4984 }
4985
4986 Tool *CudaToolChain::buildAssembler() const {
4987   return new tools::NVPTX::Assembler(*this);
4988 }
4989
4990 Tool *CudaToolChain::buildLinker() const {
4991   return new tools::NVPTX::Linker(*this);
4992 }
4993
4994 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
4995   HostTC.addClangWarningOptions(CC1Args);
4996 }
4997
4998 ToolChain::CXXStdlibType
4999 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
5000   return HostTC.GetCXXStdlibType(Args);
5001 }
5002
5003 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5004                                               ArgStringList &CC1Args) const {
5005   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
5006 }
5007
5008 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
5009                                                  ArgStringList &CC1Args) const {
5010   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
5011 }
5012
5013 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
5014                                         ArgStringList &CC1Args) const {
5015   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
5016 }
5017
5018 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
5019   // The CudaToolChain only supports sanitizers in the sense that it allows
5020   // sanitizer arguments on the command line if they are supported by the host
5021   // toolchain. The CudaToolChain will actually ignore any command line
5022   // arguments for any of these "supported" sanitizers. That means that no
5023   // sanitization of device code is actually supported at this time.
5024   //
5025   // This behavior is necessary because the host and device toolchains
5026   // invocations often share the command line, so the device toolchain must
5027   // tolerate flags meant only for the host toolchain.
5028   return HostTC.getSupportedSanitizers();
5029 }
5030
5031 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
5032                                                const ArgList &Args) const {
5033   return HostTC.computeMSVCVersion(D, Args);
5034 }
5035
5036 /// XCore tool chain
5037 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
5038                                const ArgList &Args)
5039     : ToolChain(D, Triple, Args) {
5040   // ProgramPaths are found via 'PATH' environment variable.
5041 }
5042
5043 Tool *XCoreToolChain::buildAssembler() const {
5044   return new tools::XCore::Assembler(*this);
5045 }
5046
5047 Tool *XCoreToolChain::buildLinker() const {
5048   return new tools::XCore::Linker(*this);
5049 }
5050
5051 bool XCoreToolChain::isPICDefault() const { return false; }
5052
5053 bool XCoreToolChain::isPIEDefault() const { return false; }
5054
5055 bool XCoreToolChain::isPICDefaultForced() const { return false; }
5056
5057 bool XCoreToolChain::SupportsProfiling() const { return false; }
5058
5059 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
5060
5061 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5062                                                ArgStringList &CC1Args) const {
5063   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5064       DriverArgs.hasArg(options::OPT_nostdlibinc))
5065     return;
5066   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
5067     SmallVector<StringRef, 4> Dirs;
5068     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5069     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5070     ArrayRef<StringRef> DirVec(Dirs);
5071     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5072   }
5073 }
5074
5075 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
5076                                            ArgStringList &CC1Args) const {
5077   CC1Args.push_back("-nostdsysteminc");
5078 }
5079
5080 void XCoreToolChain::AddClangCXXStdlibIncludeArgs(
5081     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
5082   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5083       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
5084       DriverArgs.hasArg(options::OPT_nostdincxx))
5085     return;
5086   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
5087     SmallVector<StringRef, 4> Dirs;
5088     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5089     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5090     ArrayRef<StringRef> DirVec(Dirs);
5091     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5092   }
5093 }
5094
5095 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
5096                                          ArgStringList &CmdArgs) const {
5097   // We don't output any lib args. This is handled by xcc.
5098 }
5099
5100 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
5101                                  const ArgList &Args)
5102     : Generic_ELF(D, Triple, Args) {
5103   // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
5104   // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
5105   // This won't work to find gcc. Instead we give the installation detector an
5106   // extra triple, which is preferable to further hacks of the logic that at
5107   // present is based solely on getArch(). In particular, it would be wrong to
5108   // choose the myriad installation when targeting a non-myriad sparc install.
5109   switch (Triple.getArch()) {
5110   default:
5111     D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5112                                               << "myriad";
5113   case llvm::Triple::sparc:
5114   case llvm::Triple::sparcel:
5115   case llvm::Triple::shave:
5116     GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
5117   }
5118
5119   if (GCCInstallation.isValid()) {
5120     // This directory contains crt{i,n,begin,end}.o as well as libgcc.
5121     // These files are tied to a particular version of gcc.
5122     SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
5123     addPathIfExists(D, CompilerSupportDir, getFilePaths());
5124   }
5125   // libstd++ and libc++ must both be found in this one place.
5126   addPathIfExists(D, D.Dir + "/../sparc-myriad-elf/lib", getFilePaths());
5127 }
5128
5129 MyriadToolChain::~MyriadToolChain() {}
5130
5131 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5132                                                 ArgStringList &CC1Args) const {
5133   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5134     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5135 }
5136
5137 std::string MyriadToolChain::findLibCxxIncludePath() const {
5138   std::string Path(getDriver().getInstalledDir());
5139   return Path + "/../include/c++/v1";
5140 }
5141
5142 void MyriadToolChain::addLibStdCxxIncludePaths(
5143     const llvm::opt::ArgList &DriverArgs,
5144     llvm::opt::ArgStringList &CC1Args) const {
5145   StringRef LibDir = GCCInstallation.getParentLibPath();
5146   const GCCVersion &Version = GCCInstallation.getVersion();
5147   StringRef TripleStr = GCCInstallation.getTriple().str();
5148   const Multilib &Multilib = GCCInstallation.getMultilib();
5149   addLibStdCXXIncludePaths(
5150       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
5151       "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
5152 }
5153
5154 // MyriadToolChain handles several triples:
5155 //  {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
5156 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const {
5157   // The inherited method works fine if not targeting the SHAVE.
5158   if (!isShaveCompilation(getTriple()))
5159     return ToolChain::SelectTool(JA);
5160   switch (JA.getKind()) {
5161   case Action::PreprocessJobClass:
5162   case Action::CompileJobClass:
5163     if (!Compiler)
5164       Compiler.reset(new tools::SHAVE::Compiler(*this));
5165     return Compiler.get();
5166   case Action::AssembleJobClass:
5167     if (!Assembler)
5168       Assembler.reset(new tools::SHAVE::Assembler(*this));
5169     return Assembler.get();
5170   default:
5171     return ToolChain::getTool(JA.getKind());
5172   }
5173 }
5174
5175 Tool *MyriadToolChain::buildLinker() const {
5176   return new tools::Myriad::Linker(*this);
5177 }
5178
5179 SanitizerMask MyriadToolChain::getSupportedSanitizers() const {
5180   return SanitizerKind::Address;
5181 }
5182
5183 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
5184                          const llvm::opt::ArgList &Args)
5185   : ToolChain(D, Triple, Args) {
5186
5187   assert(Triple.isArch32Bit() != Triple.isArch64Bit());
5188   getFilePaths().push_back(
5189       getDriver().SysRoot + "/lib" + (Triple.isArch32Bit() ? "32" : "64"));
5190 }
5191
5192 bool WebAssembly::IsMathErrnoDefault() const { return false; }
5193
5194 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
5195
5196 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
5197
5198 bool WebAssembly::isPICDefault() const { return false; }
5199
5200 bool WebAssembly::isPIEDefault() const { return false; }
5201
5202 bool WebAssembly::isPICDefaultForced() const { return false; }
5203
5204 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
5205
5206 // TODO: Support Objective C stuff.
5207 bool WebAssembly::SupportsObjCGC() const { return false; }
5208
5209 bool WebAssembly::hasBlocksRuntime() const { return false; }
5210
5211 // TODO: Support profiling.
5212 bool WebAssembly::SupportsProfiling() const { return false; }
5213
5214 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
5215
5216 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
5217                                         ArgStringList &CC1Args) const {
5218   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
5219                          options::OPT_fno_use_init_array, true))
5220     CC1Args.push_back("-fuse-init-array");
5221 }
5222
5223 ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
5224   return ToolChain::RLT_CompilerRT;
5225 }
5226
5227 ToolChain::CXXStdlibType WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
5228   return ToolChain::CST_Libcxx;
5229 }
5230
5231 void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5232                                             ArgStringList &CC1Args) const {
5233   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5234     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5235 }
5236
5237 void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
5238                                                ArgStringList &CC1Args) const {
5239   if (!DriverArgs.hasArg(options::OPT_nostdlibinc) &&
5240       !DriverArgs.hasArg(options::OPT_nostdincxx))
5241     addSystemInclude(DriverArgs, CC1Args,
5242                      getDriver().SysRoot + "/include/c++/v1");
5243 }
5244
5245 Tool *WebAssembly::buildLinker() const {
5246   return new tools::wasm::Linker(*this);
5247 }
5248
5249 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5250     : Generic_ELF(D, Triple, Args) {
5251   if (Args.hasArg(options::OPT_static))
5252     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
5253
5254   // Determine where to find the PS4 libraries. We use SCE_ORBIS_SDK_DIR
5255   // if it exists; otherwise use the driver's installation path, which
5256   // should be <SDK_DIR>/host_tools/bin.
5257
5258   SmallString<512> PS4SDKDir;
5259   if (const char *EnvValue = getenv("SCE_ORBIS_SDK_DIR")) {
5260     if (!llvm::sys::fs::exists(EnvValue))
5261       getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
5262     PS4SDKDir = EnvValue;
5263   } else {
5264     PS4SDKDir = getDriver().Dir;
5265     llvm::sys::path::append(PS4SDKDir, "/../../");
5266   }
5267
5268   // By default, the driver won't report a warning if it can't find
5269   // PS4's include or lib directories. This behavior could be changed if
5270   // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
5271   // If -isysroot was passed, use that as the SDK base path.
5272   std::string PrefixDir;
5273   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
5274     PrefixDir = A->getValue();
5275     if (!llvm::sys::fs::exists(PrefixDir))
5276       getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
5277   } else
5278     PrefixDir = PS4SDKDir.str();
5279
5280   SmallString<512> PS4SDKIncludeDir(PrefixDir);
5281   llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
5282   if (!Args.hasArg(options::OPT_nostdinc) &&
5283       !Args.hasArg(options::OPT_nostdlibinc) &&
5284       !Args.hasArg(options::OPT_isysroot) &&
5285       !Args.hasArg(options::OPT__sysroot_EQ) &&
5286       !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
5287     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5288         << "PS4 system headers" << PS4SDKIncludeDir;
5289   }
5290
5291   SmallString<512> PS4SDKLibDir(PS4SDKDir);
5292   llvm::sys::path::append(PS4SDKLibDir, "target/lib");
5293   if (!Args.hasArg(options::OPT_nostdlib) &&
5294       !Args.hasArg(options::OPT_nodefaultlibs) &&
5295       !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
5296       !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
5297       !Args.hasArg(options::OPT_emit_ast) &&
5298       !llvm::sys::fs::exists(PS4SDKLibDir)) {
5299     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5300         << "PS4 system libraries" << PS4SDKLibDir;
5301     return;
5302   }
5303   getFilePaths().push_back(PS4SDKLibDir.str());
5304 }
5305
5306 Tool *PS4CPU::buildAssembler() const {
5307   return new tools::PS4cpu::Assemble(*this);
5308 }
5309
5310 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
5311
5312 bool PS4CPU::isPICDefault() const { return true; }
5313
5314 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
5315
5316 SanitizerMask PS4CPU::getSupportedSanitizers() const {
5317   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5318   Res |= SanitizerKind::Address;
5319   Res |= SanitizerKind::Vptr;
5320   return Res;
5321 }
5322
5323 Contiki::Contiki(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5324     : Generic_ELF(D, Triple, Args) {}
5325
5326 SanitizerMask Contiki::getSupportedSanitizers() const {
5327   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
5328   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5329   if (IsX86)
5330     Res |= SanitizerKind::SafeStack;
5331   return Res;
5332 }
5333
5334 /// AVR Toolchain
5335 AVRToolChain::AVRToolChain(const Driver &D, const llvm::Triple &Triple,
5336                            const ArgList &Args)
5337   : Generic_ELF(D, Triple, Args) { }
5338 Tool *AVRToolChain::buildLinker() const {
5339   return new tools::AVR::Linker(*this);
5340 }
5341 // End AVR