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