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/IR/LegacyPassManager.h>
18#include <llvm/IR/Module.h>
19#include <llvm/MC/TargetRegistry.h>
20#include <llvm/Target/TargetMachine.h>
21#include <llvm/TargetParser/Triple.h>
22
24
25#include <string>
26
27namespace lld {
28enum Flavor {
30 Gnu, // -flavor gnu
31 MinGW, // -flavor gnu MinGW
32 WinLink, // -flavor link
33 Darwin, // -flavor darwin
34 Wasm, // -flavor wasm
35};
36
37using Driver = bool (*)(llvm::ArrayRef<const char *>, llvm::raw_ostream &,
38 llvm::raw_ostream &, bool, bool);
39
44
45struct Result {
48};
49
50Result lldMain(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
51 llvm::raw_ostream &stderrOS, llvm::ArrayRef<DriverDef> drivers);
52[[noreturn]] void exitLld(int val);
53
54namespace wasm {
55bool link(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
56 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
57} // namespace wasm
58} // namespace lld
59
60#include <dlfcn.h>
61
62namespace clang {
63
65 llvm::ErrorAsOutParameter EAO(&Err);
66
67 if (Err)
68 return;
69
70 if (auto EC =
71 llvm::sys::fs::createUniqueDirectory("clang-wasm-exec-", TempDir))
72 Err = llvm::make_error<llvm::StringError>(
73 "Failed to create temporary directory for Wasm executor: " +
74 EC.message(),
75 llvm::inconvertibleErrorCode());
76}
77
79
81 std::string ErrorString;
82
83 const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
84 PTU.TheModule->getTargetTriple(), ErrorString);
85 if (!Target) {
86 return llvm::make_error<llvm::StringError>("Failed to create Wasm Target: ",
87 llvm::inconvertibleErrorCode());
88 }
89
90 llvm::TargetOptions TO = llvm::TargetOptions();
91 llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
92 PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
93
94 llvm::SmallString<256> ObjectFileName(TempDir);
95 llvm::sys::path::append(ObjectFileName, PTU.TheModule->getName() + ".o");
96
97 llvm::SmallString<256> BinaryFileName(TempDir);
98 llvm::sys::path::append(BinaryFileName, PTU.TheModule->getName() + ".wasm");
99
100 std::error_code EC;
101 llvm::raw_fd_ostream ObjectFileOutput(ObjectFileName, EC);
102
103 if (EC)
104 return llvm::errorCodeToError(EC);
105
106 llvm::legacy::PassManager PM;
107 if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
108 llvm::CodeGenFileType::ObjectFile)) {
109 return llvm::make_error<llvm::StringError>(
110 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
111 }
112
113 if (!PM.run(*PTU.TheModule)) {
114
115 return llvm::make_error<llvm::StringError>("Failed to emit Wasm object.",
116 llvm::inconvertibleErrorCode());
117 }
118
119 ObjectFileOutput.close();
120
121 std::string Emulation = "-m";
122 Emulation +=
123 llvm::Triple(PTU.TheModule->getTargetTriple()).getArchName().str();
124 std::vector<const char *> LinkerArgs = {"wasm-ld",
125 Emulation.c_str(),
126 "-shared",
127 "--import-memory",
128 "--stack-first",
129 "--allow-undefined",
130 ObjectFileName.c_str(),
131 "-o",
132 BinaryFileName.c_str()};
133
134 const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
135 std::vector<lld::DriverDef> WasmDriverArgs;
136 WasmDriverArgs.push_back(WasmDriver);
138 lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), WasmDriverArgs);
139
140 // A fatal error may have recovered control flow without restoring LLD's
141 // process state. Do not allow another incremental link in that case.
142 if (!Result.canRunAgain)
143 lld::exitLld(Result.retCode);
144
145 if (Result.retCode)
146 return llvm::make_error<llvm::StringError>(
147 "Failed to link incremental module", llvm::inconvertibleErrorCode());
148
149 void *LoadedLibModule =
150 dlopen(BinaryFileName.c_str(), RTLD_NOW | RTLD_GLOBAL);
151 if (LoadedLibModule == nullptr) {
152 llvm::errs() << dlerror() << '\n';
153 return llvm::make_error<llvm::StringError>(
154 "Failed to load incremental module", llvm::inconvertibleErrorCode());
155 }
156
157 return llvm::Error::success();
158}
159
161 return llvm::make_error<llvm::StringError>("Not implemented yet",
162 llvm::inconvertibleErrorCode());
163}
164
166 // This seems to be automatically done when using dlopen()
167 return llvm::Error::success();
168}
169
171 // Can't call cleanUp through IncrementalExecutor as it
172 // tries to deinitialize JIT which hasn't been initialized
173 return llvm::Error::success();
174}
175
178 SymbolNameKind NameKind) const {
179 void *Sym = dlsym(RTLD_DEFAULT, Name.str().c_str());
180 if (!Sym) {
181 return llvm::make_error<llvm::StringError>("dlsym failed for symbol: " +
182 Name.str(),
183 llvm::inconvertibleErrorCode());
184 }
185
186 return llvm::orc::ExecutorAddr::fromPtr(Sym);
187}
188
189llvm::Error WasmIncrementalExecutor::LoadDynamicLibrary(const char *name) {
190 void *handle = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
191 if (!handle) {
192 llvm::errs() << dlerror() << '\n';
193 return llvm::make_error<llvm::StringError>("Failed to load dynamic library",
194 llvm::inconvertibleErrorCode());
195 }
196 return llvm::Error::success();
197}
198} // namespace clang
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const override
Definition Wasm.cpp:177
llvm::Error addModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:80
llvm::Error runCtors() const override
Definition Wasm.cpp:165
WasmIncrementalExecutor(llvm::Error &Err)
Definition Wasm.cpp:64
llvm::Error LoadDynamicLibrary(const char *name) override
Definition Wasm.cpp:189
llvm::Error removeModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:160
llvm::Error cleanUp() override
Definition Wasm.cpp:170
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:27
Flavor
Definition Wasm.cpp:28
@ Darwin
Definition Wasm.cpp:33
@ MinGW
Definition Wasm.cpp:31
@ Invalid
Definition Wasm.cpp:29
@ WinLink
Definition Wasm.cpp:32
@ Gnu
Definition Wasm.cpp:30
@ Wasm
Definition Wasm.cpp:34
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:37
#define noreturn
Definition stdnoreturn.h:17
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:42
Flavor f
Definition Wasm.cpp:41
bool canRunAgain
Definition Wasm.cpp:47
int retCode
Definition Wasm.cpp:46