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 // WASIp3 also implies pthreads support
89 if (Triple.getOS() == llvm::Triple::WASIp3)
90 WantsPthread = true;
91
92 return WantsPthread;
93}
94
95static bool WantsCooperativeMultithreading(const llvm::Triple &Triple,
96 const ArgList &Args) {
97 return Triple.getOS() == llvm::Triple::WASIp3;
98}
99
100static bool WantsSharedMemory(const llvm::Triple &Triple, const ArgList &Args) {
101 return WantsPthread(Triple, Args) &&
102 !WantsCooperativeMultithreading(Triple, Args);
103}
104
106 const InputInfo &Output,
107 const InputInfoList &Inputs,
108 const ArgList &Args,
109 const char *LinkingOutput) const {
110
112 const char *Linker = Args.MakeArgString(getLinkerPath(Args));
113 ArgStringList CmdArgs;
114
115 CmdArgs.push_back("-m");
116 if (ToolChain.getTriple().isArch64Bit())
117 CmdArgs.push_back("wasm64");
118 else
119 CmdArgs.push_back("wasm32");
120
121 if (Args.hasArg(options::OPT_s))
122 CmdArgs.push_back("--strip-all");
123
124 // On `wasip2` the default linker is `wasm-component-ld` which wraps the
125 // execution of `wasm-ld`. Find `wasm-ld` and pass it as an argument of where
126 // to find it to avoid it needing to hunt and rediscover or search `PATH` for
127 // where it is.
128 if (llvm::sys::path::stem(Linker).ends_with_insensitive(
129 "wasm-component-ld")) {
130 CmdArgs.push_back("--wasm-ld-path");
131 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetProgramPath("wasm-ld")));
132 }
133
134 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
135
136 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
137
138 bool IsCommand = true;
139 const char *Crt1;
140 const char *Entry = nullptr;
141
142 // When -shared is specified, use the reactor exec model unless
143 // specified otherwise.
144 if (Args.hasArg(options::OPT_shared))
145 IsCommand = false;
146
147 if (const Arg *A = Args.getLastArg(options::OPT_mexec_model_EQ)) {
148 StringRef CM = A->getValue();
149 if (CM == "command") {
150 IsCommand = true;
151 } else if (CM == "reactor") {
152 IsCommand = false;
153 } else {
154 ToolChain.getDriver().Diag(diag::err_drv_invalid_argument_to_option)
155 << CM << A->getOption().getName();
156 }
157 }
158
159 if (IsCommand) {
160 // If crt1-command.o exists, it supports new-style commands, so use it.
161 // Otherwise, use the old crt1.o. This is a temporary transition measure.
162 // Once WASI libc no longer needs to support LLVM versions which lack
163 // support for new-style command, it can make crt1.o the same as
164 // crt1-command.o. And once LLVM no longer needs to support WASI libc
165 // versions before that, it can switch to using crt1-command.o.
166 Crt1 = "crt1.o";
167 if (ToolChain.GetFilePath("crt1-command.o") != "crt1-command.o")
168 Crt1 = "crt1-command.o";
169 } else {
170 Crt1 = "crt1-reactor.o";
171 Entry = "_initialize";
172 }
173
174 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
175 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(Crt1)));
176 if (Entry) {
177 CmdArgs.push_back(Args.MakeArgString("--entry"));
178 CmdArgs.push_back(Args.MakeArgString(Entry));
179 }
180
181 if (Args.hasArg(options::OPT_shared))
182 CmdArgs.push_back(Args.MakeArgString("-shared"));
183
184 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
185
187 CmdArgs.push_back("--cooperative-threading");
188
190 CmdArgs.push_back("--shared-memory");
191
192 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
194 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
195
196 if (WantsPthread(ToolChain.getTriple(), Args))
197 CmdArgs.push_back("-lpthread");
198
199 CmdArgs.push_back("-lc");
200 AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
201 }
202
203 ToolChain.addProfileRTLibs(Args, CmdArgs);
204
205 CmdArgs.push_back("-o");
206 CmdArgs.push_back(Output.getFilename());
207
208 // Don't use wasm-opt by default on `wasip2` as it doesn't have support for
209 // components at this time. Retain the historical default otherwise, though,
210 // of running `wasm-opt` by default.
211 bool WasmOptDefault = !TargetBuildsComponents(ToolChain.getTriple());
212 bool RunWasmOpt = Args.hasFlag(options::OPT_wasm_opt,
213 options::OPT_no_wasm_opt, WasmOptDefault);
214
215 // If wasm-opt is enabled and optimizations are happening look for the
216 // `wasm-opt` program. If it's not found auto-disable it.
217 std::string WasmOptPath;
218 if (RunWasmOpt && Args.getLastArg(options::OPT_O_Group)) {
219 WasmOptPath = ToolChain.GetProgramPath("wasm-opt");
220 if (WasmOptPath == "wasm-opt") {
221 WasmOptPath = {};
222 }
223 }
224
225 if (!WasmOptPath.empty()) {
226 CmdArgs.push_back("--keep-section=target_features");
227 }
228
229 C.addCommand(std::make_unique<Command>(JA, *this,
231 Linker, CmdArgs, Inputs, Output));
232
233 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
234 if (!WasmOptPath.empty()) {
235 StringRef OOpt = "s";
236 if (A->getOption().matches(options::OPT_O4) ||
237 A->getOption().matches(options::OPT_Ofast))
238 OOpt = "4";
239 else if (A->getOption().matches(options::OPT_O0))
240 OOpt = "0";
241 else if (A->getOption().matches(options::OPT_O))
242 OOpt = A->getValue();
243
244 if (OOpt != "0") {
245 const char *WasmOpt = Args.MakeArgString(WasmOptPath);
246 ArgStringList OptArgs;
247 OptArgs.push_back(Output.getFilename());
248 OptArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
249 OptArgs.push_back("-o");
250 OptArgs.push_back(Output.getFilename());
251 C.addCommand(std::make_unique<Command>(
252 JA, *this, ResponseFileSupport::AtFileCurCP(), WasmOpt, OptArgs,
253 Inputs, Output));
254 }
255 }
256 }
257}
258
259/// Append `Dir` to `Paths`, but also include the LTO directories before that if
260/// LTO is enabled.
262 const ToolChain &TC,
263 const llvm::opt::ArgList &Args,
264 const std::string &Dir) {
265 if (TC.isUsingLTO(Args)) {
266 // The version allows the path to be keyed to the specific version of
267 // LLVM in used, as the bitcode format is not stable.
268 Paths.push_back(Dir + "/llvm-lto/" LLVM_VERSION_STRING);
269 }
270 Paths.push_back(Dir);
271}
272
273WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
274 const llvm::opt::ArgList &Args)
275 : ToolChain(D, Triple, Args) {
276
277 assert(Triple.isArch32Bit() != Triple.isArch64Bit());
278
279 getProgramPaths().push_back(getDriver().Dir);
280
281 auto SysRoot = getDriver().SysRoot;
282 if (getTriple().getOS() == llvm::Triple::UnknownOS) {
283 // Theoretically an "unknown" OS should mean no standard libraries, however
284 // it could also mean that a custom set of libraries is in use, so just add
285 // /lib to the search path. Disable multiarch in this case, to discourage
286 // paths containing "unknown" from acquiring meanings.
287 getFilePaths().push_back(SysRoot + "/lib");
288 } else {
289 const std::string MultiarchTriple =
290 getMultiarchTriple(getDriver(), Triple, SysRoot);
291 std::string TripleLibDir = SysRoot + "/lib/" + MultiarchTriple;
292 // Allow sysroots to segregate objects based on whether exceptions are
293 // enabled or not. This is intended to assist with distribution of pre-built
294 // sysroots that contain libraries that are capable of producing binaries
295 // entirely without exception-handling instructions but also with if
296 // exceptions are enabled, for example.
297 AppendLibDirAndLTODir(getFilePaths(), *this, Args,
298 TripleLibDir + "/" + GetCXXExceptionsDir(Args));
299 AppendLibDirAndLTODir(getFilePaths(), *this, Args, TripleLibDir);
300 }
301
302 if (getTriple().getOS() == llvm::Triple::WASI) {
303 D.Diag(diag::warn_drv_deprecated_custom)
304 << "--target=wasm32-wasi"
305 << "use --target=wasm32-wasip1 instead";
306 }
307}
308
309const char *WebAssembly::getDefaultLinker() const {
311 return "wasm-component-ld";
312 return "wasm-ld";
313}
314
315bool WebAssembly::IsMathErrnoDefault() const { return false; }
316
317bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
318
319bool WebAssembly::UseObjCMixedDispatch() const { return true; }
320
321bool WebAssembly::isPICDefault() const { return false; }
322
323bool WebAssembly::isPIEDefault(const llvm::opt::ArgList &Args) const {
324 return false;
325}
326
327bool WebAssembly::isPICDefaultForced() const { return false; }
328
329bool WebAssembly::hasBlocksRuntime() const { return false; }
330
331// TODO: Support profiling.
332bool WebAssembly::SupportsProfiling() const { return false; }
333
334bool WebAssembly::HasNativeLLVMSupport() const { return true; }
335
336void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
337 ArgStringList &CC1Args, BoundArch BA,
338 Action::OffloadKind) const {
339 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
340 options::OPT_fno_use_init_array, true))
341 CC1Args.push_back("-fno-use-init-array");
342
343 // '-pthread' implies bulk-memory, mutable-globals, and sign-ext.
344 // It also implies atomics, so long as we're not targeting a cooperative
345 // threading environment.
346 if (WantsPthread(getTriple(), DriverArgs)) {
347 if (!WantsCooperativeMultithreading(getTriple(), DriverArgs) &&
348 DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics,
349 false))
350 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
351 << "-pthread"
352 << "-mno-atomics";
353 if (DriverArgs.hasFlag(options::OPT_mno_bulk_memory,
354 options::OPT_mbulk_memory, false))
355 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
356 << "-pthread"
357 << "-mno-bulk-memory";
358 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
359 options::OPT_mmutable_globals, false))
360 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
361 << "-pthread"
362 << "-mno-mutable-globals";
363 if (DriverArgs.hasFlag(options::OPT_mno_sign_ext, options::OPT_msign_ext,
364 false))
365 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
366 << "-pthread"
367 << "-mno-sign-ext";
368 if (!WantsCooperativeMultithreading(getTriple(), DriverArgs)) {
369 CC1Args.push_back("-target-feature");
370 CC1Args.push_back("+atomics");
371 }
372 CC1Args.push_back("-target-feature");
373 CC1Args.push_back("+bulk-memory");
374 CC1Args.push_back("-target-feature");
375 CC1Args.push_back("+mutable-globals");
376 CC1Args.push_back("-target-feature");
377 CC1Args.push_back("+sign-ext");
378 }
379
380 if (!DriverArgs.hasFlag(options::OPT_mmutable_globals,
381 options::OPT_mno_mutable_globals, false)) {
382 // -fPIC implies +mutable-globals because the PIC ABI used by the linker
383 // depends on importing and exporting mutable globals.
384 llvm::Reloc::Model RelocationModel;
385 unsigned PICLevel;
386 bool IsPIE;
387 std::tie(RelocationModel, PICLevel, IsPIE) =
388 ParsePICArgs(*this, DriverArgs);
389 if (RelocationModel == llvm::Reloc::PIC_) {
390 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
391 options::OPT_mmutable_globals, false)) {
392 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
393 << "-fPIC"
394 << "-mno-mutable-globals";
395 }
396 CC1Args.push_back("-target-feature");
397 CC1Args.push_back("+mutable-globals");
398 }
399 }
400
401 bool HasBannedIncompatibleOptionsForWasmEHSjLj = false;
402 bool HasEnabledFeaturesForWasmEHSjLj = false;
403
404 // Bans incompatible options for Wasm EH / SjLj. We don't allow using
405 // different modes for EH and SjLj.
406 auto BanIncompatibleOptionsForWasmEHSjLj = [&](StringRef CurOption) {
407 if (HasBannedIncompatibleOptionsForWasmEHSjLj)
408 return;
409 HasBannedIncompatibleOptionsForWasmEHSjLj = true;
410 if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
411 options::OPT_mexception_handing, false))
412 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
413 << CurOption << "-mno-exception-handling";
414 // The standardized Wasm EH spec requires multivalue and reference-types.
415 if (DriverArgs.hasFlag(options::OPT_mno_multivalue,
416 options::OPT_mmultivalue, false))
417 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
418 << CurOption << "-mno-multivalue";
419 if (DriverArgs.hasFlag(options::OPT_mno_reference_types,
420 options::OPT_mreference_types, false))
421 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
422 << CurOption << "-mno-reference-types";
423
424 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
425 for (const auto *Option :
426 {"-enable-emscripten-cxx-exceptions", "-enable-emscripten-sjlj",
427 "-emscripten-cxx-exceptions-allowed"}) {
428 if (StringRef(A->getValue(0)) == Option)
429 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
430 << CurOption << Option;
431 }
432 }
433 };
434
435 // Enable necessary features for Wasm EH / SjLj in the backend.
436 auto EnableFeaturesForWasmEHSjLj = [&]() {
437 if (HasEnabledFeaturesForWasmEHSjLj)
438 return;
439 HasEnabledFeaturesForWasmEHSjLj = true;
440 CC1Args.push_back("-target-feature");
441 CC1Args.push_back("+exception-handling");
442 // The standardized Wasm EH spec requires multivalue and reference-types.
443 CC1Args.push_back("-target-feature");
444 CC1Args.push_back("+multivalue");
445 CC1Args.push_back("-target-feature");
446 CC1Args.push_back("+reference-types");
447 // Backend needs '-exception-model=wasm' to use Wasm EH instructions
448 CC1Args.push_back("-exception-model=wasm");
449 };
450
451 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions)) {
452 BanIncompatibleOptionsForWasmEHSjLj("-fwasm-exceptions");
453 EnableFeaturesForWasmEHSjLj();
454 // Backend needs -wasm-enable-eh to enable Wasm EH
455 CC1Args.push_back("-mllvm");
456 CC1Args.push_back("-wasm-enable-eh");
457 }
458
459 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
460 StringRef Opt = A->getValue(0);
461 if (Opt.starts_with("-emscripten-cxx-exceptions-allowed")) {
462 // '-mllvm -emscripten-cxx-exceptions-allowed' should be used with
463 // '-mllvm -enable-emscripten-cxx-exceptions'
464 bool EmEHArgExists = false;
465 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
466 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions") {
467 EmEHArgExists = true;
468 break;
469 }
470 }
471 if (!EmEHArgExists)
472 getDriver().Diag(diag::err_drv_argument_only_allowed_with)
473 << "-mllvm -emscripten-cxx-exceptions-allowed"
474 << "-mllvm -enable-emscripten-cxx-exceptions";
475
476 // Prevent functions specified in -emscripten-cxx-exceptions-allowed list
477 // from being inlined before reaching the wasm backend.
478 StringRef FuncNamesStr = Opt.split('=').second;
479 SmallVector<StringRef, 4> FuncNames;
480 FuncNamesStr.split(FuncNames, ',');
481 for (auto Name : FuncNames) {
482 CC1Args.push_back("-mllvm");
483 CC1Args.push_back(DriverArgs.MakeArgString("--force-attribute=" + Name +
484 ":noinline"));
485 }
486 }
487
488 for (const auto *Option :
489 {"-wasm-enable-eh", "-wasm-enable-sjlj", "-wasm-use-legacy-eh"}) {
490 if (Opt.starts_with(Option)) {
491 BanIncompatibleOptionsForWasmEHSjLj(Option);
492 EnableFeaturesForWasmEHSjLj();
493 }
494 }
495 }
496}
497
500}
501
503WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
504 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
505 StringRef Value = A->getValue();
506 if (Value == "libc++")
508 else if (Value == "libstdc++")
510 else
511 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
512 << A->getAsString(Args);
513 }
515}
516
517void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
518 ArgStringList &CC1Args) const {
519 if (DriverArgs.hasArg(options::OPT_nostdinc))
520 return;
521
522 const Driver &D = getDriver();
523
524 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
525 SmallString<128> P(D.ResourceDir);
526 llvm::sys::path::append(P, "include");
527 addSystemInclude(DriverArgs, CC1Args, P);
528 }
529
530 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
531 return;
532
533 // Check for configure-time C include directories.
534 StringRef CIncludeDirs(C_INCLUDE_DIRS);
535 if (CIncludeDirs != "") {
536 SmallVector<StringRef, 5> dirs;
537 CIncludeDirs.split(dirs, ":");
538 for (StringRef dir : dirs) {
539 StringRef Prefix =
540 llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
541 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
542 }
543 return;
544 }
545
546 if (getTriple().getOS() != llvm::Triple::UnknownOS) {
547 const std::string MultiarchTriple =
548 getMultiarchTriple(D, getTriple(), D.SysRoot);
549 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include/" + MultiarchTriple);
550 }
551 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
552}
553
554void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
555 ArgStringList &CC1Args) const {
556
557 if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdinc,
558 options::OPT_nostdincxx))
559 return;
560
561 switch (GetCXXStdlibType(DriverArgs)) {
563 addLibCxxIncludePaths(DriverArgs, CC1Args);
564 break;
566 addLibStdCXXIncludePaths(DriverArgs, CC1Args);
567 break;
568 }
569}
570
571void WebAssembly::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
572 llvm::opt::ArgStringList &CmdArgs) const {
573
574 switch (GetCXXStdlibType(Args)) {
576 CmdArgs.push_back("-lc++");
577 if (Args.hasArg(options::OPT_fexperimental_library))
578 CmdArgs.push_back("-lc++experimental");
579 CmdArgs.push_back("-lc++abi");
580 break;
582 CmdArgs.push_back("-lstdc++");
583 break;
584 }
585}
586
587SanitizerMask WebAssembly::getSupportedSanitizers(
588 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
589 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
590 if (getTriple().isOSEmscripten()) {
591 Res |= SanitizerKind::Vptr | SanitizerKind::Leak;
592 }
593
594 if (getTriple().isOSEmscripten() || getTriple().isOSWASI()) {
595 Res |= SanitizerKind::Address;
596 }
597
598 // -fsanitize=function places two words before the function label, which are
599 // -unsupported.
600 Res &= ~SanitizerKind::Function;
601 return Res;
602}
603
604Tool *WebAssembly::buildLinker() const {
605 return new tools::wasm::Linker(*this);
606}
607
608void WebAssembly::addLibCxxIncludePaths(
609 const llvm::opt::ArgList &DriverArgs,
610 llvm::opt::ArgStringList &CC1Args) const {
611 const Driver &D = getDriver();
612 std::string SysRoot = computeSysRoot();
613 std::string LibPath = SysRoot + "/include";
614 const std::string MultiarchTriple =
615 getMultiarchTriple(D, getTriple(), SysRoot);
616 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
617
618 std::string Version = detectLibcxxVersion(LibPath);
619 if (Version.empty())
620 return;
621
622 // First add the per-target-per-exception-handling include path if the
623 // OS is known, then second add the per-target include path.
624 if (IsKnownOs) {
625 std::string TargetDir = LibPath + "/" + MultiarchTriple;
626 std::string Suffix = "/c++/" + Version;
627 addSystemInclude(DriverArgs, CC1Args,
628 TargetDir + "/" + GetCXXExceptionsDir(DriverArgs) +
629 Suffix);
630 addSystemInclude(DriverArgs, CC1Args, TargetDir + Suffix);
631 }
632
633 // Third add the generic one.
634 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
635}
636
637void WebAssembly::addLibStdCXXIncludePaths(
638 const llvm::opt::ArgList &DriverArgs,
639 llvm::opt::ArgStringList &CC1Args) const {
640 // We cannot use GCCInstallationDetector here as the sysroot usually does
641 // not contain a full GCC installation.
642 // Instead, we search the given sysroot for /usr/include/xx, similar
643 // to how we do it for libc++.
644 const Driver &D = getDriver();
645 std::string SysRoot = computeSysRoot();
646 std::string LibPath = SysRoot + "/include";
647 const std::string MultiarchTriple =
648 getMultiarchTriple(D, getTriple(), SysRoot);
649 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
650
651 // This is similar to detectLibcxxVersion()
652 std::string Version;
653 {
654 std::error_code EC;
655 Generic_GCC::GCCVersion MaxVersion =
657 SmallString<128> Path(LibPath);
658 llvm::sys::path::append(Path, "c++");
659 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
660 !EC && LI != LE; LI = LI.increment(EC)) {
661 StringRef VersionText = llvm::sys::path::filename(LI->path());
662 if (VersionText[0] != 'v') {
663 auto Version = Generic_GCC::GCCVersion::Parse(VersionText);
664 if (Version > MaxVersion)
665 MaxVersion = Version;
666 }
667 }
668 if (MaxVersion.Major > 0)
669 Version = MaxVersion.Text;
670 }
671
672 if (Version.empty())
673 return;
674
675 // First add the per-target include path if the OS is known.
676 if (IsKnownOs) {
677 std::string TargetDir = LibPath + "/c++/" + Version + "/" + MultiarchTriple;
678 addSystemInclude(DriverArgs, CC1Args, TargetDir);
679 }
680
681 // Second add the generic one.
682 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
683 // Third the backward one.
684 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + "/backward");
685}
static std::string GetCXXExceptionsDir(const ArgList &DriverArgs)
Returns a directory name in which separate objects compile with/without exceptions may lie.
static void AppendLibDirAndLTODir(ToolChain::path_list &Paths, const ToolChain &TC, const llvm::opt::ArgList &Args, const std::string &Dir)
Append Dir to Paths, but also include the LTO directories before that if LTO is enabled.
static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args)
static bool WantsCooperativeMultithreading(const llvm::Triple &Triple, const ArgList &Args)
static bool TargetBuildsComponents(const llvm::Triple &TargetTriple)
static bool WantsSharedMemory(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:46
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:159
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:96
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.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
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:305
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:521
virtual SanitizerMask getSupportedSanitizers(BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
const Driver & getDriver() const
Definition ToolChain.h:286
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 bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition ToolChain.h:513
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:547
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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:742
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:643
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition ToolChain.h:525
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:550
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:98
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:51
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1524
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:93
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:1991