clang 23.0.0git
WebAssembly.cpp
Go to the documentation of this file.
1//===--- WebAssembly.cpp - WebAssembly ToolChain Implementation -*- 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 "WebAssembly.h"
10#include "Gnu.h"
11#include "clang/Config/config.h"
14#include "clang/Driver/Driver.h"
16#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_STRING
17#include "llvm/Option/ArgList.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/VirtualFileSystem.h"
21
22using namespace clang::driver;
23using namespace clang::driver::tools;
24using namespace clang::driver::toolchains;
25using namespace clang;
26using namespace llvm::opt;
27
28/// Following the conventions in https://wiki.debian.org/Multiarch/Tuples,
29/// we remove the vendor field to form the multiarch triple.
30std::string WebAssembly::getMultiarchTriple(const Driver &D,
31 const llvm::Triple &TargetTriple,
32 StringRef SysRoot) const {
33 return (TargetTriple.getArchName() + "-" +
34 TargetTriple.getOSAndEnvironmentName()).str();
35}
36
37/// Returns a directory name in which separate objects compile with/without
38/// exceptions may lie. This is used both for `#include` paths as well as lib
39/// paths.
40static std::string GetCXXExceptionsDir(const ArgList &DriverArgs) {
41 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions))
42 return "eh";
43 return "noeh";
44}
45
46std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
48 if (const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
49 StringRef UseLinker = A->getValue();
50 if (!UseLinker.empty()) {
51 if (llvm::sys::path::is_absolute(UseLinker) &&
52 llvm::sys::fs::can_execute(UseLinker))
53 return std::string(UseLinker);
54
55 // Interpret 'lld' as explicitly requesting `wasm-ld`, so look for that
56 // linker. Note that for `wasm32-wasip2` this overrides the default linker
57 // of `wasm-component-ld`.
58 if (UseLinker == "lld") {
59 return ToolChain.GetProgramPath("wasm-ld");
60 }
61
62 // Allow 'ld' as an alias for the default linker
63 if (UseLinker != "ld")
64 ToolChain.getDriver().Diag(diag::err_drv_invalid_linker_name)
65 << A->getAsString(Args);
66 }
67 }
68
70}
71
72static bool TargetBuildsComponents(const llvm::Triple &TargetTriple) {
73 // WASIp2 and above are all based on components, so test for WASI but exclude
74 // the original `wasi` target in addition to the `wasip1` name.
75 return TargetTriple.isOSWASI() && TargetTriple.getOSName() != "wasip1" &&
76 TargetTriple.getOSName() != "wasi";
77}
78
79static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args) {
80 bool WantsPthread =
81 Args.hasFlag(options::OPT_pthread, options::OPT_no_pthread, false);
82
83 // If the WASI environment is "threads" then enable pthreads support
84 // without requiring -pthread, in order to prevent user error
85 if (Triple.isOSWASI() && Triple.getEnvironmentName() == "threads")
86 WantsPthread = true;
87
88 return WantsPthread;
89}
90
91static bool WantsLibcallThreadContext(const llvm::Triple &Triple,
92 const ArgList &Args) {
93 return Triple.getOS() == llvm::Triple::WASIp3;
94}
95
97 const InputInfo &Output,
98 const InputInfoList &Inputs,
99 const ArgList &Args,
100 const char *LinkingOutput) const {
101
103 const char *Linker = Args.MakeArgString(getLinkerPath(Args));
104 ArgStringList CmdArgs;
105
106 CmdArgs.push_back("-m");
107 if (ToolChain.getTriple().isArch64Bit())
108 CmdArgs.push_back("wasm64");
109 else
110 CmdArgs.push_back("wasm32");
111
112 if (Args.hasArg(options::OPT_s))
113 CmdArgs.push_back("--strip-all");
114
115 // On `wasip2` the default linker is `wasm-component-ld` which wraps the
116 // execution of `wasm-ld`. Find `wasm-ld` and pass it as an argument of where
117 // to find it to avoid it needing to hunt and rediscover or search `PATH` for
118 // where it is.
119 if (llvm::sys::path::stem(Linker).ends_with_insensitive(
120 "wasm-component-ld")) {
121 CmdArgs.push_back("--wasm-ld-path");
122 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetProgramPath("wasm-ld")));
123 }
124
125 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
126
127 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
128
129 bool IsCommand = true;
130 const char *Crt1;
131 const char *Entry = nullptr;
132
133 // When -shared is specified, use the reactor exec model unless
134 // specified otherwise.
135 if (Args.hasArg(options::OPT_shared))
136 IsCommand = false;
137
138 if (const Arg *A = Args.getLastArg(options::OPT_mexec_model_EQ)) {
139 StringRef CM = A->getValue();
140 if (CM == "command") {
141 IsCommand = true;
142 } else if (CM == "reactor") {
143 IsCommand = false;
144 } else {
145 ToolChain.getDriver().Diag(diag::err_drv_invalid_argument_to_option)
146 << CM << A->getOption().getName();
147 }
148 }
149
150 if (IsCommand) {
151 // If crt1-command.o exists, it supports new-style commands, so use it.
152 // Otherwise, use the old crt1.o. This is a temporary transition measure.
153 // Once WASI libc no longer needs to support LLVM versions which lack
154 // support for new-style command, it can make crt1.o the same as
155 // crt1-command.o. And once LLVM no longer needs to support WASI libc
156 // versions before that, it can switch to using crt1-command.o.
157 Crt1 = "crt1.o";
158 if (ToolChain.GetFilePath("crt1-command.o") != "crt1-command.o")
159 Crt1 = "crt1-command.o";
160 } else {
161 Crt1 = "crt1-reactor.o";
162 Entry = "_initialize";
163 }
164
165 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
166 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(Crt1)));
167 if (Entry) {
168 CmdArgs.push_back(Args.MakeArgString("--entry"));
169 CmdArgs.push_back(Args.MakeArgString(Entry));
170 }
171
172 if (Args.hasArg(options::OPT_shared))
173 CmdArgs.push_back(Args.MakeArgString("-shared"));
174
175 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
176
178 CmdArgs.push_back("--libcall-thread-context");
179
180 if (WantsPthread(ToolChain.getTriple(), Args))
181 CmdArgs.push_back("--shared-memory");
182
183 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
185 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
186
187 if (WantsPthread(ToolChain.getTriple(), Args))
188 CmdArgs.push_back("-lpthread");
189
190 CmdArgs.push_back("-lc");
191 AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
192 }
193
194 ToolChain.addProfileRTLibs(Args, CmdArgs);
195
196 CmdArgs.push_back("-o");
197 CmdArgs.push_back(Output.getFilename());
198
199 // Don't use wasm-opt by default on `wasip2` as it doesn't have support for
200 // components at this time. Retain the historical default otherwise, though,
201 // of running `wasm-opt` by default.
202 bool WasmOptDefault = !TargetBuildsComponents(ToolChain.getTriple());
203 bool RunWasmOpt = Args.hasFlag(options::OPT_wasm_opt,
204 options::OPT_no_wasm_opt, WasmOptDefault);
205
206 // If wasm-opt is enabled and optimizations are happening look for the
207 // `wasm-opt` program. If it's not found auto-disable it.
208 std::string WasmOptPath;
209 if (RunWasmOpt && Args.getLastArg(options::OPT_O_Group)) {
210 WasmOptPath = ToolChain.GetProgramPath("wasm-opt");
211 if (WasmOptPath == "wasm-opt") {
212 WasmOptPath = {};
213 }
214 }
215
216 if (!WasmOptPath.empty()) {
217 CmdArgs.push_back("--keep-section=target_features");
218 }
219
220 C.addCommand(std::make_unique<Command>(JA, *this,
222 Linker, CmdArgs, Inputs, Output));
223
224 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
225 if (!WasmOptPath.empty()) {
226 StringRef OOpt = "s";
227 if (A->getOption().matches(options::OPT_O4) ||
228 A->getOption().matches(options::OPT_Ofast))
229 OOpt = "4";
230 else if (A->getOption().matches(options::OPT_O0))
231 OOpt = "0";
232 else if (A->getOption().matches(options::OPT_O))
233 OOpt = A->getValue();
234
235 if (OOpt != "0") {
236 const char *WasmOpt = Args.MakeArgString(WasmOptPath);
237 ArgStringList OptArgs;
238 OptArgs.push_back(Output.getFilename());
239 OptArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
240 OptArgs.push_back("-o");
241 OptArgs.push_back(Output.getFilename());
242 C.addCommand(std::make_unique<Command>(
243 JA, *this, ResponseFileSupport::AtFileCurCP(), WasmOpt, OptArgs,
244 Inputs, Output));
245 }
246 }
247 }
248}
249
250/// Append `Dir` to `Paths`, but also include the LTO directories before that if
251/// LTO is eanbled.
253 const std::string &Dir) {
254 if (D.isUsingLTO()) {
255 // The version allows the path to be keyed to the specific version of
256 // LLVM in used, as the bitcode format is not stable.
257 Paths.push_back(Dir + "/llvm-lto/" LLVM_VERSION_STRING);
258 }
259 Paths.push_back(Dir);
260}
261
262WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
263 const llvm::opt::ArgList &Args)
264 : ToolChain(D, Triple, Args) {
265
266 assert(Triple.isArch32Bit() != Triple.isArch64Bit());
267
268 getProgramPaths().push_back(getDriver().Dir);
269
270 auto SysRoot = getDriver().SysRoot;
271 if (getTriple().getOS() == llvm::Triple::UnknownOS) {
272 // Theoretically an "unknown" OS should mean no standard libraries, however
273 // it could also mean that a custom set of libraries is in use, so just add
274 // /lib to the search path. Disable multiarch in this case, to discourage
275 // paths containing "unknown" from acquiring meanings.
276 getFilePaths().push_back(SysRoot + "/lib");
277 } else {
278 const std::string MultiarchTriple =
279 getMultiarchTriple(getDriver(), Triple, SysRoot);
280 std::string TripleLibDir = SysRoot + "/lib/" + MultiarchTriple;
281 // Allow sysroots to segregate objects based on whether exceptions are
282 // enabled or not. This is intended to assist with distribution of pre-built
283 // sysroots that contain libraries that are capable of producing binaries
284 // entirely without exception-handling instructions but also with if
285 // exceptions are enabled, for example.
286 AppendLibDirAndLTODir(getFilePaths(), D,
287 TripleLibDir + "/" + GetCXXExceptionsDir(Args));
288 AppendLibDirAndLTODir(getFilePaths(), D, TripleLibDir);
289 }
290
291 if (getTriple().getOS() == llvm::Triple::WASI) {
292 D.Diag(diag::warn_drv_deprecated_custom)
293 << "--target=wasm32-wasi"
294 << "use --target=wasm32-wasip1 instead";
295 }
296}
297
298const char *WebAssembly::getDefaultLinker() const {
300 return "wasm-component-ld";
301 return "wasm-ld";
302}
303
304bool WebAssembly::IsMathErrnoDefault() const { return false; }
305
306bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
307
308bool WebAssembly::UseObjCMixedDispatch() const { return true; }
309
310bool WebAssembly::isPICDefault() const { return false; }
311
312bool WebAssembly::isPIEDefault(const llvm::opt::ArgList &Args) const {
313 return false;
314}
315
316bool WebAssembly::isPICDefaultForced() const { return false; }
317
318bool WebAssembly::hasBlocksRuntime() const { return false; }
319
320// TODO: Support profiling.
321bool WebAssembly::SupportsProfiling() const { return false; }
322
323bool WebAssembly::HasNativeLLVMSupport() const { return true; }
324
325void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
326 ArgStringList &CC1Args,
327 Action::OffloadKind) const {
328 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
329 options::OPT_fno_use_init_array, true))
330 CC1Args.push_back("-fno-use-init-array");
331
332 // '-pthread' implies atomics, bulk-memory, mutable-globals, and sign-ext
333 if (WantsPthread(getTriple(), DriverArgs)) {
334 if (DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics,
335 false))
336 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
337 << "-pthread"
338 << "-mno-atomics";
339 if (DriverArgs.hasFlag(options::OPT_mno_bulk_memory,
340 options::OPT_mbulk_memory, false))
341 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
342 << "-pthread"
343 << "-mno-bulk-memory";
344 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
345 options::OPT_mmutable_globals, false))
346 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
347 << "-pthread"
348 << "-mno-mutable-globals";
349 if (DriverArgs.hasFlag(options::OPT_mno_sign_ext, options::OPT_msign_ext,
350 false))
351 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
352 << "-pthread"
353 << "-mno-sign-ext";
354 CC1Args.push_back("-target-feature");
355 CC1Args.push_back("+atomics");
356 CC1Args.push_back("-target-feature");
357 CC1Args.push_back("+bulk-memory");
358 CC1Args.push_back("-target-feature");
359 CC1Args.push_back("+mutable-globals");
360 CC1Args.push_back("-target-feature");
361 CC1Args.push_back("+sign-ext");
362 }
363
364 if (!DriverArgs.hasFlag(options::OPT_mmutable_globals,
365 options::OPT_mno_mutable_globals, false)) {
366 // -fPIC implies +mutable-globals because the PIC ABI used by the linker
367 // depends on importing and exporting mutable globals.
368 llvm::Reloc::Model RelocationModel;
369 unsigned PICLevel;
370 bool IsPIE;
371 std::tie(RelocationModel, PICLevel, IsPIE) =
372 ParsePICArgs(*this, DriverArgs);
373 if (RelocationModel == llvm::Reloc::PIC_) {
374 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
375 options::OPT_mmutable_globals, false)) {
376 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
377 << "-fPIC"
378 << "-mno-mutable-globals";
379 }
380 CC1Args.push_back("-target-feature");
381 CC1Args.push_back("+mutable-globals");
382 }
383 }
384
385 bool HasBannedIncompatibleOptionsForWasmEHSjLj = false;
386 bool HasEnabledFeaturesForWasmEHSjLj = false;
387
388 // Bans incompatible options for Wasm EH / SjLj. We don't allow using
389 // different modes for EH and SjLj.
390 auto BanIncompatibleOptionsForWasmEHSjLj = [&](StringRef CurOption) {
391 if (HasBannedIncompatibleOptionsForWasmEHSjLj)
392 return;
393 HasBannedIncompatibleOptionsForWasmEHSjLj = true;
394 if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
395 options::OPT_mexception_handing, false))
396 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
397 << CurOption << "-mno-exception-handling";
398 // The standardized Wasm EH spec requires multivalue and reference-types.
399 if (DriverArgs.hasFlag(options::OPT_mno_multivalue,
400 options::OPT_mmultivalue, false))
401 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
402 << CurOption << "-mno-multivalue";
403 if (DriverArgs.hasFlag(options::OPT_mno_reference_types,
404 options::OPT_mreference_types, false))
405 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
406 << CurOption << "-mno-reference-types";
407
408 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
409 for (const auto *Option :
410 {"-enable-emscripten-cxx-exceptions", "-enable-emscripten-sjlj",
411 "-emscripten-cxx-exceptions-allowed"}) {
412 if (StringRef(A->getValue(0)) == Option)
413 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
414 << CurOption << Option;
415 }
416 }
417 };
418
419 // Enable necessary features for Wasm EH / SjLj in the backend.
420 auto EnableFeaturesForWasmEHSjLj = [&]() {
421 if (HasEnabledFeaturesForWasmEHSjLj)
422 return;
423 HasEnabledFeaturesForWasmEHSjLj = true;
424 CC1Args.push_back("-target-feature");
425 CC1Args.push_back("+exception-handling");
426 // The standardized Wasm EH spec requires multivalue and reference-types.
427 CC1Args.push_back("-target-feature");
428 CC1Args.push_back("+multivalue");
429 CC1Args.push_back("-target-feature");
430 CC1Args.push_back("+reference-types");
431 // Backend needs '-exception-model=wasm' to use Wasm EH instructions
432 CC1Args.push_back("-exception-model=wasm");
433 };
434
435 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions)) {
436 BanIncompatibleOptionsForWasmEHSjLj("-fwasm-exceptions");
437 EnableFeaturesForWasmEHSjLj();
438 // Backend needs -wasm-enable-eh to enable Wasm EH
439 CC1Args.push_back("-mllvm");
440 CC1Args.push_back("-wasm-enable-eh");
441 }
442
443 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
444 StringRef Opt = A->getValue(0);
445 if (Opt.starts_with("-emscripten-cxx-exceptions-allowed")) {
446 // '-mllvm -emscripten-cxx-exceptions-allowed' should be used with
447 // '-mllvm -enable-emscripten-cxx-exceptions'
448 bool EmEHArgExists = false;
449 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
450 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions") {
451 EmEHArgExists = true;
452 break;
453 }
454 }
455 if (!EmEHArgExists)
456 getDriver().Diag(diag::err_drv_argument_only_allowed_with)
457 << "-mllvm -emscripten-cxx-exceptions-allowed"
458 << "-mllvm -enable-emscripten-cxx-exceptions";
459
460 // Prevent functions specified in -emscripten-cxx-exceptions-allowed list
461 // from being inlined before reaching the wasm backend.
462 StringRef FuncNamesStr = Opt.split('=').second;
463 SmallVector<StringRef, 4> FuncNames;
464 FuncNamesStr.split(FuncNames, ',');
465 for (auto Name : FuncNames) {
466 CC1Args.push_back("-mllvm");
467 CC1Args.push_back(DriverArgs.MakeArgString("--force-attribute=" + Name +
468 ":noinline"));
469 }
470 }
471
472 for (const auto *Option :
473 {"-wasm-enable-eh", "-wasm-enable-sjlj", "-wasm-use-legacy-eh"}) {
474 if (Opt.starts_with(Option)) {
475 BanIncompatibleOptionsForWasmEHSjLj(Option);
476 EnableFeaturesForWasmEHSjLj();
477 }
478 }
479 }
480}
481
484}
485
487WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
488 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
489 StringRef Value = A->getValue();
490 if (Value == "libc++")
492 else if (Value == "libstdc++")
494 else
495 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
496 << A->getAsString(Args);
497 }
499}
500
501void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
502 ArgStringList &CC1Args) const {
503 if (DriverArgs.hasArg(options::OPT_nostdinc))
504 return;
505
506 const Driver &D = getDriver();
507
508 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
509 SmallString<128> P(D.ResourceDir);
510 llvm::sys::path::append(P, "include");
511 addSystemInclude(DriverArgs, CC1Args, P);
512 }
513
514 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
515 return;
516
517 // Check for configure-time C include directories.
518 StringRef CIncludeDirs(C_INCLUDE_DIRS);
519 if (CIncludeDirs != "") {
520 SmallVector<StringRef, 5> dirs;
521 CIncludeDirs.split(dirs, ":");
522 for (StringRef dir : dirs) {
523 StringRef Prefix =
524 llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
525 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
526 }
527 return;
528 }
529
530 if (getTriple().getOS() != llvm::Triple::UnknownOS) {
531 const std::string MultiarchTriple =
532 getMultiarchTriple(D, getTriple(), D.SysRoot);
533 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include/" + MultiarchTriple);
534 }
535 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
536}
537
538void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
539 ArgStringList &CC1Args) const {
540
541 if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdinc,
542 options::OPT_nostdincxx))
543 return;
544
545 switch (GetCXXStdlibType(DriverArgs)) {
547 addLibCxxIncludePaths(DriverArgs, CC1Args);
548 break;
550 addLibStdCXXIncludePaths(DriverArgs, CC1Args);
551 break;
552 }
553}
554
555void WebAssembly::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
556 llvm::opt::ArgStringList &CmdArgs) const {
557
558 switch (GetCXXStdlibType(Args)) {
560 CmdArgs.push_back("-lc++");
561 if (Args.hasArg(options::OPT_fexperimental_library))
562 CmdArgs.push_back("-lc++experimental");
563 CmdArgs.push_back("-lc++abi");
564 break;
566 CmdArgs.push_back("-lstdc++");
567 break;
568 }
569}
570
571SanitizerMask WebAssembly::getSupportedSanitizers(
572 StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const {
573 SanitizerMask Res =
574 ToolChain::getSupportedSanitizers(BoundArch, DeviceOffloadKind);
575 if (getTriple().isOSEmscripten()) {
576 Res |= SanitizerKind::Vptr | SanitizerKind::Leak;
577 }
578
579 if (getTriple().isOSEmscripten() || getTriple().isOSWASI()) {
580 Res |= SanitizerKind::Address;
581 }
582
583 // -fsanitize=function places two words before the function label, which are
584 // -unsupported.
585 Res &= ~SanitizerKind::Function;
586 return Res;
587}
588
589Tool *WebAssembly::buildLinker() const {
590 return new tools::wasm::Linker(*this);
591}
592
593void WebAssembly::addLibCxxIncludePaths(
594 const llvm::opt::ArgList &DriverArgs,
595 llvm::opt::ArgStringList &CC1Args) const {
596 const Driver &D = getDriver();
597 std::string SysRoot = computeSysRoot();
598 std::string LibPath = SysRoot + "/include";
599 const std::string MultiarchTriple =
600 getMultiarchTriple(D, getTriple(), SysRoot);
601 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
602
603 std::string Version = detectLibcxxVersion(LibPath);
604 if (Version.empty())
605 return;
606
607 // First add the per-target-per-exception-handling include path if the
608 // OS is known, then second add the per-target include path.
609 if (IsKnownOs) {
610 std::string TargetDir = LibPath + "/" + MultiarchTriple;
611 std::string Suffix = "/c++/" + Version;
612 addSystemInclude(DriverArgs, CC1Args,
613 TargetDir + "/" + GetCXXExceptionsDir(DriverArgs) +
614 Suffix);
615 addSystemInclude(DriverArgs, CC1Args, TargetDir + Suffix);
616 }
617
618 // Third add the generic one.
619 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
620}
621
622void WebAssembly::addLibStdCXXIncludePaths(
623 const llvm::opt::ArgList &DriverArgs,
624 llvm::opt::ArgStringList &CC1Args) const {
625 // We cannot use GCCInstallationDetector here as the sysroot usually does
626 // not contain a full GCC installation.
627 // Instead, we search the given sysroot for /usr/include/xx, similar
628 // to how we do it for libc++.
629 const Driver &D = getDriver();
630 std::string SysRoot = computeSysRoot();
631 std::string LibPath = SysRoot + "/include";
632 const std::string MultiarchTriple =
633 getMultiarchTriple(D, getTriple(), SysRoot);
634 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
635
636 // This is similar to detectLibcxxVersion()
637 std::string Version;
638 {
639 std::error_code EC;
640 Generic_GCC::GCCVersion MaxVersion =
642 SmallString<128> Path(LibPath);
643 llvm::sys::path::append(Path, "c++");
644 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
645 !EC && LI != LE; LI = LI.increment(EC)) {
646 StringRef VersionText = llvm::sys::path::filename(LI->path());
647 if (VersionText[0] != 'v') {
648 auto Version = Generic_GCC::GCCVersion::Parse(VersionText);
649 if (Version > MaxVersion)
650 MaxVersion = Version;
651 }
652 }
653 if (MaxVersion.Major > 0)
654 Version = MaxVersion.Text;
655 }
656
657 if (Version.empty())
658 return;
659
660 // First add the per-target include path if the OS is known.
661 if (IsKnownOs) {
662 std::string TargetDir = LibPath + "/c++/" + Version + "/" + MultiarchTriple;
663 addSystemInclude(DriverArgs, CC1Args, TargetDir);
664 }
665
666 // Second add the generic one.
667 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
668 // Third the backward one.
669 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + "/backward");
670}
static std::string GetCXXExceptionsDir(const ArgList &DriverArgs)
Returns a directory name in which separate objects compile with/without exceptions may lie.
static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args)
static void AppendLibDirAndLTODir(ToolChain::path_list &Paths, const Driver &D, const std::string &Dir)
Append Dir to Paths, but also include the LTO directories before that if LTO is eanbled.
static bool TargetBuildsComponents(const llvm::Triple &TargetTriple)
static bool WantsLibcallThreadContext(const llvm::Triple &Triple, const ArgList &Args)
static StringRef getTriple(const Command &Job)
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:99
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:169
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
Definition Driver.h:744
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:93
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments.
std::string GetFilePath(const char *Name) const
StringRef getOS() const
Definition ToolChain.h:302
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:507
const Driver & getDriver() const
Definition ToolChain.h:283
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
llvm::vfs::FileSystem & getVFS() const
virtual bool isPICDefaultForced() const =0
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
virtual SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
virtual bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition ToolChain.h:499
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition ToolChain.h:533
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:285
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
std::string GetProgramPath(const char *Name) const
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:729
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:629
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition ToolChain.h:511
virtual void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition ToolChain.h:536
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:95
const ToolChain & getToolChain() const
Definition Tool.h:52
WebAssembly(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
std::string getLinkerPath(const llvm::opt::ArgList &Args) const
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1483
The JSON file list parser is used to communicate input to InstallAPI.
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
static constexpr ResponseFileSupport AtFileCurCP()
Definition Job.h:92
int Major
The parsed major, minor, and patch numbers.
Definition Gnu.h:168
std::string Text
The unparsed text of the version.
Definition Gnu.h:165
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition Gnu.cpp:1992