encoder.cc 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/signature.h"

#include "src/handles.h"
#include "src/v8.h"
#include "src/zone-containers.h"

#include "src/wasm/ast-decoder.h"
#include "src/wasm/encoder.h"
13
#include "src/wasm/leb-helper.h"
14
#include "src/wasm/wasm-macro-gen.h"
15 16 17 18 19
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-opcodes.h"

#include "src/v8memory.h"

20 21 22
#if DEBUG
#define TRACE(...)                                    \
  do {                                                \
23
    if (FLAG_trace_wasm_encoder) PrintF(__VA_ARGS__); \
24 25 26 27 28
  } while (false)
#else
#define TRACE(...)
#endif

29 30 31 32
namespace v8 {
namespace internal {
namespace wasm {

33 34 35
// Emit a section name and the size as a padded varint that can be patched
// later.
size_t EmitSection(WasmSection::Code code, ZoneBuffer& buffer) {
36 37 38 39
  // Emit the section name.
  const char* name = WasmSection::getName(code);
  TRACE("emit section: %s\n", name);
  size_t length = WasmSection::getNameLength(code);
40 41
  buffer.write_size(length);  // Section name string size.
  buffer.write(reinterpret_cast<const byte*>(name), length);
42

43
  // Emit a placeholder for the length.
44 45
  return buffer.reserve_u32v();
}
46

47 48 49 50
// Patch the size of a section after it's finished.
void FixupSection(ZoneBuffer& buffer, size_t start) {
  buffer.patch_u32v(start, static_cast<uint32_t>(buffer.offset() - start -
                                                 kPaddedVarInt32Size));
51
}
52

53 54 55 56 57 58 59
WasmFunctionBuilder::WasmFunctionBuilder(WasmModuleBuilder* builder)
    : builder_(builder),
      locals_(builder->zone()),
      signature_index_(0),
      exported_(0),
      body_(builder->zone()),
      name_(builder->zone()) {}
60

61 62 63 64 65 66 67 68
void WasmFunctionBuilder::EmitVarInt(uint32_t val) {
  byte buffer[8];
  byte* ptr = buffer;
  LEBHelper::write_u32v(&ptr, val);
  for (byte* p = buffer; p < ptr; p++) {
    body_.push_back(*p);
  }
}
69

70 71 72
void WasmFunctionBuilder::SetSignature(FunctionSig* sig) {
  DCHECK(!locals_.has_sig());
  locals_.set_sig(sig);
73
  signature_index_ = builder_->AddSignature(sig);
74 75
}

76 77 78
uint32_t WasmFunctionBuilder::AddLocal(LocalType type) {
  DCHECK(locals_.has_sig());
  return locals_.AddLocals(1, type);
79 80
}

81 82 83 84 85 86 87
void WasmFunctionBuilder::EmitGetLocal(uint32_t local_index) {
  EmitWithVarInt(kExprGetLocal, local_index);
}

void WasmFunctionBuilder::EmitSetLocal(uint32_t local_index) {
  EmitWithVarInt(kExprSetLocal, local_index);
}
88

89
void WasmFunctionBuilder::EmitCode(const byte* code, uint32_t code_size) {
ritesht's avatar
ritesht committed
90
  for (size_t i = 0; i < code_size; ++i) {
91 92 93 94 95 96 97 98 99 100 101 102 103
    body_.push_back(code[i]);
  }
}

void WasmFunctionBuilder::Emit(WasmOpcode opcode) {
  body_.push_back(static_cast<byte>(opcode));
}

void WasmFunctionBuilder::EmitWithU8(WasmOpcode opcode, const byte immediate) {
  body_.push_back(static_cast<byte>(opcode));
  body_.push_back(immediate);
}

104 105 106 107 108 109 110
void WasmFunctionBuilder::EmitWithU8U8(WasmOpcode opcode, const byte imm1,
                                       const byte imm2) {
  body_.push_back(static_cast<byte>(opcode));
  body_.push_back(imm1);
  body_.push_back(imm2);
}

111 112 113
void WasmFunctionBuilder::EmitWithVarInt(WasmOpcode opcode,
                                         uint32_t immediate) {
  body_.push_back(static_cast<byte>(opcode));
114
  EmitVarInt(immediate);
115
}
116

117 118 119 120 121 122 123 124 125 126
void WasmFunctionBuilder::EmitI32Const(int32_t value) {
  // TODO(titzer): variable-length signed and unsigned i32 constants.
  if (-128 <= value && value <= 127) {
    EmitWithU8(kExprI8Const, static_cast<byte>(value));
  } else {
    byte code[] = {WASM_I32V_5(value)};
    EmitCode(code, sizeof(code));
  }
}

127
void WasmFunctionBuilder::SetExported() { exported_ = true; }
128

129
void WasmFunctionBuilder::SetName(const char* name, int name_length) {
130 131
  name_.clear();
  if (name_length > 0) {
ritesht's avatar
ritesht committed
132
    for (int i = 0; i < name_length; ++i) {
133 134 135 136 137
      name_.push_back(*(name + i));
    }
  }
}

138
void WasmFunctionBuilder::WriteSignature(ZoneBuffer& buffer) const {
139
  buffer.write_u32v(signature_index_);
140 141
}

142
void WasmFunctionBuilder::WriteExport(ZoneBuffer& buffer,
143 144 145 146 147 148
                                      uint32_t func_index) const {
  if (exported_) {
    buffer.write_u32v(func_index);
    buffer.write_size(name_.size());
    if (name_.size() > 0) {
      buffer.write(reinterpret_cast<const byte*>(&name_[0]), name_.size());
149
    }
150
  }
151
}
152

153
void WasmFunctionBuilder::WriteBody(ZoneBuffer& buffer) const {
154 155 156 157 158 159
  size_t locals_size = locals_.Size();
  buffer.write_size(locals_size + body_.size());
  buffer.EnsureSpace(locals_size);
  byte** ptr = buffer.pos_ptr();
  locals_.Emit(*ptr);
  (*ptr) += locals_size;  // UGLY: manual bump of position pointer
160
  if (body_.size() > 0) {
161
    buffer.write(&body_[0], body_.size());
162 163 164 165 166 167
  }
}

WasmDataSegmentEncoder::WasmDataSegmentEncoder(Zone* zone, const byte* data,
                                               uint32_t size, uint32_t dest)
    : data_(zone), dest_(dest) {
ritesht's avatar
ritesht committed
168
  for (size_t i = 0; i < size; ++i) {
169 170 171 172
    data_.push_back(data[i]);
  }
}

173 174 175 176
void WasmDataSegmentEncoder::Write(ZoneBuffer& buffer) const {
  buffer.write_u32v(dest_);
  buffer.write_u32v(static_cast<uint32_t>(data_.size()));
  buffer.write(&data_[0], data_.size());
177 178 179 180 181
}

WasmModuleBuilder::WasmModuleBuilder(Zone* zone)
    : zone_(zone),
      signatures_(zone),
182
      imports_(zone),
183 184 185 186
      functions_(zone),
      data_segments_(zone),
      indirect_functions_(zone),
      globals_(zone),
187 188
      signature_map_(zone),
      start_function_index_(-1) {}
189

190
uint32_t WasmModuleBuilder::AddFunction() {
191
  functions_.push_back(new (zone_) WasmFunctionBuilder(this));
192
  return static_cast<uint32_t>(functions_.size() - 1);
193 194 195 196 197 198 199 200 201 202 203 204 205 206
}

WasmFunctionBuilder* WasmModuleBuilder::FunctionAt(size_t index) {
  if (functions_.size() > index) {
    return functions_.at(index);
  } else {
    return nullptr;
  }
}

void WasmModuleBuilder::AddDataSegment(WasmDataSegmentEncoder* data) {
  data_segments_.push_back(data);
}

207 208 209 210 211 212
bool WasmModuleBuilder::CompareFunctionSigs::operator()(FunctionSig* a,
                                                        FunctionSig* b) const {
  if (a->return_count() < b->return_count()) return true;
  if (a->return_count() > b->return_count()) return false;
  if (a->parameter_count() < b->parameter_count()) return true;
  if (a->parameter_count() > b->parameter_count()) return false;
213
  for (size_t r = 0; r < a->return_count(); r++) {
214 215
    if (a->GetReturn(r) < b->GetReturn(r)) return true;
    if (a->GetReturn(r) > b->GetReturn(r)) return false;
216 217
  }
  for (size_t p = 0; p < a->parameter_count(); p++) {
218 219
    if (a->GetParam(p) < b->GetParam(p)) return true;
    if (a->GetParam(p) > b->GetParam(p)) return false;
220
  }
221
  return false;
222 223
}

224
uint32_t WasmModuleBuilder::AddSignature(FunctionSig* sig) {
225 226 227 228
  SignatureMap::iterator pos = signature_map_.find(sig);
  if (pos != signature_map_.end()) {
    return pos->second;
  } else {
229
    uint32_t index = static_cast<uint32_t>(signatures_.size());
230 231 232 233 234 235
    signature_map_[sig] = index;
    signatures_.push_back(sig);
    return index;
  }
}

236
void WasmModuleBuilder::AddIndirectFunction(uint32_t index) {
237 238 239
  indirect_functions_.push_back(index);
}

240 241 242 243 244 245
uint32_t WasmModuleBuilder::AddImport(const char* name, int name_length,
                                      FunctionSig* sig) {
  imports_.push_back({AddSignature(sig), name, name_length});
  return static_cast<uint32_t>(imports_.size() - 1);
}

246
void WasmModuleBuilder::MarkStartFunction(uint32_t index) {
247 248
  start_function_index_ = index;
}
249

250
uint32_t WasmModuleBuilder::AddGlobal(LocalType type, bool exported) {
251 252 253 254
  globals_.push_back(std::make_pair(type, exported));
  return static_cast<uint32_t>(globals_.size() - 1);
}

255
void WasmModuleBuilder::WriteTo(ZoneBuffer& buffer) const {
256
  uint32_t exports = 0;
257

258
  // == Emit magic =============================================================
259
  TRACE("emit magic\n");
260 261
  buffer.write_u32(kWasmMagic);
  buffer.write_u32(kWasmVersion);
262

263
  // == Emit signatures ========================================================
264
  if (signatures_.size() > 0) {
265 266
    size_t start = EmitSection(WasmSection::Code::Signatures, buffer);
    buffer.write_size(signatures_.size());
267 268

    for (FunctionSig* sig : signatures_) {
269 270
      buffer.write_u8(kWasmFunctionTypeForm);
      buffer.write_size(sig->parameter_count());
271
      for (size_t j = 0; j < sig->parameter_count(); j++) {
272
        buffer.write_u8(WasmOpcodes::LocalTypeCodeFor(sig->GetParam(j)));
273
      }
274
      buffer.write_size(sig->return_count());
275
      for (size_t j = 0; j < sig->return_count(); j++) {
276
        buffer.write_u8(WasmOpcodes::LocalTypeCodeFor(sig->GetReturn(j)));
277
      }
278
    }
279 280 281 282 283 284 285 286 287 288
    FixupSection(buffer, start);
  }

  // == Emit globals ===========================================================
  if (globals_.size() > 0) {
    size_t start = EmitSection(WasmSection::Code::Globals, buffer);
    buffer.write_size(globals_.size());

    for (auto global : globals_) {
      buffer.write_u32v(0);  // Length of the global name.
289
      buffer.write_u8(WasmOpcodes::LocalTypeCodeFor(global.first));
290 291 292
      buffer.write_u8(global.second);
    }
    FixupSection(buffer, start);
293 294
  }

295
  // == Emit imports ===========================================================
296
  if (imports_.size() > 0) {
297 298
    size_t start = EmitSection(WasmSection::Code::ImportTable, buffer);
    buffer.write_size(imports_.size());
299
    for (auto import : imports_) {
300 301 302 303 304
      buffer.write_u32v(import.sig_index);
      buffer.write_u32v(import.name_length);
      buffer.write(reinterpret_cast<const byte*>(import.name),
                   import.name_length);
      buffer.write_u32v(0);
305
    }
306
    FixupSection(buffer, start);
307 308
  }

309
  // == Emit function signatures ===============================================
310
  if (functions_.size() > 0) {
311 312 313 314 315
    size_t start = EmitSection(WasmSection::Code::FunctionSignatures, buffer);
    buffer.write_size(functions_.size());
    for (auto function : functions_) {
      function->WriteSignature(buffer);
      if (function->exported()) exports++;
316
    }
317
    FixupSection(buffer, start);
318 319
  }

320
  // == emit function table ====================================================
321
  if (indirect_functions_.size() > 0) {
322 323
    size_t start = EmitSection(WasmSection::Code::FunctionTable, buffer);
    buffer.write_size(indirect_functions_.size());
324 325

    for (auto index : indirect_functions_) {
326
      buffer.write_u32v(index);
327
    }
328
    FixupSection(buffer, start);
329 330
  }

331
  // == emit memory declaration ================================================
332
  {
333 334 335 336
    size_t start = EmitSection(WasmSection::Code::Memory, buffer);
    buffer.write_u32v(16);  // min memory size
    buffer.write_u32v(16);  // max memory size
    buffer.write_u8(0);     // memory export
337
    static_assert(kDeclMemorySize == 3, "memory size must match emit above");
338
    FixupSection(buffer, start);
339 340
  }

341 342 343 344 345 346 347 348 349 350 351 352
  // == emit exports ===========================================================
  if (exports > 0) {
    size_t start = EmitSection(WasmSection::Code::ExportTable, buffer);
    buffer.write_u32v(exports);
    uint32_t index = 0;
    for (auto function : functions_) {
      function->WriteExport(buffer, index++);
    }
    FixupSection(buffer, start);
  }

  // == emit start function index ==============================================
353
  if (start_function_index_ >= 0) {
354 355 356
    size_t start = EmitSection(WasmSection::Code::StartFunction, buffer);
    buffer.write_u32v(start_function_index_);
    FixupSection(buffer, start);
357 358
  }

359 360 361 362 363 364 365 366 367 368 369
  // == emit code ==============================================================
  if (functions_.size() > 0) {
    size_t start = EmitSection(WasmSection::Code::FunctionBodies, buffer);
    buffer.write_size(functions_.size());
    for (auto function : functions_) {
      function->WriteBody(buffer);
    }
    FixupSection(buffer, start);
  }

  // == emit data segments =====================================================
370
  if (data_segments_.size() > 0) {
371 372
    size_t start = EmitSection(WasmSection::Code::DataSegments, buffer);
    buffer.write_size(data_segments_.size());
373 374

    for (auto segment : data_segments_) {
375
      segment->Write(buffer);
376
    }
377
    FixupSection(buffer, start);
378 379 380 381 382
  }
}
}  // namespace wasm
}  // namespace internal
}  // namespace v8