xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp (revision 1323ec571215a77ddd21294f0871979d5ad6b992)
1 //===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Linux.h"
10 #include "Arch/ARM.h"
11 #include "Arch/Mips.h"
12 #include "Arch/PPC.h"
13 #include "Arch/RISCV.h"
14 #include "CommonArgs.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Distro.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/ProfileData/InstrProf.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/ScopedPrinter.h"
24 #include "llvm/Support/VirtualFileSystem.h"
25 #include <system_error>
26 
27 using namespace clang::driver;
28 using namespace clang::driver::toolchains;
29 using namespace clang;
30 using namespace llvm::opt;
31 
32 using tools::addPathIfExists;
33 
34 /// Get our best guess at the multiarch triple for a target.
35 ///
36 /// Debian-based systems are starting to use a multiarch setup where they use
37 /// a target-triple directory in the library and header search paths.
38 /// Unfortunately, this triple does not align with the vanilla target triple,
39 /// so we provide a rough mapping here.
40 std::string Linux::getMultiarchTriple(const Driver &D,
41                                       const llvm::Triple &TargetTriple,
42                                       StringRef SysRoot) const {
43   llvm::Triple::EnvironmentType TargetEnvironment =
44       TargetTriple.getEnvironment();
45   bool IsAndroid = TargetTriple.isAndroid();
46   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
47   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
48 
49   // For most architectures, just use whatever we have rather than trying to be
50   // clever.
51   switch (TargetTriple.getArch()) {
52   default:
53     break;
54 
55   // We use the existence of '/lib/<triple>' as a directory to detect some
56   // common linux triples that don't quite match the Clang triple for both
57   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
58   // regardless of what the actual target triple is.
59   case llvm::Triple::arm:
60   case llvm::Triple::thumb:
61     if (IsAndroid)
62       return "arm-linux-androideabi";
63     if (TargetEnvironment == llvm::Triple::GNUEABIHF)
64       return "arm-linux-gnueabihf";
65     return "arm-linux-gnueabi";
66   case llvm::Triple::armeb:
67   case llvm::Triple::thumbeb:
68     if (TargetEnvironment == llvm::Triple::GNUEABIHF)
69       return "armeb-linux-gnueabihf";
70     return "armeb-linux-gnueabi";
71   case llvm::Triple::x86:
72     if (IsAndroid)
73       return "i686-linux-android";
74     return "i386-linux-gnu";
75   case llvm::Triple::x86_64:
76     if (IsAndroid)
77       return "x86_64-linux-android";
78     if (TargetEnvironment == llvm::Triple::GNUX32)
79       return "x86_64-linux-gnux32";
80     return "x86_64-linux-gnu";
81   case llvm::Triple::aarch64:
82     if (IsAndroid)
83       return "aarch64-linux-android";
84     return "aarch64-linux-gnu";
85   case llvm::Triple::aarch64_be:
86     return "aarch64_be-linux-gnu";
87 
88   case llvm::Triple::m68k:
89     return "m68k-linux-gnu";
90 
91   case llvm::Triple::mips:
92     return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
93   case llvm::Triple::mipsel:
94     if (IsAndroid)
95       return "mipsel-linux-android";
96     return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
97   case llvm::Triple::mips64: {
98     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
99                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
100     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
101       return MT;
102     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
103       return "mips64-linux-gnu";
104     break;
105   }
106   case llvm::Triple::mips64el: {
107     if (IsAndroid)
108       return "mips64el-linux-android";
109     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
110                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
111     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
112       return MT;
113     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
114       return "mips64el-linux-gnu";
115     break;
116   }
117   case llvm::Triple::ppc:
118     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
119       return "powerpc-linux-gnuspe";
120     return "powerpc-linux-gnu";
121   case llvm::Triple::ppcle:
122     return "powerpcle-linux-gnu";
123   case llvm::Triple::ppc64:
124     return "powerpc64-linux-gnu";
125   case llvm::Triple::ppc64le:
126     return "powerpc64le-linux-gnu";
127   case llvm::Triple::sparc:
128     return "sparc-linux-gnu";
129   case llvm::Triple::sparcv9:
130     return "sparc64-linux-gnu";
131   case llvm::Triple::systemz:
132     return "s390x-linux-gnu";
133   }
134   return TargetTriple.str();
135 }
136 
137 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
138   if (Triple.isMIPS()) {
139     if (Triple.isAndroid()) {
140       StringRef CPUName;
141       StringRef ABIName;
142       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
143       if (CPUName == "mips32r6")
144         return "libr6";
145       if (CPUName == "mips32r2")
146         return "libr2";
147     }
148     // lib32 directory has a special meaning on MIPS targets.
149     // It contains N32 ABI binaries. Use this folder if produce
150     // code for N32 ABI only.
151     if (tools::mips::hasMipsAbiArg(Args, "n32"))
152       return "lib32";
153     return Triple.isArch32Bit() ? "lib" : "lib64";
154   }
155 
156   // It happens that only x86, PPC and SPARC use the 'lib32' variant of
157   // oslibdir, and using that variant while targeting other architectures causes
158   // problems because the libraries are laid out in shared system roots that
159   // can't cope with a 'lib32' library search path being considered. So we only
160   // enable them when we know we may need it.
161   //
162   // FIXME: This is a bit of a hack. We should really unify this code for
163   // reasoning about oslibdir spellings with the lib dir spellings in the
164   // GCCInstallationDetector, but that is a more significant refactoring.
165   if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
166       Triple.getArch() == llvm::Triple::sparc)
167     return "lib32";
168 
169   if (Triple.getArch() == llvm::Triple::x86_64 && Triple.isX32())
170     return "libx32";
171 
172   if (Triple.getArch() == llvm::Triple::riscv32)
173     return "lib32";
174 
175   return Triple.isArch32Bit() ? "lib" : "lib64";
176 }
177 
178 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
179     : Generic_ELF(D, Triple, Args) {
180   GCCInstallation.init(Triple, Args);
181   Multilibs = GCCInstallation.getMultilibs();
182   SelectedMultilib = GCCInstallation.getMultilib();
183   llvm::Triple::ArchType Arch = Triple.getArch();
184   std::string SysRoot = computeSysRoot();
185   ToolChain::path_list &PPaths = getProgramPaths();
186 
187   Generic_GCC::PushPPaths(PPaths);
188 
189   Distro Distro(D.getVFS(), Triple);
190 
191   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
192     ExtraOpts.push_back("-z");
193     ExtraOpts.push_back("now");
194   }
195 
196   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
197       Triple.isAndroid()) {
198     ExtraOpts.push_back("-z");
199     ExtraOpts.push_back("relro");
200   }
201 
202   // Android ARM/AArch64 use max-page-size=4096 to reduce VMA usage. Note, lld
203   // from 11 onwards default max-page-size to 65536 for both ARM and AArch64.
204   if ((Triple.isARM() || Triple.isAArch64()) && Triple.isAndroid()) {
205     ExtraOpts.push_back("-z");
206     ExtraOpts.push_back("max-page-size=4096");
207   }
208 
209   if (GCCInstallation.getParentLibPath().find("opt/rh/devtoolset") !=
210       StringRef::npos)
211     // With devtoolset on RHEL, we want to add a bin directory that is relative
212     // to the detected gcc install, because if we are using devtoolset gcc then
213     // we want to use other tools from devtoolset (e.g. ld) instead of the
214     // standard system tools.
215     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
216                      "/../bin").str());
217 
218   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
219     ExtraOpts.push_back("-X");
220 
221   const bool IsAndroid = Triple.isAndroid();
222   const bool IsMips = Triple.isMIPS();
223   const bool IsHexagon = Arch == llvm::Triple::hexagon;
224   const bool IsRISCV = Triple.isRISCV();
225 
226   if (IsMips && !SysRoot.empty())
227     ExtraOpts.push_back("--sysroot=" + SysRoot);
228 
229   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
230   // and the MIPS ABI require .dynsym to be sorted in different ways.
231   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
232   // ABI requires a mapping between the GOT and the symbol table.
233   // Android loader does not support .gnu.hash until API 23.
234   // Hexagon linker/loader does not support .gnu.hash
235   if (!IsMips && !IsHexagon) {
236     if (Distro.IsRedhat() || Distro.IsOpenSUSE() || Distro.IsAlpineLinux() ||
237         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick) ||
238         (IsAndroid && !Triple.isAndroidVersionLT(23)))
239       ExtraOpts.push_back("--hash-style=gnu");
240 
241     if (Distro.IsDebian() || Distro.IsOpenSUSE() ||
242         Distro == Distro::UbuntuLucid || Distro == Distro::UbuntuJaunty ||
243         Distro == Distro::UbuntuKarmic ||
244         (IsAndroid && Triple.isAndroidVersionLT(23)))
245       ExtraOpts.push_back("--hash-style=both");
246   }
247 
248 #ifdef ENABLE_LINKER_BUILD_ID
249   ExtraOpts.push_back("--build-id");
250 #endif
251 
252   if (IsAndroid || Distro.IsOpenSUSE())
253     ExtraOpts.push_back("--enable-new-dtags");
254 
255   // The selection of paths to try here is designed to match the patterns which
256   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
257   // This was determined by running GCC in a fake filesystem, creating all
258   // possible permutations of these directories, and seeing which ones it added
259   // to the link paths.
260   path_list &Paths = getFilePaths();
261 
262   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
263   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
264 
265   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
266 
267   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
268   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
269 
270   if (IsAndroid) {
271     // Android sysroots contain a library directory for each supported OS
272     // version as well as some unversioned libraries in the usual multiarch
273     // directory.
274     unsigned Major;
275     unsigned Minor;
276     unsigned Micro;
277     Triple.getEnvironmentVersion(Major, Minor, Micro);
278     addPathIfExists(D,
279                     SysRoot + "/usr/lib/" + MultiarchTriple + "/" +
280                         llvm::to_string(Major),
281                     Paths);
282   }
283 
284   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
285   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
286   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
287   // this here.
288   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
289       Triple.isArch64Bit())
290     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths);
291   else
292     addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
293   if (IsRISCV) {
294     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
295     addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths);
296     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir + "/" + ABIName, Paths);
297   }
298 
299   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
300 
301   // Similar to the logic for GCC above, if we are currently running Clang
302   // inside of the requested system root, add its parent library path to those
303   // searched.
304   // FIXME: It's not clear whether we should use the driver's installed
305   // directory ('Dir' below) or the ResourceDir.
306   if (StringRef(D.Dir).startswith(SysRoot))
307     addPathIfExists(D, D.Dir + "/../lib", Paths);
308 
309   addPathIfExists(D, SysRoot + "/lib", Paths);
310   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
311 }
312 
313 ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
314   if (getTriple().isAndroid())
315     return ToolChain::RLT_CompilerRT;
316   return Generic_ELF::GetDefaultRuntimeLibType();
317 }
318 
319 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
320   if (getTriple().isAndroid())
321     return ToolChain::CST_Libcxx;
322   return ToolChain::CST_Libstdcxx;
323 }
324 
325 bool Linux::HasNativeLLVMSupport() const { return true; }
326 
327 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
328 
329 Tool *Linux::buildStaticLibTool() const {
330   return new tools::gnutools::StaticLibTool(*this);
331 }
332 
333 Tool *Linux::buildAssembler() const {
334   return new tools::gnutools::Assembler(*this);
335 }
336 
337 std::string Linux::computeSysRoot() const {
338   if (!getDriver().SysRoot.empty())
339     return getDriver().SysRoot;
340 
341   if (getTriple().isAndroid()) {
342     // Android toolchains typically include a sysroot at ../sysroot relative to
343     // the clang binary.
344     const StringRef ClangDir = getDriver().getInstalledDir();
345     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
346     if (getVFS().exists(AndroidSysRootPath))
347       return AndroidSysRootPath;
348   }
349 
350   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
351     return std::string();
352 
353   // Standalone MIPS toolchains use different names for sysroot folder
354   // and put it into different places. Here we try to check some known
355   // variants.
356 
357   const StringRef InstallDir = GCCInstallation.getInstallPath();
358   const StringRef TripleStr = GCCInstallation.getTriple().str();
359   const Multilib &Multilib = GCCInstallation.getMultilib();
360 
361   std::string Path =
362       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
363           .str();
364 
365   if (getVFS().exists(Path))
366     return Path;
367 
368   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
369 
370   if (getVFS().exists(Path))
371     return Path;
372 
373   return std::string();
374 }
375 
376 std::string Linux::getDynamicLinker(const ArgList &Args) const {
377   const llvm::Triple::ArchType Arch = getArch();
378   const llvm::Triple &Triple = getTriple();
379 
380   const Distro Distro(getDriver().getVFS(), Triple);
381 
382   if (Triple.isAndroid())
383     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
384 
385   if (Triple.isMusl()) {
386     std::string ArchName;
387     bool IsArm = false;
388 
389     switch (Arch) {
390     case llvm::Triple::arm:
391     case llvm::Triple::thumb:
392       ArchName = "arm";
393       IsArm = true;
394       break;
395     case llvm::Triple::armeb:
396     case llvm::Triple::thumbeb:
397       ArchName = "armeb";
398       IsArm = true;
399       break;
400     case llvm::Triple::x86:
401       ArchName = "i386";
402       break;
403     case llvm::Triple::x86_64:
404       ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
405       break;
406     default:
407       ArchName = Triple.getArchName().str();
408     }
409     if (IsArm &&
410         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
411          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
412       ArchName += "hf";
413 
414     return "/lib/ld-musl-" + ArchName + ".so.1";
415   }
416 
417   std::string LibDir;
418   std::string Loader;
419 
420   switch (Arch) {
421   default:
422     llvm_unreachable("unsupported architecture");
423 
424   case llvm::Triple::aarch64:
425     LibDir = "lib";
426     Loader = "ld-linux-aarch64.so.1";
427     break;
428   case llvm::Triple::aarch64_be:
429     LibDir = "lib";
430     Loader = "ld-linux-aarch64_be.so.1";
431     break;
432   case llvm::Triple::arm:
433   case llvm::Triple::thumb:
434   case llvm::Triple::armeb:
435   case llvm::Triple::thumbeb: {
436     const bool HF =
437         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
438         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
439 
440     LibDir = "lib";
441     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
442     break;
443   }
444   case llvm::Triple::m68k:
445     LibDir = "lib";
446     Loader = "ld.so.1";
447     break;
448   case llvm::Triple::mips:
449   case llvm::Triple::mipsel:
450   case llvm::Triple::mips64:
451   case llvm::Triple::mips64el: {
452     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
453 
454     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
455 
456     if (tools::mips::isUCLibc(Args))
457       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
458     else if (!Triple.hasEnvironment() &&
459              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
460       Loader =
461           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
462     else
463       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
464 
465     break;
466   }
467   case llvm::Triple::ppc:
468     LibDir = "lib";
469     Loader = "ld.so.1";
470     break;
471   case llvm::Triple::ppcle:
472     LibDir = "lib";
473     Loader = "ld.so.1";
474     break;
475   case llvm::Triple::ppc64:
476     LibDir = "lib64";
477     Loader =
478         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
479     break;
480   case llvm::Triple::ppc64le:
481     LibDir = "lib64";
482     Loader =
483         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
484     break;
485   case llvm::Triple::riscv32: {
486     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
487     LibDir = "lib";
488     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
489     break;
490   }
491   case llvm::Triple::riscv64: {
492     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
493     LibDir = "lib";
494     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
495     break;
496   }
497   case llvm::Triple::sparc:
498   case llvm::Triple::sparcel:
499     LibDir = "lib";
500     Loader = "ld-linux.so.2";
501     break;
502   case llvm::Triple::sparcv9:
503     LibDir = "lib64";
504     Loader = "ld-linux.so.2";
505     break;
506   case llvm::Triple::systemz:
507     LibDir = "lib";
508     Loader = "ld64.so.1";
509     break;
510   case llvm::Triple::x86:
511     LibDir = "lib";
512     Loader = "ld-linux.so.2";
513     break;
514   case llvm::Triple::x86_64: {
515     bool X32 = Triple.isX32();
516 
517     LibDir = X32 ? "libx32" : "lib64";
518     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
519     break;
520   }
521   case llvm::Triple::ve:
522     return "/opt/nec/ve/lib/ld-linux-ve.so.1";
523   }
524 
525   if (Distro == Distro::Exherbo &&
526       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
527        Triple.getVendor() == llvm::Triple::PC))
528     return "/usr/" + Triple.str() + "/lib/" + Loader;
529   return "/" + LibDir + "/" + Loader;
530 }
531 
532 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
533                                       ArgStringList &CC1Args) const {
534   const Driver &D = getDriver();
535   std::string SysRoot = computeSysRoot();
536 
537   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
538     return;
539 
540   // Add 'include' in the resource directory, which is similar to
541   // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
542   // contains some files conflicting with system /usr/include. musl systems
543   // prefer the /usr/include copies which are more relevant.
544   SmallString<128> ResourceDirInclude(D.ResourceDir);
545   llvm::sys::path::append(ResourceDirInclude, "include");
546   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
547       (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
548     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
549 
550   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
551     return;
552 
553   // LOCAL_INCLUDE_DIR
554   addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
555   // TOOL_INCLUDE_DIR
556   AddMultilibIncludeArgs(DriverArgs, CC1Args);
557 
558   // Check for configure-time C include directories.
559   StringRef CIncludeDirs(C_INCLUDE_DIRS);
560   if (CIncludeDirs != "") {
561     SmallVector<StringRef, 5> dirs;
562     CIncludeDirs.split(dirs, ":");
563     for (StringRef dir : dirs) {
564       StringRef Prefix =
565           llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
566       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
567     }
568     return;
569   }
570 
571   // On systems using multiarch and Android, add /usr/include/$triple before
572   // /usr/include.
573   std::string MultiarchIncludeDir = getMultiarchTriple(D, getTriple(), SysRoot);
574   if (!MultiarchIncludeDir.empty() &&
575       D.getVFS().exists(SysRoot + "/usr/include/" + MultiarchIncludeDir))
576     addExternCSystemInclude(DriverArgs, CC1Args,
577                             SysRoot + "/usr/include/" + MultiarchIncludeDir);
578 
579   if (getTriple().getOS() == llvm::Triple::RTEMS)
580     return;
581 
582   // Add an include of '/include' directly. This isn't provided by default by
583   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
584   // add even when Clang is acting as-if it were a system compiler.
585   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
586 
587   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
588 
589   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
590     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
591 }
592 
593 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
594                                      llvm::opt::ArgStringList &CC1Args) const {
595   // We need a detected GCC installation on Linux to provide libstdc++'s
596   // headers in odd Linuxish places.
597   if (!GCCInstallation.isValid())
598     return;
599 
600   // Detect Debian g++-multiarch-incdir.diff.
601   StringRef TripleStr = GCCInstallation.getTriple().str();
602   StringRef DebianMultiarch =
603       GCCInstallation.getTriple().getArch() == llvm::Triple::x86
604           ? "i386-linux-gnu"
605           : TripleStr;
606 
607   // Try generic GCC detection first.
608   if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
609                                                DebianMultiarch))
610     return;
611 
612   StringRef LibDir = GCCInstallation.getParentLibPath();
613   const Multilib &Multilib = GCCInstallation.getMultilib();
614   const GCCVersion &Version = GCCInstallation.getVersion();
615 
616   const std::string LibStdCXXIncludePathCandidates[] = {
617       // Android standalone toolchain has C++ headers in yet another place.
618       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
619       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
620       // without a subdirectory corresponding to the gcc version.
621       LibDir.str() + "/../include/c++",
622       // Cray's gcc installation puts headers under "g++" without a
623       // version suffix.
624       LibDir.str() + "/../include/g++",
625   };
626 
627   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
628     if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
629                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
630       break;
631   }
632 }
633 
634 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
635                                ArgStringList &CC1Args) const {
636   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
637 }
638 
639 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
640                               ArgStringList &CC1Args) const {
641   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
642 }
643 
644 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
645                                 ArgStringList &CC1Args) const {
646   if (GCCInstallation.isValid()) {
647     CC1Args.push_back("-isystem");
648     CC1Args.push_back(DriverArgs.MakeArgString(
649         GCCInstallation.getParentLibPath() + "/../" +
650         GCCInstallation.getTriple().str() + "/include"));
651   }
652 }
653 
654 bool Linux::isPIEDefault() const {
655   return (getTriple().isAndroid() && !getTriple().isAndroidVersionLT(16)) ||
656           getTriple().isMusl() || getSanitizerArgs().requiresPIE();
657 }
658 
659 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
660   // Outline atomics for AArch64 are supported by compiler-rt
661   // and libgcc since 9.3.1
662   assert(getTriple().isAArch64() && "expected AArch64 target!");
663   ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
664   if (RtLib == ToolChain::RLT_CompilerRT)
665     return true;
666   assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
667   if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
668     return false;
669   return true;
670 }
671 
672 bool Linux::isNoExecStackDefault() const {
673     return getTriple().isAndroid();
674 }
675 
676 bool Linux::IsMathErrnoDefault() const {
677   if (getTriple().isAndroid())
678     return false;
679   return Generic_ELF::IsMathErrnoDefault();
680 }
681 
682 SanitizerMask Linux::getSupportedSanitizers() const {
683   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
684   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
685   const bool IsMIPS = getTriple().isMIPS32();
686   const bool IsMIPS64 = getTriple().isMIPS64();
687   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
688                            getTriple().getArch() == llvm::Triple::ppc64le;
689   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
690                          getTriple().getArch() == llvm::Triple::aarch64_be;
691   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
692                          getTriple().getArch() == llvm::Triple::thumb ||
693                          getTriple().getArch() == llvm::Triple::armeb ||
694                          getTriple().getArch() == llvm::Triple::thumbeb;
695   const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
696   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
697   SanitizerMask Res = ToolChain::getSupportedSanitizers();
698   Res |= SanitizerKind::Address;
699   Res |= SanitizerKind::PointerCompare;
700   Res |= SanitizerKind::PointerSubtract;
701   Res |= SanitizerKind::Fuzzer;
702   Res |= SanitizerKind::FuzzerNoLink;
703   Res |= SanitizerKind::KernelAddress;
704   Res |= SanitizerKind::Memory;
705   Res |= SanitizerKind::Vptr;
706   Res |= SanitizerKind::SafeStack;
707   if (IsX86_64 || IsMIPS64 || IsAArch64)
708     Res |= SanitizerKind::DataFlow;
709   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
710       IsRISCV64 || IsSystemZ)
711     Res |= SanitizerKind::Leak;
712   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ)
713     Res |= SanitizerKind::Thread;
714   if (IsX86_64)
715     Res |= SanitizerKind::KernelMemory;
716   if (IsX86 || IsX86_64)
717     Res |= SanitizerKind::Function;
718   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
719       IsPowerPC64)
720     Res |= SanitizerKind::Scudo;
721   if (IsX86_64 || IsAArch64) {
722     Res |= SanitizerKind::HWAddress;
723     Res |= SanitizerKind::KernelHWAddress;
724   }
725   return Res;
726 }
727 
728 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
729                              llvm::opt::ArgStringList &CmdArgs) const {
730   // Add linker option -u__llvm_profile_runtime to cause runtime
731   // initialization module to be linked in.
732   if (needsProfileRT(Args))
733     CmdArgs.push_back(Args.MakeArgString(
734         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
735   ToolChain::addProfileRTLibs(Args, CmdArgs);
736 }
737 
738 llvm::DenormalMode
739 Linux::getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs,
740                                      const JobAction &JA,
741                                      const llvm::fltSemantics *FPType) const {
742   switch (getTriple().getArch()) {
743   case llvm::Triple::x86:
744   case llvm::Triple::x86_64: {
745     std::string Unused;
746     // DAZ and FTZ are turned on in crtfastmath.o
747     if (!DriverArgs.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
748         isFastMathRuntimeAvailable(DriverArgs, Unused))
749       return llvm::DenormalMode::getPreserveSign();
750     return llvm::DenormalMode::getIEEE();
751   }
752   default:
753     return llvm::DenormalMode::getIEEE();
754   }
755 }
756 
757 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
758   for (const auto &Opt : ExtraOpts)
759     CmdArgs.push_back(Opt.c_str());
760 }
761