WebAssembly.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. #include "WebAssembly.h"
  9. #include "CommonArgs.h"
  10. #include "clang/Basic/Version.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 "llvm/Support/FileSystem.h"
  17. #include "llvm/Support/Path.h"
  18. #include "llvm/Option/ArgList.h"
  19. using namespace clang::driver;
  20. using namespace clang::driver::tools;
  21. using namespace clang::driver::toolchains;
  22. using namespace clang;
  23. using namespace llvm::opt;
  24. /// Following the conventions in https://wiki.debian.org/Multiarch/Tuples,
  25. /// we remove the vendor field to form the multiarch triple.
  26. std::string WebAssembly::getMultiarchTriple(const Driver &D,
  27. const llvm::Triple &TargetTriple,
  28. StringRef SysRoot) const {
  29. return (TargetTriple.getArchName() + "-" +
  30. TargetTriple.getOSAndEnvironmentName()).str();
  31. }
  32. std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
  33. const ToolChain &ToolChain = getToolChain();
  34. if (const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  35. StringRef UseLinker = A->getValue();
  36. if (!UseLinker.empty()) {
  37. if (llvm::sys::path::is_absolute(UseLinker) &&
  38. llvm::sys::fs::can_execute(UseLinker))
  39. return std::string(UseLinker);
  40. // Accept 'lld', and 'ld' as aliases for the default linker
  41. if (UseLinker != "lld" && UseLinker != "ld")
  42. ToolChain.getDriver().Diag(diag::err_drv_invalid_linker_name)
  43. << A->getAsString(Args);
  44. }
  45. }
  46. return ToolChain.GetProgramPath(ToolChain.getDefaultLinker());
  47. }
  48. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  49. const InputInfo &Output,
  50. const InputInfoList &Inputs,
  51. const ArgList &Args,
  52. const char *LinkingOutput) const {
  53. const ToolChain &ToolChain = getToolChain();
  54. const char *Linker = Args.MakeArgString(getLinkerPath(Args));
  55. ArgStringList CmdArgs;
  56. CmdArgs.push_back("-m");
  57. if (ToolChain.getTriple().isArch64Bit())
  58. CmdArgs.push_back("wasm64");
  59. else
  60. CmdArgs.push_back("wasm32");
  61. if (Args.hasArg(options::OPT_s))
  62. CmdArgs.push_back("--strip-all");
  63. Args.AddAllArgs(CmdArgs, options::OPT_L);
  64. Args.AddAllArgs(CmdArgs, options::OPT_u);
  65. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  66. const char *Crt1 = "crt1.o";
  67. const char *Entry = nullptr;
  68. // If crt1-command.o exists, it supports new-style commands, so use it.
  69. // Otherwise, use the old crt1.o. This is a temporary transition measure.
  70. // Once WASI libc no longer needs to support LLVM versions which lack
  71. // support for new-style command, it can make crt1.o the same as
  72. // crt1-command.o. And once LLVM no longer needs to support WASI libc
  73. // versions before that, it can switch to using crt1-command.o.
  74. if (ToolChain.GetFilePath("crt1-command.o") != "crt1-command.o")
  75. Crt1 = "crt1-command.o";
  76. if (const Arg *A = Args.getLastArg(options::OPT_mexec_model_EQ)) {
  77. StringRef CM = A->getValue();
  78. if (CM == "command") {
  79. // Use default values.
  80. } else if (CM == "reactor") {
  81. Crt1 = "crt1-reactor.o";
  82. Entry = "_initialize";
  83. } else {
  84. ToolChain.getDriver().Diag(diag::err_drv_invalid_argument_to_option)
  85. << CM << A->getOption().getName();
  86. }
  87. }
  88. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  89. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(Crt1)));
  90. if (Entry) {
  91. CmdArgs.push_back(Args.MakeArgString("--entry"));
  92. CmdArgs.push_back(Args.MakeArgString(Entry));
  93. }
  94. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  95. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  96. if (ToolChain.ShouldLinkCXXStdlib(Args))
  97. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  98. if (Args.hasArg(options::OPT_pthread)) {
  99. CmdArgs.push_back("-lpthread");
  100. CmdArgs.push_back("--shared-memory");
  101. }
  102. CmdArgs.push_back("-lc");
  103. AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
  104. }
  105. CmdArgs.push_back("-o");
  106. CmdArgs.push_back(Output.getFilename());
  107. C.addCommand(std::make_unique<Command>(JA, *this,
  108. ResponseFileSupport::AtFileCurCP(),
  109. Linker, CmdArgs, Inputs, Output));
  110. // When optimizing, if wasm-opt is available, run it.
  111. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  112. auto WasmOptPath = ToolChain.GetProgramPath("wasm-opt");
  113. if (WasmOptPath != "wasm-opt") {
  114. StringRef OOpt = "s";
  115. if (A->getOption().matches(options::OPT_O4) ||
  116. A->getOption().matches(options::OPT_Ofast))
  117. OOpt = "4";
  118. else if (A->getOption().matches(options::OPT_O0))
  119. OOpt = "0";
  120. else if (A->getOption().matches(options::OPT_O))
  121. OOpt = A->getValue();
  122. if (OOpt != "0") {
  123. const char *WasmOpt = Args.MakeArgString(WasmOptPath);
  124. ArgStringList CmdArgs;
  125. CmdArgs.push_back(Output.getFilename());
  126. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  127. CmdArgs.push_back("-o");
  128. CmdArgs.push_back(Output.getFilename());
  129. C.addCommand(std::make_unique<Command>(
  130. JA, *this, ResponseFileSupport::AtFileCurCP(), WasmOpt, CmdArgs,
  131. Inputs, Output));
  132. }
  133. }
  134. }
  135. }
  136. /// Given a base library directory, append path components to form the
  137. /// LTO directory.
  138. static std::string AppendLTOLibDir(const std::string &Dir) {
  139. // The version allows the path to be keyed to the specific version of
  140. // LLVM in used, as the bitcode format is not stable.
  141. return Dir + "/llvm-lto/" LLVM_VERSION_STRING;
  142. }
  143. WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
  144. const llvm::opt::ArgList &Args)
  145. : ToolChain(D, Triple, Args) {
  146. assert(Triple.isArch32Bit() != Triple.isArch64Bit());
  147. getProgramPaths().push_back(getDriver().getInstalledDir());
  148. auto SysRoot = getDriver().SysRoot;
  149. if (getTriple().getOS() == llvm::Triple::UnknownOS) {
  150. // Theoretically an "unknown" OS should mean no standard libraries, however
  151. // it could also mean that a custom set of libraries is in use, so just add
  152. // /lib to the search path. Disable multiarch in this case, to discourage
  153. // paths containing "unknown" from acquiring meanings.
  154. getFilePaths().push_back(SysRoot + "/lib");
  155. } else {
  156. const std::string MultiarchTriple =
  157. getMultiarchTriple(getDriver(), Triple, SysRoot);
  158. if (D.isUsingLTO()) {
  159. // For LTO, enable use of lto-enabled sysroot libraries too, if available.
  160. // Note that the directory is keyed to the LLVM revision, as LLVM's
  161. // bitcode format is not stable.
  162. auto Dir = AppendLTOLibDir(SysRoot + "/lib/" + MultiarchTriple);
  163. getFilePaths().push_back(Dir);
  164. }
  165. getFilePaths().push_back(SysRoot + "/lib/" + MultiarchTriple);
  166. }
  167. }
  168. bool WebAssembly::IsMathErrnoDefault() const { return false; }
  169. bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
  170. bool WebAssembly::UseObjCMixedDispatch() const { return true; }
  171. bool WebAssembly::isPICDefault() const { return false; }
  172. bool WebAssembly::isPIEDefault(const llvm::opt::ArgList &Args) const {
  173. return false;
  174. }
  175. bool WebAssembly::isPICDefaultForced() const { return false; }
  176. bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
  177. bool WebAssembly::hasBlocksRuntime() const { return false; }
  178. // TODO: Support profiling.
  179. bool WebAssembly::SupportsProfiling() const { return false; }
  180. bool WebAssembly::HasNativeLLVMSupport() const { return true; }
  181. void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
  182. ArgStringList &CC1Args,
  183. Action::OffloadKind) const {
  184. if (!DriverArgs.hasFlag(clang::driver::options::OPT_fuse_init_array,
  185. options::OPT_fno_use_init_array, true))
  186. CC1Args.push_back("-fno-use-init-array");
  187. // '-pthread' implies atomics, bulk-memory, mutable-globals, and sign-ext
  188. if (DriverArgs.hasFlag(options::OPT_pthread, options::OPT_no_pthread,
  189. false)) {
  190. if (DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics,
  191. false))
  192. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  193. << "-pthread"
  194. << "-mno-atomics";
  195. if (DriverArgs.hasFlag(options::OPT_mno_bulk_memory,
  196. options::OPT_mbulk_memory, false))
  197. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  198. << "-pthread"
  199. << "-mno-bulk-memory";
  200. if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
  201. options::OPT_mmutable_globals, false))
  202. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  203. << "-pthread"
  204. << "-mno-mutable-globals";
  205. if (DriverArgs.hasFlag(options::OPT_mno_sign_ext, options::OPT_msign_ext,
  206. false))
  207. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  208. << "-pthread"
  209. << "-mno-sign-ext";
  210. CC1Args.push_back("-target-feature");
  211. CC1Args.push_back("+atomics");
  212. CC1Args.push_back("-target-feature");
  213. CC1Args.push_back("+bulk-memory");
  214. CC1Args.push_back("-target-feature");
  215. CC1Args.push_back("+mutable-globals");
  216. CC1Args.push_back("-target-feature");
  217. CC1Args.push_back("+sign-ext");
  218. }
  219. if (!DriverArgs.hasFlag(options::OPT_mmutable_globals,
  220. options::OPT_mno_mutable_globals, false)) {
  221. // -fPIC implies +mutable-globals because the PIC ABI used by the linker
  222. // depends on importing and exporting mutable globals.
  223. llvm::Reloc::Model RelocationModel;
  224. unsigned PICLevel;
  225. bool IsPIE;
  226. std::tie(RelocationModel, PICLevel, IsPIE) =
  227. ParsePICArgs(*this, DriverArgs);
  228. if (RelocationModel == llvm::Reloc::PIC_) {
  229. if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
  230. options::OPT_mmutable_globals, false)) {
  231. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  232. << "-fPIC"
  233. << "-mno-mutable-globals";
  234. }
  235. CC1Args.push_back("-target-feature");
  236. CC1Args.push_back("+mutable-globals");
  237. }
  238. }
  239. if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions)) {
  240. // '-fwasm-exceptions' is not compatible with '-mno-exception-handling'
  241. if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
  242. options::OPT_mexception_handing, false))
  243. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  244. << "-fwasm-exceptions"
  245. << "-mno-exception-handling";
  246. // '-fwasm-exceptions' is not compatible with
  247. // '-mllvm -enable-emscripten-cxx-exceptions'
  248. for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
  249. if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions")
  250. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  251. << "-fwasm-exceptions"
  252. << "-mllvm -enable-emscripten-cxx-exceptions";
  253. }
  254. // '-fwasm-exceptions' implies exception-handling feature
  255. CC1Args.push_back("-target-feature");
  256. CC1Args.push_back("+exception-handling");
  257. // Backend needs -wasm-enable-eh to enable Wasm EH
  258. CC1Args.push_back("-mllvm");
  259. CC1Args.push_back("-wasm-enable-eh");
  260. }
  261. for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
  262. StringRef Opt = A->getValue(0);
  263. if (Opt.startswith("-emscripten-cxx-exceptions-allowed")) {
  264. // '-mllvm -emscripten-cxx-exceptions-allowed' should be used with
  265. // '-mllvm -enable-emscripten-cxx-exceptions'
  266. bool EmEHArgExists = false;
  267. for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
  268. if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions") {
  269. EmEHArgExists = true;
  270. break;
  271. }
  272. }
  273. if (!EmEHArgExists)
  274. getDriver().Diag(diag::err_drv_argument_only_allowed_with)
  275. << "-mllvm -emscripten-cxx-exceptions-allowed"
  276. << "-mllvm -enable-emscripten-cxx-exceptions";
  277. // Prevent functions specified in -emscripten-cxx-exceptions-allowed list
  278. // from being inlined before reaching the wasm backend.
  279. StringRef FuncNamesStr = Opt.split('=').second;
  280. SmallVector<StringRef, 4> FuncNames;
  281. FuncNamesStr.split(FuncNames, ',');
  282. for (auto Name : FuncNames) {
  283. CC1Args.push_back("-mllvm");
  284. CC1Args.push_back(DriverArgs.MakeArgString("--force-attribute=" + Name +
  285. ":noinline"));
  286. }
  287. }
  288. if (Opt.startswith("-wasm-enable-sjlj")) {
  289. // '-mllvm -wasm-enable-sjlj' is not compatible with
  290. // '-mno-exception-handling'
  291. if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
  292. options::OPT_mexception_handing, false))
  293. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  294. << "-mllvm -wasm-enable-sjlj"
  295. << "-mno-exception-handling";
  296. // '-mllvm -wasm-enable-sjlj' is not compatible with
  297. // '-mllvm -enable-emscripten-cxx-exceptions'
  298. // because we don't allow Emscripten EH + Wasm SjLj
  299. for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
  300. if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions")
  301. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  302. << "-mllvm -wasm-enable-sjlj"
  303. << "-mllvm -enable-emscripten-cxx-exceptions";
  304. }
  305. // '-mllvm -wasm-enable-sjlj' is not compatible with
  306. // '-mllvm -enable-emscripten-sjlj'
  307. for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
  308. if (StringRef(A->getValue(0)) == "-enable-emscripten-sjlj")
  309. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  310. << "-mllvm -wasm-enable-sjlj"
  311. << "-mllvm -enable-emscripten-sjlj";
  312. }
  313. // '-mllvm -wasm-enable-sjlj' implies exception-handling feature
  314. CC1Args.push_back("-target-feature");
  315. CC1Args.push_back("+exception-handling");
  316. // Backend needs '-exception-model=wasm' to use Wasm EH instructions
  317. CC1Args.push_back("-exception-model=wasm");
  318. }
  319. }
  320. }
  321. ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
  322. return ToolChain::RLT_CompilerRT;
  323. }
  324. ToolChain::CXXStdlibType
  325. WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
  326. if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
  327. StringRef Value = A->getValue();
  328. if (Value != "libc++")
  329. getDriver().Diag(diag::err_drv_invalid_stdlib_name)
  330. << A->getAsString(Args);
  331. }
  332. return ToolChain::CST_Libcxx;
  333. }
  334. void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  335. ArgStringList &CC1Args) const {
  336. if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
  337. return;
  338. const Driver &D = getDriver();
  339. if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
  340. SmallString<128> P(D.ResourceDir);
  341. llvm::sys::path::append(P, "include");
  342. addSystemInclude(DriverArgs, CC1Args, P);
  343. }
  344. if (DriverArgs.hasArg(options::OPT_nostdlibinc))
  345. return;
  346. // Check for configure-time C include directories.
  347. StringRef CIncludeDirs(C_INCLUDE_DIRS);
  348. if (CIncludeDirs != "") {
  349. SmallVector<StringRef, 5> dirs;
  350. CIncludeDirs.split(dirs, ":");
  351. for (StringRef dir : dirs) {
  352. StringRef Prefix =
  353. llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
  354. addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
  355. }
  356. return;
  357. }
  358. if (getTriple().getOS() != llvm::Triple::UnknownOS) {
  359. const std::string MultiarchTriple =
  360. getMultiarchTriple(D, getTriple(), D.SysRoot);
  361. addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include/" + MultiarchTriple);
  362. }
  363. addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
  364. }
  365. void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  366. ArgStringList &CC1Args) const {
  367. if (!DriverArgs.hasArg(options::OPT_nostdlibinc) &&
  368. !DriverArgs.hasArg(options::OPT_nostdincxx)) {
  369. if (getTriple().getOS() != llvm::Triple::UnknownOS) {
  370. const std::string MultiarchTriple =
  371. getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
  372. addSystemInclude(DriverArgs, CC1Args,
  373. getDriver().SysRoot + "/include/" + MultiarchTriple +
  374. "/c++/v1");
  375. }
  376. addSystemInclude(DriverArgs, CC1Args,
  377. getDriver().SysRoot + "/include/c++/v1");
  378. }
  379. }
  380. void WebAssembly::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
  381. llvm::opt::ArgStringList &CmdArgs) const {
  382. switch (GetCXXStdlibType(Args)) {
  383. case ToolChain::CST_Libcxx:
  384. CmdArgs.push_back("-lc++");
  385. CmdArgs.push_back("-lc++abi");
  386. break;
  387. case ToolChain::CST_Libstdcxx:
  388. llvm_unreachable("invalid stdlib name");
  389. }
  390. }
  391. SanitizerMask WebAssembly::getSupportedSanitizers() const {
  392. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  393. if (getTriple().isOSEmscripten()) {
  394. Res |= SanitizerKind::Vptr | SanitizerKind::Leak | SanitizerKind::Address;
  395. }
  396. return Res;
  397. }
  398. Tool *WebAssembly::buildLinker() const {
  399. return new tools::wasm::Linker(*this);
  400. }