]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains/Linux.cpp
Merge clang trunk r338150, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains / Linux.cpp
1 //===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Linux.h"
11 #include "Arch/ARM.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "CommonArgs.h"
16 #include "clang/Basic/VirtualFileSystem.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Distro.h"
19 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/ProfileData/InstrProf.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/ScopedPrinter.h"
26 #include <system_error>
27
28 using namespace clang::driver;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32
33 using tools::addPathIfExists;
34
35 /// Get our best guess at the multiarch triple for a target.
36 ///
37 /// Debian-based systems are starting to use a multiarch setup where they use
38 /// a target-triple directory in the library and header search paths.
39 /// Unfortunately, this triple does not align with the vanilla target triple,
40 /// so we provide a rough mapping here.
41 static std::string getMultiarchTriple(const Driver &D,
42                                       const llvm::Triple &TargetTriple,
43                                       StringRef SysRoot) {
44   llvm::Triple::EnvironmentType TargetEnvironment =
45       TargetTriple.getEnvironment();
46   bool IsAndroid = TargetTriple.isAndroid();
47
48   // For most architectures, just use whatever we have rather than trying to be
49   // clever.
50   switch (TargetTriple.getArch()) {
51   default:
52     break;
53
54   // We use the existence of '/lib/<triple>' as a directory to detect some
55   // common linux triples that don't quite match the Clang triple for both
56   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
57   // regardless of what the actual target triple is.
58   case llvm::Triple::arm:
59   case llvm::Triple::thumb:
60     if (IsAndroid) {
61       return "arm-linux-androideabi";
62     } else if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
63       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
64         return "arm-linux-gnueabihf";
65     } else {
66       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
67         return "arm-linux-gnueabi";
68     }
69     break;
70   case llvm::Triple::armeb:
71   case llvm::Triple::thumbeb:
72     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
73       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
74         return "armeb-linux-gnueabihf";
75     } else {
76       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
77         return "armeb-linux-gnueabi";
78     }
79     break;
80   case llvm::Triple::x86:
81     if (IsAndroid)
82       return "i686-linux-android";
83     if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
84       return "i386-linux-gnu";
85     break;
86   case llvm::Triple::x86_64:
87     if (IsAndroid)
88       return "x86_64-linux-android";
89     // We don't want this for x32, otherwise it will match x86_64 libs
90     if (TargetEnvironment != llvm::Triple::GNUX32 &&
91         D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
92       return "x86_64-linux-gnu";
93     break;
94   case llvm::Triple::aarch64:
95     if (IsAndroid)
96       return "aarch64-linux-android";
97     if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
98       return "aarch64-linux-gnu";
99     break;
100   case llvm::Triple::aarch64_be:
101     if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
102       return "aarch64_be-linux-gnu";
103     break;
104   case llvm::Triple::mips:
105     if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
106       return "mips-linux-gnu";
107     break;
108   case llvm::Triple::mipsel:
109     if (IsAndroid)
110       return "mipsel-linux-android";
111     if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
112       return "mipsel-linux-gnu";
113     break;
114   case llvm::Triple::mips64:
115     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
116       return "mips64-linux-gnu";
117     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
118       return "mips64-linux-gnuabi64";
119     break;
120   case llvm::Triple::mips64el:
121     if (IsAndroid)
122       return "mips64el-linux-android";
123     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
124       return "mips64el-linux-gnu";
125     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
126       return "mips64el-linux-gnuabi64";
127     break;
128   case llvm::Triple::ppc:
129     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
130       return "powerpc-linux-gnuspe";
131     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
132       return "powerpc-linux-gnu";
133     break;
134   case llvm::Triple::ppc64:
135     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
136       return "powerpc64-linux-gnu";
137     break;
138   case llvm::Triple::ppc64le:
139     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
140       return "powerpc64le-linux-gnu";
141     break;
142   case llvm::Triple::sparc:
143     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
144       return "sparc-linux-gnu";
145     break;
146   case llvm::Triple::sparcv9:
147     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
148       return "sparc64-linux-gnu";
149     break;
150   case llvm::Triple::systemz:
151     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
152       return "s390x-linux-gnu";
153     break;
154   }
155   return TargetTriple.str();
156 }
157
158 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
159   if (Triple.isMIPS()) {
160     if (Triple.isAndroid()) {
161       StringRef CPUName;
162       StringRef ABIName;
163       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
164       if (CPUName == "mips32r6")
165         return "libr6";
166       if (CPUName == "mips32r2")
167         return "libr2";
168     }
169     // lib32 directory has a special meaning on MIPS targets.
170     // It contains N32 ABI binaries. Use this folder if produce
171     // code for N32 ABI only.
172     if (tools::mips::hasMipsAbiArg(Args, "n32"))
173       return "lib32";
174     return Triple.isArch32Bit() ? "lib" : "lib64";
175   }
176
177   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
178   // using that variant while targeting other architectures causes problems
179   // because the libraries are laid out in shared system roots that can't cope
180   // with a 'lib32' library search path being considered. So we only enable
181   // them when we know we may need it.
182   //
183   // FIXME: This is a bit of a hack. We should really unify this code for
184   // reasoning about oslibdir spellings with the lib dir spellings in the
185   // GCCInstallationDetector, but that is a more significant refactoring.
186   if (Triple.getArch() == llvm::Triple::x86 ||
187       Triple.getArch() == llvm::Triple::ppc)
188     return "lib32";
189
190   if (Triple.getArch() == llvm::Triple::x86_64 &&
191       Triple.getEnvironment() == llvm::Triple::GNUX32)
192     return "libx32";
193
194   if (Triple.getArch() == llvm::Triple::riscv32)
195     return "lib32";
196
197   return Triple.isArch32Bit() ? "lib" : "lib64";
198 }
199
200 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
201                                   const Multilib &Multilib,
202                                   StringRef InstallPath,
203                                   ToolChain::path_list &Paths) {
204   if (const auto &PathsCallback = Multilibs.filePathsCallback())
205     for (const auto &Path : PathsCallback(Multilib))
206       addPathIfExists(D, InstallPath + Path, Paths);
207 }
208
209 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
210     : Generic_ELF(D, Triple, Args) {
211   GCCInstallation.init(Triple, Args);
212   Multilibs = GCCInstallation.getMultilibs();
213   llvm::Triple::ArchType Arch = Triple.getArch();
214   std::string SysRoot = computeSysRoot();
215
216   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
217   // least) put various tools in a triple-prefixed directory off of the parent
218   // of the GCC installation. We use the GCC triple here to ensure that we end
219   // up with tools that support the same amount of cross compiling as the
220   // detected GCC installation. For example, if we find a GCC installation
221   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
222   // used to target i386.
223   // FIXME: This seems unlikely to be Linux-specific.
224   ToolChain::path_list &PPaths = getProgramPaths();
225   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
226                          GCCInstallation.getTriple().str() + "/bin")
227                        .str());
228
229   Distro Distro(D.getVFS());
230
231   if (Distro.IsAlpineLinux()) {
232     ExtraOpts.push_back("-z");
233     ExtraOpts.push_back("now");
234   }
235
236   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux()) {
237     ExtraOpts.push_back("-z");
238     ExtraOpts.push_back("relro");
239   }
240
241   if (GCCInstallation.getParentLibPath().find("opt/rh/devtoolset") !=
242       StringRef::npos)
243     // With devtoolset on RHEL, we want to add a bin directory that is relative
244     // to the detected gcc install, because if we are using devtoolset gcc then
245     // we want to use other tools from devtoolset (e.g. ld) instead of the
246     // standard system tools.
247     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
248                      "/../bin").str());
249
250   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
251     ExtraOpts.push_back("-X");
252
253   const bool IsAndroid = Triple.isAndroid();
254   const bool IsMips = Triple.isMIPS();
255   const bool IsHexagon = Arch == llvm::Triple::hexagon;
256   const bool IsRISCV =
257       Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64;
258
259   if (IsMips && !SysRoot.empty())
260     ExtraOpts.push_back("--sysroot=" + SysRoot);
261
262   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
263   // and the MIPS ABI require .dynsym to be sorted in different ways.
264   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
265   // ABI requires a mapping between the GOT and the symbol table.
266   // Android loader does not support .gnu.hash.
267   // Hexagon linker/loader does not support .gnu.hash
268   if (!IsMips && !IsAndroid && !IsHexagon) {
269     if (Distro.IsRedhat() || Distro.IsOpenSUSE() || Distro.IsAlpineLinux() ||
270         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick))
271       ExtraOpts.push_back("--hash-style=gnu");
272
273     if (Distro.IsDebian() || Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
274         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic)
275       ExtraOpts.push_back("--hash-style=both");
276   }
277
278   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
279     ExtraOpts.push_back("--no-add-needed");
280
281 #ifdef ENABLE_LINKER_BUILD_ID
282   ExtraOpts.push_back("--build-id");
283 #endif
284
285   if (IsAndroid || Distro.IsOpenSUSE())
286     ExtraOpts.push_back("--enable-new-dtags");
287
288   // The selection of paths to try here is designed to match the patterns which
289   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
290   // This was determined by running GCC in a fake filesystem, creating all
291   // possible permutations of these directories, and seeing which ones it added
292   // to the link paths.
293   path_list &Paths = getFilePaths();
294
295   const std::string OSLibDir = getOSLibDir(Triple, Args);
296   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
297
298   // Add the multilib suffixed paths where they are available.
299   if (GCCInstallation.isValid()) {
300     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
301     const std::string &LibPath = GCCInstallation.getParentLibPath();
302     const Multilib &Multilib = GCCInstallation.getMultilib();
303     const MultilibSet &Multilibs = GCCInstallation.getMultilibs();
304
305     // Add toolchain / multilib specific file paths.
306     addMultilibsFilePaths(D, Multilibs, Multilib,
307                           GCCInstallation.getInstallPath(), Paths);
308
309     // Sourcery CodeBench MIPS toolchain holds some libraries under
310     // a biarch-like suffix of the GCC installation.
311     addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
312                     Paths);
313
314     // GCC cross compiling toolchains will install target libraries which ship
315     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
316     // any part of the GCC installation in
317     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
318     // debatable, but is the reality today. We need to search this tree even
319     // when we have a sysroot somewhere else. It is the responsibility of
320     // whomever is doing the cross build targeting a sysroot using a GCC
321     // installation that is *not* within the system root to ensure two things:
322     //
323     //  1) Any DSOs that are linked in from this tree or from the install path
324     //     above must be present on the system root and found via an
325     //     appropriate rpath.
326     //  2) There must not be libraries installed into
327     //     <prefix>/<triple>/<libdir> unless they should be preferred over
328     //     those within the system root.
329     //
330     // Note that this matches the GCC behavior. See the below comment for where
331     // Clang diverges from GCC's behavior.
332     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
333                            OSLibDir + Multilib.osSuffix(),
334                     Paths);
335
336     // If the GCC installation we found is inside of the sysroot, we want to
337     // prefer libraries installed in the parent prefix of the GCC installation.
338     // It is important to *not* use these paths when the GCC installation is
339     // outside of the system root as that can pick up unintended libraries.
340     // This usually happens when there is an external cross compiler on the
341     // host system, and a more minimal sysroot available that is the target of
342     // the cross. Note that GCC does include some of these directories in some
343     // configurations but this seems somewhere between questionable and simply
344     // a bug.
345     if (StringRef(LibPath).startswith(SysRoot)) {
346       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
347       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
348     }
349   }
350
351   // Similar to the logic for GCC above, if we currently running Clang inside
352   // of the requested system root, add its parent library paths to
353   // those searched.
354   // FIXME: It's not clear whether we should use the driver's installed
355   // directory ('Dir' below) or the ResourceDir.
356   if (StringRef(D.Dir).startswith(SysRoot)) {
357     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
358     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
359   }
360
361   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
362   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
363
364   if (IsAndroid) {
365     // Android sysroots contain a library directory for each supported OS
366     // version as well as some unversioned libraries in the usual multiarch
367     // directory.
368     unsigned Major;
369     unsigned Minor;
370     unsigned Micro;
371     Triple.getEnvironmentVersion(Major, Minor, Micro);
372     addPathIfExists(D,
373                     SysRoot + "/usr/lib/" + MultiarchTriple + "/" +
374                         llvm::to_string(Major),
375                     Paths);
376   }
377
378   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
379   addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
380   if (IsRISCV) {
381     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
382     addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths);
383     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir + "/" + ABIName, Paths);
384   }
385
386   // Try walking via the GCC triple path in case of biarch or multiarch GCC
387   // installations with strange symlinks.
388   if (GCCInstallation.isValid()) {
389     addPathIfExists(D,
390                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
391                         "/../../" + OSLibDir,
392                     Paths);
393
394     // Add the 'other' biarch variant path
395     Multilib BiarchSibling;
396     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
397       addPathIfExists(D, GCCInstallation.getInstallPath() +
398                              BiarchSibling.gccSuffix(),
399                       Paths);
400     }
401
402     // See comments above on the multilib variant for details of why this is
403     // included even from outside the sysroot.
404     const std::string &LibPath = GCCInstallation.getParentLibPath();
405     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
406     const Multilib &Multilib = GCCInstallation.getMultilib();
407     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
408                            Multilib.osSuffix(),
409                     Paths);
410
411     // See comments above on the multilib variant for details of why this is
412     // only included from within the sysroot.
413     if (StringRef(LibPath).startswith(SysRoot))
414       addPathIfExists(D, LibPath, Paths);
415   }
416
417   // Similar to the logic for GCC above, if we are currently running Clang
418   // inside of the requested system root, add its parent library path to those
419   // searched.
420   // FIXME: It's not clear whether we should use the driver's installed
421   // directory ('Dir' below) or the ResourceDir.
422   if (StringRef(D.Dir).startswith(SysRoot))
423     addPathIfExists(D, D.Dir + "/../lib", Paths);
424
425   addPathIfExists(D, SysRoot + "/lib", Paths);
426   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
427 }
428
429 bool Linux::HasNativeLLVMSupport() const { return true; }
430
431 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
432
433 Tool *Linux::buildAssembler() const {
434   return new tools::gnutools::Assembler(*this);
435 }
436
437 std::string Linux::computeSysRoot() const {
438   if (!getDriver().SysRoot.empty())
439     return getDriver().SysRoot;
440
441   if (getTriple().isAndroid()) {
442     // Android toolchains typically include a sysroot at ../sysroot relative to
443     // the clang binary.
444     const StringRef ClangDir = getDriver().getInstalledDir();
445     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
446     if (getVFS().exists(AndroidSysRootPath))
447       return AndroidSysRootPath;
448   }
449
450   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
451     return std::string();
452
453   // Standalone MIPS toolchains use different names for sysroot folder
454   // and put it into different places. Here we try to check some known
455   // variants.
456
457   const StringRef InstallDir = GCCInstallation.getInstallPath();
458   const StringRef TripleStr = GCCInstallation.getTriple().str();
459   const Multilib &Multilib = GCCInstallation.getMultilib();
460
461   std::string Path =
462       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
463           .str();
464
465   if (getVFS().exists(Path))
466     return Path;
467
468   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
469
470   if (getVFS().exists(Path))
471     return Path;
472
473   return std::string();
474 }
475
476 std::string Linux::getDynamicLinker(const ArgList &Args) const {
477   const llvm::Triple::ArchType Arch = getArch();
478   const llvm::Triple &Triple = getTriple();
479
480   const Distro Distro(getDriver().getVFS());
481
482   if (Triple.isAndroid())
483     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
484
485   if (Triple.isMusl()) {
486     std::string ArchName;
487     bool IsArm = false;
488
489     switch (Arch) {
490     case llvm::Triple::arm:
491     case llvm::Triple::thumb:
492       ArchName = "arm";
493       IsArm = true;
494       break;
495     case llvm::Triple::armeb:
496     case llvm::Triple::thumbeb:
497       ArchName = "armeb";
498       IsArm = true;
499       break;
500     default:
501       ArchName = Triple.getArchName().str();
502     }
503     if (IsArm &&
504         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
505          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
506       ArchName += "hf";
507
508     return "/lib/ld-musl-" + ArchName + ".so.1";
509   }
510
511   std::string LibDir;
512   std::string Loader;
513
514   switch (Arch) {
515   default:
516     llvm_unreachable("unsupported architecture");
517
518   case llvm::Triple::aarch64:
519     LibDir = "lib";
520     Loader = "ld-linux-aarch64.so.1";
521     break;
522   case llvm::Triple::aarch64_be:
523     LibDir = "lib";
524     Loader = "ld-linux-aarch64_be.so.1";
525     break;
526   case llvm::Triple::arm:
527   case llvm::Triple::thumb:
528   case llvm::Triple::armeb:
529   case llvm::Triple::thumbeb: {
530     const bool HF =
531         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
532         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
533
534     LibDir = "lib";
535     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
536     break;
537   }
538   case llvm::Triple::mips:
539   case llvm::Triple::mipsel:
540   case llvm::Triple::mips64:
541   case llvm::Triple::mips64el: {
542     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
543
544     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
545
546     if (tools::mips::isUCLibc(Args))
547       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
548     else if (!Triple.hasEnvironment() &&
549              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
550       Loader =
551           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
552     else
553       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
554
555     break;
556   }
557   case llvm::Triple::ppc:
558     LibDir = "lib";
559     Loader = "ld.so.1";
560     break;
561   case llvm::Triple::ppc64:
562     LibDir = "lib64";
563     Loader =
564         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
565     break;
566   case llvm::Triple::ppc64le:
567     LibDir = "lib64";
568     Loader =
569         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
570     break;
571   case llvm::Triple::riscv32: {
572     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
573     LibDir = "lib";
574     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
575     break;
576   }
577   case llvm::Triple::riscv64: {
578     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
579     LibDir = "lib";
580     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
581     break;
582   }
583   case llvm::Triple::sparc:
584   case llvm::Triple::sparcel:
585     LibDir = "lib";
586     Loader = "ld-linux.so.2";
587     break;
588   case llvm::Triple::sparcv9:
589     LibDir = "lib64";
590     Loader = "ld-linux.so.2";
591     break;
592   case llvm::Triple::systemz:
593     LibDir = "lib";
594     Loader = "ld64.so.1";
595     break;
596   case llvm::Triple::x86:
597     LibDir = "lib";
598     Loader = "ld-linux.so.2";
599     break;
600   case llvm::Triple::x86_64: {
601     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
602
603     LibDir = X32 ? "libx32" : "lib64";
604     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
605     break;
606   }
607   }
608
609   if (Distro == Distro::Exherbo && (Triple.getVendor() == llvm::Triple::UnknownVendor ||
610                                     Triple.getVendor() == llvm::Triple::PC))
611     return "/usr/" + Triple.str() + "/lib/" + Loader;
612   return "/" + LibDir + "/" + Loader;
613 }
614
615 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
616                                       ArgStringList &CC1Args) const {
617   const Driver &D = getDriver();
618   std::string SysRoot = computeSysRoot();
619
620   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
621     return;
622
623   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
624     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
625
626   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
627     SmallString<128> P(D.ResourceDir);
628     llvm::sys::path::append(P, "include");
629     addSystemInclude(DriverArgs, CC1Args, P);
630   }
631
632   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
633     return;
634
635   // Check for configure-time C include directories.
636   StringRef CIncludeDirs(C_INCLUDE_DIRS);
637   if (CIncludeDirs != "") {
638     SmallVector<StringRef, 5> dirs;
639     CIncludeDirs.split(dirs, ":");
640     for (StringRef dir : dirs) {
641       StringRef Prefix =
642           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
643       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
644     }
645     return;
646   }
647
648   // Lacking those, try to detect the correct set of system includes for the
649   // target triple.
650
651   // Add include directories specific to the selected multilib set and multilib.
652   if (GCCInstallation.isValid()) {
653     const auto &Callback = Multilibs.includeDirsCallback();
654     if (Callback) {
655       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
656         addExternCSystemIncludeIfExists(
657             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
658     }
659   }
660
661   // Implement generic Debian multiarch support.
662   const StringRef X86_64MultiarchIncludeDirs[] = {
663       "/usr/include/x86_64-linux-gnu",
664
665       // FIXME: These are older forms of multiarch. It's not clear that they're
666       // in use in any released version of Debian, so we should consider
667       // removing them.
668       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
669   const StringRef X86MultiarchIncludeDirs[] = {
670       "/usr/include/i386-linux-gnu",
671
672       // FIXME: These are older forms of multiarch. It's not clear that they're
673       // in use in any released version of Debian, so we should consider
674       // removing them.
675       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
676       "/usr/include/i486-linux-gnu"};
677   const StringRef AArch64MultiarchIncludeDirs[] = {
678       "/usr/include/aarch64-linux-gnu"};
679   const StringRef ARMMultiarchIncludeDirs[] = {
680       "/usr/include/arm-linux-gnueabi"};
681   const StringRef ARMHFMultiarchIncludeDirs[] = {
682       "/usr/include/arm-linux-gnueabihf"};
683   const StringRef ARMEBMultiarchIncludeDirs[] = {
684       "/usr/include/armeb-linux-gnueabi"};
685   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
686       "/usr/include/armeb-linux-gnueabihf"};
687   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
688   const StringRef MIPSELMultiarchIncludeDirs[] = {
689       "/usr/include/mipsel-linux-gnu"};
690   const StringRef MIPS64MultiarchIncludeDirs[] = {
691       "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
692   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
693       "/usr/include/mips64el-linux-gnu",
694       "/usr/include/mips64el-linux-gnuabi64"};
695   const StringRef PPCMultiarchIncludeDirs[] = {
696       "/usr/include/powerpc-linux-gnu"};
697   const StringRef PPC64MultiarchIncludeDirs[] = {
698       "/usr/include/powerpc64-linux-gnu"};
699   const StringRef PPC64LEMultiarchIncludeDirs[] = {
700       "/usr/include/powerpc64le-linux-gnu"};
701   const StringRef SparcMultiarchIncludeDirs[] = {
702       "/usr/include/sparc-linux-gnu"};
703   const StringRef Sparc64MultiarchIncludeDirs[] = {
704       "/usr/include/sparc64-linux-gnu"};
705   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
706       "/usr/include/s390x-linux-gnu"};
707   ArrayRef<StringRef> MultiarchIncludeDirs;
708   switch (getTriple().getArch()) {
709   case llvm::Triple::x86_64:
710     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
711     break;
712   case llvm::Triple::x86:
713     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
714     break;
715   case llvm::Triple::aarch64:
716   case llvm::Triple::aarch64_be:
717     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
718     break;
719   case llvm::Triple::arm:
720   case llvm::Triple::thumb:
721     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
722       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
723     else
724       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
725     break;
726   case llvm::Triple::armeb:
727   case llvm::Triple::thumbeb:
728     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
729       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
730     else
731       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
732     break;
733   case llvm::Triple::mips:
734     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
735     break;
736   case llvm::Triple::mipsel:
737     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
738     break;
739   case llvm::Triple::mips64:
740     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
741     break;
742   case llvm::Triple::mips64el:
743     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
744     break;
745   case llvm::Triple::ppc:
746     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
747     break;
748   case llvm::Triple::ppc64:
749     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
750     break;
751   case llvm::Triple::ppc64le:
752     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
753     break;
754   case llvm::Triple::sparc:
755     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
756     break;
757   case llvm::Triple::sparcv9:
758     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
759     break;
760   case llvm::Triple::systemz:
761     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
762     break;
763   default:
764     break;
765   }
766
767   const std::string AndroidMultiarchIncludeDir =
768       std::string("/usr/include/") +
769       getMultiarchTriple(D, getTriple(), SysRoot);
770   const StringRef AndroidMultiarchIncludeDirs[] = {AndroidMultiarchIncludeDir};
771   if (getTriple().isAndroid())
772     MultiarchIncludeDirs = AndroidMultiarchIncludeDirs;
773
774   for (StringRef Dir : MultiarchIncludeDirs) {
775     if (D.getVFS().exists(SysRoot + Dir)) {
776       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
777       break;
778     }
779   }
780
781   if (getTriple().getOS() == llvm::Triple::RTEMS)
782     return;
783
784   // Add an include of '/include' directly. This isn't provided by default by
785   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
786   // add even when Clang is acting as-if it were a system compiler.
787   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
788
789   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
790 }
791
792 static std::string DetectLibcxxIncludePath(StringRef base) {
793   std::error_code EC;
794   int MaxVersion = 0;
795   std::string MaxVersionString = "";
796   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
797        LI = LI.increment(EC)) {
798     StringRef VersionText = llvm::sys::path::filename(LI->path());
799     int Version;
800     if (VersionText[0] == 'v' &&
801         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
802       if (Version > MaxVersion) {
803         MaxVersion = Version;
804         MaxVersionString = VersionText;
805       }
806     }
807   }
808   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
809 }
810
811 void Linux::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
812                                   llvm::opt::ArgStringList &CC1Args) const {
813   const std::string& SysRoot = computeSysRoot();
814   const std::string LibCXXIncludePathCandidates[] = {
815       DetectLibcxxIncludePath(getDriver().ResourceDir + "/include/c++"),
816       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
817       // If this is a development, non-installed, clang, libcxx will
818       // not be found at ../include/c++ but it likely to be found at
819       // one of the following two locations:
820       DetectLibcxxIncludePath(SysRoot + "/usr/local/include/c++"),
821       DetectLibcxxIncludePath(SysRoot + "/usr/include/c++") };
822   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
823     if (IncludePath.empty() || !getVFS().exists(IncludePath))
824       continue;
825     // Use the first candidate that exists.
826     addSystemInclude(DriverArgs, CC1Args, IncludePath);
827     return;
828   }
829 }
830
831 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
832                                      llvm::opt::ArgStringList &CC1Args) const {
833   // We need a detected GCC installation on Linux to provide libstdc++'s
834   // headers.
835   if (!GCCInstallation.isValid())
836     return;
837
838   // By default, look for the C++ headers in an include directory adjacent to
839   // the lib directory of the GCC installation. Note that this is expect to be
840   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
841   StringRef LibDir = GCCInstallation.getParentLibPath();
842   StringRef InstallDir = GCCInstallation.getInstallPath();
843   StringRef TripleStr = GCCInstallation.getTriple().str();
844   const Multilib &Multilib = GCCInstallation.getMultilib();
845   const std::string GCCMultiarchTriple = getMultiarchTriple(
846       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
847   const std::string TargetMultiarchTriple =
848       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
849   const GCCVersion &Version = GCCInstallation.getVersion();
850
851   // The primary search for libstdc++ supports multiarch variants.
852   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
853                                "/c++/" + Version.Text, TripleStr,
854                                GCCMultiarchTriple, TargetMultiarchTriple,
855                                Multilib.includeSuffix(), DriverArgs, CC1Args))
856     return;
857
858   // Otherwise, fall back on a bunch of options which don't use multiarch
859   // layouts for simplicity.
860   const std::string LibStdCXXIncludePathCandidates[] = {
861       // Gentoo is weird and places its headers inside the GCC install,
862       // so if the first attempt to find the headers fails, try these patterns.
863       InstallDir.str() + "/include/g++-v" + Version.Text,
864       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
865           Version.MinorStr,
866       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
867       // Android standalone toolchain has C++ headers in yet another place.
868       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
869       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
870       // without a subdirectory corresponding to the gcc version.
871       LibDir.str() + "/../include/c++",
872   };
873
874   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
875     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
876                                  /*GCCMultiarchTriple*/ "",
877                                  /*TargetMultiarchTriple*/ "",
878                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
879       break;
880   }
881 }
882
883 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
884                                ArgStringList &CC1Args) const {
885   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
886 }
887
888 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
889                                 ArgStringList &CC1Args) const {
890   if (GCCInstallation.isValid()) {
891     CC1Args.push_back("-isystem");
892     CC1Args.push_back(DriverArgs.MakeArgString(
893         GCCInstallation.getParentLibPath() + "/../" +
894         GCCInstallation.getTriple().str() + "/include"));
895   }
896 }
897
898 bool Linux::isPIEDefault() const {
899   return (getTriple().isAndroid() && !getTriple().isAndroidVersionLT(16)) ||
900           getTriple().isMusl() || getSanitizerArgs().requiresPIE();
901 }
902
903 SanitizerMask Linux::getSupportedSanitizers() const {
904   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
905   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
906   const bool IsMIPS = getTriple().isMIPS32();
907   const bool IsMIPS64 = getTriple().isMIPS64();
908   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
909                            getTriple().getArch() == llvm::Triple::ppc64le;
910   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
911                          getTriple().getArch() == llvm::Triple::aarch64_be;
912   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
913                          getTriple().getArch() == llvm::Triple::thumb ||
914                          getTriple().getArch() == llvm::Triple::armeb ||
915                          getTriple().getArch() == llvm::Triple::thumbeb;
916   SanitizerMask Res = ToolChain::getSupportedSanitizers();
917   Res |= SanitizerKind::Address;
918   Res |= SanitizerKind::Fuzzer;
919   Res |= SanitizerKind::FuzzerNoLink;
920   Res |= SanitizerKind::KernelAddress;
921   Res |= SanitizerKind::Memory;
922   Res |= SanitizerKind::Vptr;
923   Res |= SanitizerKind::SafeStack;
924   if (IsX86_64 || IsMIPS64 || IsAArch64)
925     Res |= SanitizerKind::DataFlow;
926   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64)
927     Res |= SanitizerKind::Leak;
928   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
929     Res |= SanitizerKind::Thread;
930   if (IsX86_64 || IsMIPS64)
931     Res |= SanitizerKind::Efficiency;
932   if (IsX86 || IsX86_64)
933     Res |= SanitizerKind::Function;
934   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
935       IsPowerPC64)
936     Res |= SanitizerKind::Scudo;
937   if (IsX86_64 || IsAArch64) {
938     Res |= SanitizerKind::HWAddress;
939     Res |= SanitizerKind::KernelHWAddress;
940   }
941   return Res;
942 }
943
944 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
945                              llvm::opt::ArgStringList &CmdArgs) const {
946   if (!needsProfileRT(Args)) return;
947
948   // Add linker option -u__llvm_runtime_variable to cause runtime
949   // initialization module to be linked in.
950   if (!Args.hasArg(options::OPT_coverage))
951     CmdArgs.push_back(Args.MakeArgString(
952         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
953   ToolChain::addProfileRTLibs(Args, CmdArgs);
954 }