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