[Driver] Move detectLibcxxIncludePath to ToolChain
[lldb.git] / clang / lib / Driver / ToolChains / Fuchsia.cpp
1 //===--- Fuchsia.cpp - Fuchsia 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 "Fuchsia.h"
10 #include "CommonArgs.h"
11 #include "clang/Config/config.h"
12 #include "clang/Driver/Compilation.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/SanitizerArgs.h"
17 #include "llvm/Option/ArgList.h"
18 #include "llvm/ProfileData/InstrProf.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/VirtualFileSystem.h"
22
23 using namespace clang::driver;
24 using namespace clang::driver::toolchains;
25 using namespace clang::driver::tools;
26 using namespace clang;
27 using namespace llvm::opt;
28
29 using tools::addMultilibFlag;
30
31 void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
32                                    const InputInfo &Output,
33                                    const InputInfoList &Inputs,
34                                    const ArgList &Args,
35                                    const char *LinkingOutput) const {
36   const toolchains::Fuchsia &ToolChain =
37       static_cast<const toolchains::Fuchsia &>(getToolChain());
38   const Driver &D = ToolChain.getDriver();
39
40   ArgStringList CmdArgs;
41
42   // Silence warning for "clang -g foo.o -o foo"
43   Args.ClaimAllArgs(options::OPT_g_Group);
44   // and "clang -emit-llvm foo.o -o foo"
45   Args.ClaimAllArgs(options::OPT_emit_llvm);
46   // and for "clang -w foo.o -o foo". Other warning options are already
47   // handled somewhere else.
48   Args.ClaimAllArgs(options::OPT_w);
49
50   CmdArgs.push_back("-z");
51   CmdArgs.push_back("max-page-size=4096");
52
53   CmdArgs.push_back("-z");
54   CmdArgs.push_back("now");
55
56   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
57   if (llvm::sys::path::filename(Exec).equals_lower("ld.lld") ||
58       llvm::sys::path::stem(Exec).equals_lower("ld.lld")) {
59     CmdArgs.push_back("-z");
60     CmdArgs.push_back("rodynamic");
61     CmdArgs.push_back("-z");
62     CmdArgs.push_back("separate-loadable-segments");
63     CmdArgs.push_back("--pack-dyn-relocs=relr");
64   }
65
66   if (!D.SysRoot.empty())
67     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
68
69   if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
70     CmdArgs.push_back("-pie");
71
72   if (Args.hasArg(options::OPT_rdynamic))
73     CmdArgs.push_back("-export-dynamic");
74
75   if (Args.hasArg(options::OPT_s))
76     CmdArgs.push_back("-s");
77
78   if (Args.hasArg(options::OPT_r)) {
79     CmdArgs.push_back("-r");
80   } else {
81     CmdArgs.push_back("--build-id");
82     CmdArgs.push_back("--hash-style=gnu");
83   }
84
85   CmdArgs.push_back("--eh-frame-hdr");
86
87   if (Args.hasArg(options::OPT_static))
88     CmdArgs.push_back("-Bstatic");
89   else if (Args.hasArg(options::OPT_shared))
90     CmdArgs.push_back("-shared");
91
92   const SanitizerArgs &SanArgs = ToolChain.getSanitizerArgs();
93
94   if (!Args.hasArg(options::OPT_shared)) {
95     std::string Dyld = D.DyldPrefix;
96     if (SanArgs.needsAsanRt() && SanArgs.needsSharedRt())
97       Dyld += "asan/";
98     if (SanArgs.needsTsanRt() && SanArgs.needsSharedRt())
99       Dyld += "tsan/";
100     Dyld += "ld.so.1";
101     CmdArgs.push_back("-dynamic-linker");
102     CmdArgs.push_back(Args.MakeArgString(Dyld));
103   }
104
105   CmdArgs.push_back("-o");
106   CmdArgs.push_back(Output.getFilename());
107
108   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
109     if (!Args.hasArg(options::OPT_shared)) {
110       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
111     }
112   }
113
114   Args.AddAllArgs(CmdArgs, options::OPT_L);
115   Args.AddAllArgs(CmdArgs, options::OPT_u);
116
117   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
118
119   if (D.isUsingLTO()) {
120     assert(!Inputs.empty() && "Must have at least one input.");
121     addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
122                   D.getLTOMode() == LTOK_Thin);
123   }
124
125   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
126   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
127   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
128   ToolChain.addProfileRTLibs(Args, CmdArgs);
129
130   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
131     if (Args.hasArg(options::OPT_static))
132       CmdArgs.push_back("-Bdynamic");
133
134     if (D.CCCIsCXX()) {
135       if (ToolChain.ShouldLinkCXXStdlib(Args)) {
136         bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
137                                    !Args.hasArg(options::OPT_static);
138         CmdArgs.push_back("--push-state");
139         CmdArgs.push_back("--as-needed");
140         if (OnlyLibstdcxxStatic)
141           CmdArgs.push_back("-Bstatic");
142         ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
143         if (OnlyLibstdcxxStatic)
144           CmdArgs.push_back("-Bdynamic");
145         CmdArgs.push_back("-lm");
146         CmdArgs.push_back("--pop-state");
147       }
148     }
149
150     if (NeedsSanitizerDeps)
151       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
152
153     if (NeedsXRayDeps)
154       linkXRayRuntimeDeps(ToolChain, CmdArgs);
155
156     AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
157
158     if (Args.hasArg(options::OPT_pthread) ||
159         Args.hasArg(options::OPT_pthreads))
160       CmdArgs.push_back("-lpthread");
161
162     if (Args.hasArg(options::OPT_fsplit_stack))
163       CmdArgs.push_back("--wrap=pthread_create");
164
165     if (!Args.hasArg(options::OPT_nolibc))
166       CmdArgs.push_back("-lc");
167   }
168
169   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
170                                          Exec, CmdArgs, Inputs));
171 }
172
173 /// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
174
175 Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
176                  const ArgList &Args)
177     : ToolChain(D, Triple, Args) {
178   getProgramPaths().push_back(getDriver().getInstalledDir());
179   if (getDriver().getInstalledDir() != D.Dir)
180     getProgramPaths().push_back(D.Dir);
181
182   if (!D.SysRoot.empty()) {
183     SmallString<128> P(D.SysRoot);
184     llvm::sys::path::append(P, "lib");
185     getFilePaths().push_back(std::string(P.str()));
186   }
187
188   auto FilePaths = [&](const Multilib &M) -> std::vector<std::string> {
189     std::vector<std::string> FP;
190     if (D.CCCIsCXX()) {
191       if (auto CXXStdlibPath = getCXXStdlibPath()) {
192         SmallString<128> P(*CXXStdlibPath);
193         llvm::sys::path::append(P, M.gccSuffix());
194         FP.push_back(std::string(P.str()));
195       }
196     }
197     return FP;
198   };
199
200   Multilibs.push_back(Multilib());
201   // Use the noexcept variant with -fno-exceptions to avoid the extra overhead.
202   Multilibs.push_back(Multilib("noexcept", {}, {}, 1)
203                           .flag("-fexceptions")
204                           .flag("+fno-exceptions"));
205   // ASan has higher priority because we always want the instrumentated version.
206   Multilibs.push_back(Multilib("asan", {}, {}, 2)
207                           .flag("+fsanitize=address"));
208   // Use the asan+noexcept variant with ASan and -fno-exceptions.
209   Multilibs.push_back(Multilib("asan+noexcept", {}, {}, 3)
210                           .flag("+fsanitize=address")
211                           .flag("-fexceptions")
212                           .flag("+fno-exceptions"));
213   Multilibs.FilterOut([&](const Multilib &M) {
214     std::vector<std::string> RD = FilePaths(M);
215     return std::all_of(RD.begin(), RD.end(), [&](std::string P) {
216       return !getVFS().exists(P);
217     });
218   });
219
220   Multilib::flags_list Flags;
221   addMultilibFlag(
222       Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, true),
223       "fexceptions", Flags);
224   addMultilibFlag(getSanitizerArgs().needsAsanRt(), "fsanitize=address", Flags);
225   Multilibs.setFilePathsCallback(FilePaths);
226
227   if (Multilibs.select(Flags, SelectedMultilib))
228     if (!SelectedMultilib.isDefault())
229       if (const auto &PathsCallback = Multilibs.filePathsCallback())
230         for (const auto &Path : PathsCallback(SelectedMultilib))
231           // Prepend the multilib path to ensure it takes the precedence.
232           getFilePaths().insert(getFilePaths().begin(), Path);
233 }
234
235 std::string Fuchsia::ComputeEffectiveClangTriple(const ArgList &Args,
236                                                  types::ID InputType) const {
237   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
238   return Triple.str();
239 }
240
241 Tool *Fuchsia::buildLinker() const {
242   return new tools::fuchsia::Linker(*this);
243 }
244
245 ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
246     const ArgList &Args) const {
247   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_rtlib_EQ)) {
248     StringRef Value = A->getValue();
249     if (Value != "compiler-rt")
250       getDriver().Diag(clang::diag::err_drv_invalid_rtlib_name)
251           << A->getAsString(Args);
252   }
253
254   return ToolChain::RLT_CompilerRT;
255 }
256
257 ToolChain::CXXStdlibType
258 Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
259   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
260     StringRef Value = A->getValue();
261     if (Value != "libc++")
262       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
263         << A->getAsString(Args);
264   }
265
266   return ToolChain::CST_Libcxx;
267 }
268
269 void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
270                                     ArgStringList &CC1Args,
271                                     Action::OffloadKind) const {
272   if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
273                           options::OPT_fno_use_init_array, true))
274     CC1Args.push_back("-fno-use-init-array");
275 }
276
277 void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
278                                         ArgStringList &CC1Args) const {
279   const Driver &D = getDriver();
280
281   if (DriverArgs.hasArg(options::OPT_nostdinc))
282     return;
283
284   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
285     SmallString<128> P(D.ResourceDir);
286     llvm::sys::path::append(P, "include");
287     addSystemInclude(DriverArgs, CC1Args, P);
288   }
289
290   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
291     return;
292
293   // Check for configure-time C include directories.
294   StringRef CIncludeDirs(C_INCLUDE_DIRS);
295   if (CIncludeDirs != "") {
296     SmallVector<StringRef, 5> dirs;
297     CIncludeDirs.split(dirs, ":");
298     for (StringRef dir : dirs) {
299       StringRef Prefix =
300           llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
301       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
302     }
303     return;
304   }
305
306   if (!D.SysRoot.empty()) {
307     SmallString<128> P(D.SysRoot);
308     llvm::sys::path::append(P, "include");
309     addExternCSystemInclude(DriverArgs, CC1Args, P.str());
310   }
311 }
312
313 void Fuchsia::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
314                                            ArgStringList &CC1Args) const {
315   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
316       DriverArgs.hasArg(options::OPT_nostdincxx))
317     return;
318
319   switch (GetCXXStdlibType(DriverArgs)) {
320   case ToolChain::CST_Libcxx: {
321     SmallString<128> P(getDriver().Dir);
322     llvm::sys::path::append(P, "..", "include", "c++");
323     addSystemInclude(DriverArgs, CC1Args, detectLibcxxIncludePath(P.str()));
324     break;
325   }
326
327   default:
328     llvm_unreachable("invalid stdlib name");
329   }
330 }
331
332 void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
333                                   ArgStringList &CmdArgs) const {
334   switch (GetCXXStdlibType(Args)) {
335   case ToolChain::CST_Libcxx:
336     CmdArgs.push_back("-lc++");
337     break;
338
339   case ToolChain::CST_Libstdcxx:
340     llvm_unreachable("invalid stdlib name");
341   }
342 }
343
344 SanitizerMask Fuchsia::getSupportedSanitizers() const {
345   SanitizerMask Res = ToolChain::getSupportedSanitizers();
346   Res |= SanitizerKind::Address;
347   Res |= SanitizerKind::PointerCompare;
348   Res |= SanitizerKind::PointerSubtract;
349   Res |= SanitizerKind::Fuzzer;
350   Res |= SanitizerKind::FuzzerNoLink;
351   Res |= SanitizerKind::Leak;
352   Res |= SanitizerKind::SafeStack;
353   Res |= SanitizerKind::Scudo;
354   Res |= SanitizerKind::Thread;
355   return Res;
356 }
357
358 SanitizerMask Fuchsia::getDefaultSanitizers() const {
359   SanitizerMask Res;
360   switch (getTriple().getArch()) {
361   case llvm::Triple::aarch64:
362     Res |= SanitizerKind::ShadowCallStack;
363     break;
364   case llvm::Triple::x86_64:
365     Res |= SanitizerKind::SafeStack;
366     break;
367   default:
368     // TODO: Enable SafeStack on RISC-V once tested.
369     break;
370   }
371   return Res;
372 }
373
374 void Fuchsia::addProfileRTLibs(const llvm::opt::ArgList &Args,
375                                llvm::opt::ArgStringList &CmdArgs) const {
376   // Add linker option -u__llvm_profile_runtime to cause runtime
377   // initialization module to be linked in.
378   if (needsProfileRT(Args))
379     CmdArgs.push_back(Args.MakeArgString(
380         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
381   ToolChain::addProfileRTLibs(Args, CmdArgs);
382 }