1 //===-- WebAssemblyWasmObjectWriter.cpp - WebAssembly Wasm Writer ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file handles Wasm-specific object emission, converting LLVM's
12 /// internal fixups into the appropriate relocations.
14 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "MCTargetDesc/WebAssemblyFixupKinds.h"
18 #include "llvm/MC/MCFixup.h"
19 #include "llvm/MC/MCSymbolWasm.h"
20 #include "llvm/MC/MCWasmObjectWriter.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/Wasm.h"
27 class WebAssemblyWasmObjectWriter final : public MCWasmObjectTargetWriter {
29 explicit WebAssemblyWasmObjectWriter(bool Is64Bit);
32 unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
33 const MCFixup &Fixup, bool IsPCRel) const override;
35 } // end anonymous namespace
37 WebAssemblyWasmObjectWriter::WebAssemblyWasmObjectWriter(bool Is64Bit)
38 : MCWasmObjectTargetWriter(Is64Bit) {}
40 // Test whether the given expression computes a function address.
41 static bool IsFunctionExpr(const MCExpr *Expr) {
42 if (const MCSymbolRefExpr *SyExp =
43 dyn_cast<MCSymbolRefExpr>(Expr))
44 return cast<MCSymbolWasm>(SyExp->getSymbol()).isFunction();
46 if (const MCBinaryExpr *BinOp =
47 dyn_cast<MCBinaryExpr>(Expr))
48 return IsFunctionExpr(BinOp->getLHS()) != IsFunctionExpr(BinOp->getRHS());
50 if (const MCUnaryExpr *UnOp =
51 dyn_cast<MCUnaryExpr>(Expr))
52 return IsFunctionExpr(UnOp->getSubExpr());
57 unsigned WebAssemblyWasmObjectWriter::getRelocType(MCContext &Ctx,
58 const MCValue &Target,
61 // WebAssembly functions are not allocated in the data address space. To
62 // resolve a pointer to a function, we must use a special relocation type.
63 bool IsFunction = IsFunctionExpr(Fixup.getValue());
66 switch (unsigned(Fixup.getKind())) {
67 case WebAssembly::fixup_code_sleb128_i32:
69 return wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB;
70 return wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB;
71 case WebAssembly::fixup_code_sleb128_i64:
72 llvm_unreachable("fixup_sleb128_i64 not implemented yet");
73 case WebAssembly::fixup_code_uleb128_i32:
75 return wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB;
76 return wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB;
79 return wasm::R_WEBASSEMBLY_TABLE_INDEX_I32;
80 return wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32;
82 llvm_unreachable("FK_Data_8 not implemented yet");
84 llvm_unreachable("unimplemented fixup kind");
88 MCObjectWriter *llvm::createWebAssemblyWasmObjectWriter(raw_pwrite_stream &OS,
90 MCWasmObjectTargetWriter *MOTW = new WebAssemblyWasmObjectWriter(Is64Bit);
91 return createWasmObjectWriter(MOTW, OS);