clang 24.0.0git
Wasm.cpp
Go to the documentation of this file.
1//===----------------- Wasm.cpp - Wasm Interpreter --------------*- 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// This file implements interpreter support for code execution in WebAssembly.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Wasm.h"
14
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/Path.h"
17#include "llvm/TargetParser/Host.h"
18#include <llvm/IR/LLVMContext.h>
19#include <llvm/IR/LegacyPassManager.h>
20#include <llvm/IR/Module.h>
21#include <llvm/MC/TargetRegistry.h>
22#include <llvm/Target/TargetMachine.h>
23#include <llvm/TargetParser/Triple.h>
24
26
27#include <string>
28
29namespace lld {
30enum Flavor {
32 Gnu, // -flavor gnu
33 MinGW, // -flavor gnu MinGW
34 WinLink, // -flavor link
35 Darwin, // -flavor darwin
36 Wasm, // -flavor wasm
37};
38
39using Driver = bool (*)(llvm::ArrayRef<const char *>, llvm::raw_ostream &,
40 llvm::raw_ostream &, bool, bool);
41
46
47struct Result {
50};
51
52Result lldMain(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
53 llvm::raw_ostream &stderrOS, llvm::ArrayRef<DriverDef> drivers);
54[[noreturn]] void exitLld(int val);
55
56namespace wasm {
57bool link(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
58 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
59} // namespace wasm
60} // namespace lld
61
62#include <dlfcn.h>
63
64namespace clang {
65
66std::unique_ptr<IncrementalExecutorBuilder>
68 return std::make_unique<WasmIncrementalExecutorBuilder>();
69}
70
71llvm::Error
73 const Options &Opts) {
74 if (Opts.IsOutOfProcess)
75 return llvm::createStringError("Out-of-process execution is not supported "
76 "by the WebAssembly executor");
77 return llvm::Error::success();
78}
79
82 return llvm::Triple(llvm::sys::getProcessTriple());
83}
84
86WasmIncrementalExecutorBuilder::createExecutor(
87 llvm::orc::ThreadSafeContext &TSC, const clang::TargetInfo &TI) {
88 llvm::Error Err = llvm::Error::success();
89 std::unique_ptr<IncrementalExecutor> Executor =
90 std::make_unique<WasmIncrementalExecutor>(Err);
91 if (Err)
92 return std::move(Err);
93 return std::move(Executor);
94}
95
97 llvm::ErrorAsOutParameter EAO(&Err);
98
99 if (Err)
100 return;
101
102 if (auto EC =
103 llvm::sys::fs::createUniqueDirectory("clang-wasm-exec-", TempDir))
104 Err = llvm::make_error<llvm::StringError>(
105 "Failed to create temporary directory for Wasm executor: " +
106 EC.message(),
107 llvm::inconvertibleErrorCode());
108}
109
111
113 std::string ErrorString;
114
115 const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
116 PTU.TheModule->getTargetTriple(), ErrorString);
117 if (!Target) {
118 return llvm::make_error<llvm::StringError>("Failed to create Wasm Target: ",
119 llvm::inconvertibleErrorCode());
120 }
121
122 llvm::TargetOptions TO = llvm::TargetOptions();
123 TO.MCOptions.LibraryOptions =
124 &PTU.TheModule->getContext().getLibraryOptions();
125 llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
126 PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
127
128 llvm::SmallString<256> ObjectFileName(TempDir);
129 llvm::sys::path::append(ObjectFileName, PTU.TheModule->getName() + ".o");
130
131 llvm::SmallString<256> BinaryFileName(TempDir);
132 llvm::sys::path::append(BinaryFileName, PTU.TheModule->getName() + ".wasm");
133
134 std::error_code EC;
135 llvm::raw_fd_ostream ObjectFileOutput(ObjectFileName, EC);
136
137 if (EC)
138 return llvm::errorCodeToError(EC);
139
140 llvm::legacy::PassManager PM;
141 if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
142 llvm::CodeGenFileType::ObjectFile)) {
143 return llvm::make_error<llvm::StringError>(
144 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
145 }
146
147 if (!PM.run(*PTU.TheModule)) {
148
149 return llvm::make_error<llvm::StringError>("Failed to emit Wasm object.",
150 llvm::inconvertibleErrorCode());
151 }
152
153 ObjectFileOutput.close();
154
155 std::string Emulation = "-m";
156 Emulation +=
157 llvm::Triple(PTU.TheModule->getTargetTriple()).getArchName().str();
158 std::vector<const char *> LinkerArgs = {"wasm-ld",
159 Emulation.c_str(),
160 "-shared",
161 "--import-memory",
162 "--stack-first",
163 "--allow-undefined",
164 ObjectFileName.c_str(),
165 "-o",
166 BinaryFileName.c_str()};
167
168 const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
169 std::vector<lld::DriverDef> WasmDriverArgs;
170 WasmDriverArgs.push_back(WasmDriver);
172 lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), WasmDriverArgs);
173
174 // A fatal error may have recovered control flow without restoring LLD's
175 // process state. Do not allow another incremental link in that case.
176 if (!Result.canRunAgain)
177 lld::exitLld(Result.retCode);
178
179 if (Result.retCode)
180 return llvm::make_error<llvm::StringError>(
181 "Failed to link incremental module", llvm::inconvertibleErrorCode());
182
183 void *LoadedLibModule =
184 dlopen(BinaryFileName.c_str(), RTLD_NOW | RTLD_GLOBAL);
185 if (LoadedLibModule == nullptr) {
186 llvm::errs() << dlerror() << '\n';
187 return llvm::make_error<llvm::StringError>(
188 "Failed to load incremental module", llvm::inconvertibleErrorCode());
189 }
190
191 return llvm::Error::success();
192}
193
195 return llvm::make_error<llvm::StringError>("Not implemented yet",
196 llvm::inconvertibleErrorCode());
197}
198
200 // This seems to be automatically done when using dlopen()
201 return llvm::Error::success();
202}
203
205 // Can't call cleanUp through IncrementalExecutor as it
206 // tries to deinitialize JIT which hasn't been initialized
207 return llvm::Error::success();
208}
209
212 SymbolNameKind NameKind) const {
213 void *Sym = dlsym(RTLD_DEFAULT, Name.str().c_str());
214 if (!Sym) {
215 return llvm::make_error<llvm::StringError>("dlsym failed for symbol: " +
216 Name.str(),
217 llvm::inconvertibleErrorCode());
218 }
219
220 return llvm::orc::ExecutorAddr::fromPtr(Sym);
221}
222
223llvm::Error WasmIncrementalExecutor::LoadDynamicLibrary(const char *name) {
224 void *handle = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
225 if (!handle) {
226 llvm::errs() << dlerror() << '\n';
227 return llvm::make_error<llvm::StringError>("Failed to load dynamic library",
228 llvm::inconvertibleErrorCode());
229 }
230 return llvm::Error::success();
231}
232} // namespace clang
Create a pre-configured CompilerInstance for incremental processing.
Definition Interpreter.h:54
static std::unique_ptr< IncrementalExecutorBuilder > createDefault()
Create the default builder for the platform clangInterpreter is built for.
Exposes information about the current target.
Definition TargetInfo.h:228
llvm::Error configure(IncrementalCompilerBuilder &CB, const Options &Opts) override
Apply execution options and configure the compiler for this backend.
Definition Wasm.cpp:72
llvm::Expected< llvm::Triple > getHostJITTriple() const override
Return the host triple used by this backend.
Definition Wasm.cpp:81
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const override
Definition Wasm.cpp:211
llvm::Error addModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:112
llvm::Error runCtors() const override
Definition Wasm.cpp:199
WasmIncrementalExecutor(llvm::Error &Err)
Definition Wasm.cpp:96
llvm::Error LoadDynamicLibrary(const char *name) override
Definition Wasm.cpp:223
llvm::Error removeModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:194
llvm::Error cleanUp() override
Definition Wasm.cpp:204
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool link(llvm::ArrayRef< const char * > args, llvm::raw_ostream &stdoutOS, llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput)
Definition Wasm.cpp:29
Flavor
Definition Wasm.cpp:30
@ Darwin
Definition Wasm.cpp:35
@ MinGW
Definition Wasm.cpp:33
@ Invalid
Definition Wasm.cpp:31
@ WinLink
Definition Wasm.cpp:34
@ Gnu
Definition Wasm.cpp:32
@ Wasm
Definition Wasm.cpp:36
void exitLld(int val)
Result lldMain(llvm::ArrayRef< const char * > args, llvm::raw_ostream &stdoutOS, llvm::raw_ostream &stderrOS, llvm::ArrayRef< DriverDef > drivers)
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:39
#define noreturn
Definition stdnoreturn.h:17
Options passed to the backend when configuring execution.
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.
Driver d
Definition Wasm.cpp:44
Flavor f
Definition Wasm.cpp:43
bool canRunAgain
Definition Wasm.cpp:49
int retCode
Definition Wasm.cpp:48