function-body-decoder-impl.h 105 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 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.

#ifndef V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
#define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_

8 9 10
// Do only include this header for implementing new Interface of the
// WasmFullDecoder.

11
#include "src/base/platform/elapsed-timer.h"
12
#include "src/base/small-vector.h"
13
#include "src/bit-vector.h"
14
#include "src/wasm/decoder.h"
15
#include "src/wasm/function-body-decoder.h"
16
#include "src/wasm/wasm-features.h"
17 18
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-module.h"
19 20 21 22 23 24 25
#include "src/wasm/wasm-opcodes.h"

namespace v8 {
namespace internal {
namespace wasm {

struct WasmGlobal;
26
struct WasmException;
27

28 29 30 31 32
#define TRACE(...)                                    \
  do {                                                \
    if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
  } while (false)

33 34
#define TRACE_INST_FORMAT "  @%-8d #%-20s|"

35 36
// Return the evaluation of `condition` if validate==true, DCHECK that it's
// true and always return true otherwise.
37 38 39 40 41 42
#define VALIDATE(condition)       \
  (validate ? (condition) : [&] { \
    DCHECK(condition);            \
    return true;                  \
  }())

43
#define RET_ON_PROTOTYPE_OPCODE(feat)                                          \
44
  DCHECK(!this->module_ || this->module_->origin == kWasmOrigin);              \
45 46 47 48
  if (!this->enabled_.feat) {                                                  \
    this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \
  } else {                                                                     \
    this->detected_->feat = true;                                              \
49 50
  }

51
#define CHECK_PROTOTYPE_OPCODE(feat)                                           \
52
  DCHECK(!this->module_ || this->module_->origin == kWasmOrigin);              \
53 54
  if (!this->enabled_.feat) {                                                  \
    this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \
55
    break;                                                                     \
56 57
  } else {                                                                     \
    this->detected_->feat = true;                                              \
58 59 60 61 62 63
  }

#define OPCODE_ERROR(opcode, message)                                 \
  (this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \
                (message)))

64
#define ATOMIC_OP_LIST(V)                \
65
  V(AtomicNotify, Uint32)                \
66
  V(I32AtomicWait, Uint32)               \
67
  V(I64AtomicWait, Uint32)               \
68
  V(I32AtomicLoad, Uint32)               \
69
  V(I64AtomicLoad, Uint64)               \
70 71
  V(I32AtomicLoad8U, Uint8)              \
  V(I32AtomicLoad16U, Uint16)            \
72 73 74
  V(I64AtomicLoad8U, Uint8)              \
  V(I64AtomicLoad16U, Uint16)            \
  V(I64AtomicLoad32U, Uint32)            \
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  V(I32AtomicAdd, Uint32)                \
  V(I32AtomicAdd8U, Uint8)               \
  V(I32AtomicAdd16U, Uint16)             \
  V(I64AtomicAdd, Uint64)                \
  V(I64AtomicAdd8U, Uint8)               \
  V(I64AtomicAdd16U, Uint16)             \
  V(I64AtomicAdd32U, Uint32)             \
  V(I32AtomicSub, Uint32)                \
  V(I64AtomicSub, Uint64)                \
  V(I32AtomicSub8U, Uint8)               \
  V(I32AtomicSub16U, Uint16)             \
  V(I64AtomicSub8U, Uint8)               \
  V(I64AtomicSub16U, Uint16)             \
  V(I64AtomicSub32U, Uint32)             \
  V(I32AtomicAnd, Uint32)                \
  V(I64AtomicAnd, Uint64)                \
  V(I32AtomicAnd8U, Uint8)               \
  V(I32AtomicAnd16U, Uint16)             \
  V(I64AtomicAnd8U, Uint8)               \
  V(I64AtomicAnd16U, Uint16)             \
  V(I64AtomicAnd32U, Uint32)             \
  V(I32AtomicOr, Uint32)                 \
  V(I64AtomicOr, Uint64)                 \
  V(I32AtomicOr8U, Uint8)                \
  V(I32AtomicOr16U, Uint16)              \
  V(I64AtomicOr8U, Uint8)                \
  V(I64AtomicOr16U, Uint16)              \
  V(I64AtomicOr32U, Uint32)              \
  V(I32AtomicXor, Uint32)                \
  V(I64AtomicXor, Uint64)                \
  V(I32AtomicXor8U, Uint8)               \
  V(I32AtomicXor16U, Uint16)             \
  V(I64AtomicXor8U, Uint8)               \
  V(I64AtomicXor16U, Uint16)             \
  V(I64AtomicXor32U, Uint32)             \
  V(I32AtomicExchange, Uint32)           \
  V(I64AtomicExchange, Uint64)           \
  V(I32AtomicExchange8U, Uint8)          \
  V(I32AtomicExchange16U, Uint16)        \
  V(I64AtomicExchange8U, Uint8)          \
  V(I64AtomicExchange16U, Uint16)        \
  V(I64AtomicExchange32U, Uint32)        \
  V(I32AtomicCompareExchange, Uint32)    \
  V(I64AtomicCompareExchange, Uint64)    \
  V(I32AtomicCompareExchange8U, Uint8)   \
  V(I32AtomicCompareExchange16U, Uint16) \
  V(I64AtomicCompareExchange8U, Uint8)   \
  V(I64AtomicCompareExchange16U, Uint16) \
  V(I64AtomicCompareExchange32U, Uint32)
124

125 126
#define ATOMIC_STORE_OP_LIST(V) \
  V(I32AtomicStore, Uint32)     \
127
  V(I64AtomicStore, Uint64)     \
128
  V(I32AtomicStore8U, Uint8)    \
129 130 131 132
  V(I32AtomicStore16U, Uint16)  \
  V(I64AtomicStore8U, Uint8)    \
  V(I64AtomicStore16U, Uint16)  \
  V(I64AtomicStore32U, Uint32)
133

134
// Helpers for decoding different kinds of immediates which follow bytecodes.
135
template <Decoder::ValidateFlag validate>
136
struct LocalIndexImmediate {
137
  uint32_t index;
138
  ValueType type = kWasmStmt;
139
  uint32_t length;
140

141
  inline LocalIndexImmediate(Decoder* decoder, const byte* pc) {
142
    index = decoder->read_u32v<validate>(pc + 1, &length, "local index");
143 144 145
  }
};

146
template <Decoder::ValidateFlag validate>
147
struct ExceptionIndexImmediate {
148 149
  uint32_t index;
  const WasmException* exception = nullptr;
150
  uint32_t length;
151

152
  inline ExceptionIndexImmediate(Decoder* decoder, const byte* pc) {
153
    index = decoder->read_u32v<validate>(pc + 1, &length, "exception index");
154 155 156
  }
};

157
template <Decoder::ValidateFlag validate>
158
struct ImmI32Immediate {
159
  int32_t value;
160
  uint32_t length;
161
  inline ImmI32Immediate(Decoder* decoder, const byte* pc) {
162
    value = decoder->read_i32v<validate>(pc + 1, &length, "immi32");
163 164 165
  }
};

166
template <Decoder::ValidateFlag validate>
167
struct ImmI64Immediate {
168
  int64_t value;
169
  uint32_t length;
170
  inline ImmI64Immediate(Decoder* decoder, const byte* pc) {
171
    value = decoder->read_i64v<validate>(pc + 1, &length, "immi64");
172 173 174
  }
};

175
template <Decoder::ValidateFlag validate>
176
struct ImmF32Immediate {
177
  float value;
178
  uint32_t length = 4;
179
  inline ImmF32Immediate(Decoder* decoder, const byte* pc) {
180
    // Avoid bit_cast because it might not preserve the signalling bit of a NaN.
181
    uint32_t tmp = decoder->read_u32<validate>(pc + 1, "immf32");
182 183 184 185
    memcpy(&value, &tmp, sizeof(value));
  }
};

186
template <Decoder::ValidateFlag validate>
187
struct ImmF64Immediate {
188
  double value;
189
  uint32_t length = 8;
190
  inline ImmF64Immediate(Decoder* decoder, const byte* pc) {
191
    // Avoid bit_cast because it might not preserve the signalling bit of a NaN.
192
    uint64_t tmp = decoder->read_u64<validate>(pc + 1, "immf64");
193 194 195 196
    memcpy(&value, &tmp, sizeof(value));
  }
};

197
template <Decoder::ValidateFlag validate>
198
struct GlobalIndexImmediate {
199
  uint32_t index;
200 201
  ValueType type = kWasmStmt;
  const WasmGlobal* global = nullptr;
202
  uint32_t length;
203

204
  inline GlobalIndexImmediate(Decoder* decoder, const byte* pc) {
205
    index = decoder->read_u32v<validate>(pc + 1, &length, "global index");
206 207 208
  }
};

209
template <Decoder::ValidateFlag validate>
210
struct BlockTypeImmediate {
211
  uint32_t length = 1;
212 213 214
  ValueType type = kWasmStmt;
  uint32_t sig_index = 0;
  FunctionSig* sig = nullptr;
215

216 217
  inline BlockTypeImmediate(const WasmFeatures& enabled, Decoder* decoder,
                            const byte* pc) {
218
    uint8_t val = decoder->read_u8<validate>(pc + 1, "block type");
219
    if (!decode_local_type(val, &type)) {
220
      // Handle multi-value blocks.
221
      if (!VALIDATE(enabled.mv)) {
222
        decoder->error(pc + 1, "invalid block type");
223
        return;
224
      }
225
      if (!VALIDATE(decoder->ok())) return;
226 227 228 229 230
      int32_t index =
          decoder->read_i32v<validate>(pc + 1, &length, "block arity");
      if (!VALIDATE(length > 0 && index >= 0)) {
        decoder->error(pc + 1, "invalid block type index");
        return;
231
      }
232
      sig_index = static_cast<uint32_t>(index);
233 234
    }
  }
235

236
  // Decode a byte representing a local type. Return {false} if the encoded
237
  // byte was invalid or the start of a type index.
238
  inline bool decode_local_type(uint8_t val, ValueType* result) {
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    switch (static_cast<ValueTypeCode>(val)) {
      case kLocalVoid:
        *result = kWasmStmt;
        return true;
      case kLocalI32:
        *result = kWasmI32;
        return true;
      case kLocalI64:
        *result = kWasmI64;
        return true;
      case kLocalF32:
        *result = kWasmF32;
        return true;
      case kLocalF64:
        *result = kWasmF64;
        return true;
      case kLocalS128:
        *result = kWasmS128;
        return true;
258 259 260
      case kLocalAnyFunc:
        *result = kWasmAnyFunc;
        return true;
261 262 263
      case kLocalAnyRef:
        *result = kWasmAnyRef;
        return true;
264 265 266
      case kLocalExceptRef:
        *result = kWasmExceptRef;
        return true;
267
      default:
268
        *result = kWasmVar;
269 270 271
        return false;
    }
  }
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  uint32_t in_arity() const {
    if (type != kWasmVar) return 0;
    return static_cast<uint32_t>(sig->parameter_count());
  }
  uint32_t out_arity() const {
    if (type == kWasmStmt) return 0;
    if (type != kWasmVar) return 1;
    return static_cast<uint32_t>(sig->return_count());
  }
  ValueType in_type(uint32_t index) {
    DCHECK_EQ(kWasmVar, type);
    return sig->GetParam(index);
  }
  ValueType out_type(uint32_t index) {
    if (type == kWasmVar) return sig->GetReturn(index);
    DCHECK_NE(kWasmStmt, type);
    DCHECK_EQ(0, index);
    return type;
291 292 293
  }
};

294
template <Decoder::ValidateFlag validate>
295
struct BranchDepthImmediate {
296
  uint32_t depth;
297
  uint32_t length;
298 299
  inline BranchDepthImmediate(Decoder* decoder, const byte* pc) {
    depth = decoder->read_u32v<validate>(pc + 1, &length, "branch depth");
300 301 302
  }
};

303 304 305 306 307 308 309 310 311 312 313 314
template <Decoder::ValidateFlag validate>
struct BranchOnExceptionImmediate {
  BranchDepthImmediate<validate> depth;
  ExceptionIndexImmediate<validate> index;
  uint32_t length = 0;
  inline BranchOnExceptionImmediate(Decoder* decoder, const byte* pc)
      : depth(BranchDepthImmediate<validate>(decoder, pc)),
        index(ExceptionIndexImmediate<validate>(decoder, pc + depth.length)) {
    length = depth.length + index.length;
  }
};

315
template <Decoder::ValidateFlag validate>
316
struct CallIndirectImmediate {
317
  uint32_t table_index;
318
  uint32_t sig_index;
319
  FunctionSig* sig = nullptr;
320
  uint32_t length = 0;
321 322
  inline CallIndirectImmediate(const WasmFeatures enabled, Decoder* decoder,
                               const byte* pc) {
323
    uint32_t len = 0;
324
    sig_index = decoder->read_u32v<validate>(pc + 1, &len, "signature index");
325
    table_index = decoder->read_u8<validate>(pc + 1 + len, "table index");
326
    if (!VALIDATE(table_index == 0 || enabled.anyref)) {
327 328
      decoder->errorf(pc + 1 + len, "expected table index 0, found %u",
                      table_index);
329 330 331 332 333
    }
    length = 1 + len;
  }
};

334
template <Decoder::ValidateFlag validate>
335
struct CallFunctionImmediate {
336
  uint32_t index;
337
  FunctionSig* sig = nullptr;
338
  uint32_t length;
339
  inline CallFunctionImmediate(Decoder* decoder, const byte* pc) {
340
    index = decoder->read_u32v<validate>(pc + 1, &length, "function index");
341 342 343
  }
};

344 345 346 347 348 349 350 351 352
template <Decoder::ValidateFlag validate>
struct FunctionIndexImmediate {
  uint32_t index = 0;
  uint32_t length = 1;
  inline FunctionIndexImmediate(Decoder* decoder, const byte* pc) {
    index = decoder->read_u32v<validate>(pc + 1, &length, "function index");
  }
};

353
template <Decoder::ValidateFlag validate>
354
struct MemoryIndexImmediate {
355
  uint32_t index = 0;
356
  uint32_t length = 1;
357
  inline MemoryIndexImmediate() = default;
358
  inline MemoryIndexImmediate(Decoder* decoder, const byte* pc) {
359
    index = decoder->read_u8<validate>(pc + 1, "memory index");
360
    if (!VALIDATE(index == 0)) {
361
      decoder->errorf(pc + 1, "expected memory index 0, found %u", index);
362 363 364 365
    }
  }
};

366 367
template <Decoder::ValidateFlag validate>
struct TableIndexImmediate {
368
  uint32_t index = 0;
369
  unsigned length = 1;
370
  inline TableIndexImmediate() = default;
371 372 373 374 375
  inline TableIndexImmediate(Decoder* decoder, const byte* pc) {
    index = decoder->read_u8<validate>(pc + 1, "table index");
  }
};

376
template <Decoder::ValidateFlag validate>
377
struct BranchTableImmediate {
378 379 380
  uint32_t table_count;
  const byte* start;
  const byte* table;
381
  inline BranchTableImmediate(Decoder* decoder, const byte* pc) {
382
    DCHECK_EQ(kExprBrTable, decoder->read_u8<validate>(pc, "opcode"));
383
    start = pc + 1;
384
    uint32_t len = 0;
385
    table_count = decoder->read_u32v<validate>(pc + 1, &len, "table count");
386
    table = pc + 1 + len;
387 388 389 390
  }
};

// A helper to iterate over a branch table.
391
template <Decoder::ValidateFlag validate>
392 393
class BranchTableIterator {
 public:
394
  uint32_t cur_index() { return index_; }
395
  bool has_next() { return VALIDATE(decoder_->ok()) && index_ <= table_count_; }
396 397 398
  uint32_t next() {
    DCHECK(has_next());
    index_++;
399
    uint32_t length;
400
    uint32_t result =
401
        decoder_->read_u32v<validate>(pc_, &length, "branch table entry");
402 403 404
    pc_ += length;
    return result;
  }
405
  // length, including the length of the {BranchTableImmediate}, but not the
406
  // opcode.
407
  uint32_t length() {
408
    while (has_next()) next();
409
    return static_cast<uint32_t>(pc_ - start_);
410 411 412
  }
  const byte* pc() { return pc_; }

413
  BranchTableIterator(Decoder* decoder,
414
                      const BranchTableImmediate<validate>& imm)
415
      : decoder_(decoder),
416 417 418
        start_(imm.start),
        pc_(imm.table),
        table_count_(imm.table_count) {}
419 420 421 422 423

 private:
  Decoder* decoder_;
  const byte* start_;
  const byte* pc_;
424
  uint32_t index_ = 0;    // the current index.
425 426 427
  uint32_t table_count_;  // the count of entries, not including default.
};

428
template <Decoder::ValidateFlag validate>
429
struct MemoryAccessImmediate {
430 431
  uint32_t alignment;
  uint32_t offset;
432
  uint32_t length = 0;
433 434
  inline MemoryAccessImmediate(Decoder* decoder, const byte* pc,
                               uint32_t max_alignment) {
435
    uint32_t alignment_length;
436
    alignment =
437
        decoder->read_u32v<validate>(pc + 1, &alignment_length, "alignment");
438
    if (!VALIDATE(alignment <= max_alignment)) {
439 440 441 442
      decoder->errorf(pc + 1,
                      "invalid alignment; expected maximum alignment is %u, "
                      "actual alignment is %u",
                      max_alignment, alignment);
443
    }
444
    uint32_t offset_length;
445 446
    offset = decoder->read_u32v<validate>(pc + 1 + alignment_length,
                                          &offset_length, "offset");
447 448 449 450
    length = alignment_length + offset_length;
  }
};

451
// Immediate for SIMD lane operations.
452
template <Decoder::ValidateFlag validate>
453
struct SimdLaneImmediate {
454
  uint8_t lane;
455
  uint32_t length = 1;
456

457
  inline SimdLaneImmediate(Decoder* decoder, const byte* pc) {
458
    lane = decoder->read_u8<validate>(pc + 2, "lane");
459 460 461
  }
};

462
// Immediate for SIMD shift operations.
463
template <Decoder::ValidateFlag validate>
464
struct SimdShiftImmediate {
465
  uint8_t shift;
466
  uint32_t length = 1;
467

468
  inline SimdShiftImmediate(Decoder* decoder, const byte* pc) {
469
    shift = decoder->read_u8<validate>(pc + 2, "shift");
470 471 472
  }
};

473
// Immediate for SIMD S8x16 shuffle operations.
474
template <Decoder::ValidateFlag validate>
475
struct Simd8x16ShuffleImmediate {
476
  uint8_t shuffle[kSimd128Size] = {0};
477

478
  inline Simd8x16ShuffleImmediate(Decoder* decoder, const byte* pc) {
479
    for (uint32_t i = 0; i < kSimd128Size; ++i) {
480
      shuffle[i] = decoder->read_u8<validate>(pc + 2 + i, "shuffle");
481
    }
482 483 484
  }
};

485 486
template <Decoder::ValidateFlag validate>
struct MemoryInitImmediate {
487
  uint32_t data_segment_index = 0;
488
  MemoryIndexImmediate<validate> memory;
489
  unsigned length = 0;
490

491
  inline MemoryInitImmediate(Decoder* decoder, const byte* pc) {
492
    uint32_t len = 0;
493 494 495 496
    data_segment_index =
        decoder->read_i32v<validate>(pc + 2, &len, "data segment index");
    memory = MemoryIndexImmediate<validate>(decoder, pc + 1 + len);
    length = len + memory.length;
497 498 499 500
  }
};

template <Decoder::ValidateFlag validate>
501
struct DataDropImmediate {
502 503 504
  uint32_t index;
  unsigned length;

505
  inline DataDropImmediate(Decoder* decoder, const byte* pc) {
506 507 508 509
    index = decoder->read_i32v<validate>(pc + 2, &length, "data segment index");
  }
};

510 511 512 513 514 515 516 517 518 519 520 521 522 523
template <Decoder::ValidateFlag validate>
struct MemoryCopyImmediate {
  MemoryIndexImmediate<validate> memory_src;
  MemoryIndexImmediate<validate> memory_dst;
  unsigned length = 0;

  inline MemoryCopyImmediate(Decoder* decoder, const byte* pc) {
    memory_src = MemoryIndexImmediate<validate>(decoder, pc + 1);
    memory_dst =
        MemoryIndexImmediate<validate>(decoder, pc + 1 + memory_src.length);
    length = memory_src.length + memory_dst.length;
  }
};

524 525
template <Decoder::ValidateFlag validate>
struct TableInitImmediate {
526
  uint32_t elem_segment_index = 0;
527
  TableIndexImmediate<validate> table;
528
  unsigned length = 0;
529

530
  inline TableInitImmediate(Decoder* decoder, const byte* pc) {
531
    uint32_t len = 0;
532 533 534 535
    elem_segment_index =
        decoder->read_i32v<validate>(pc + 2, &len, "elem segment index");
    table = TableIndexImmediate<validate>(decoder, pc + 1 + len);
    length = len + table.length;
536 537 538 539
  }
};

template <Decoder::ValidateFlag validate>
540
struct ElemDropImmediate {
541 542 543
  uint32_t index;
  unsigned length;

544
  inline ElemDropImmediate(Decoder* decoder, const byte* pc) {
545 546 547 548
    index = decoder->read_i32v<validate>(pc + 2, &length, "elem segment index");
  }
};

549 550 551 552 553 554 555 556 557 558 559 560 561 562
template <Decoder::ValidateFlag validate>
struct TableCopyImmediate {
  TableIndexImmediate<validate> table_src;
  TableIndexImmediate<validate> table_dst;
  unsigned length = 0;

  inline TableCopyImmediate(Decoder* decoder, const byte* pc) {
    table_src = TableIndexImmediate<validate>(decoder, pc + 1);
    table_dst =
        TableIndexImmediate<validate>(decoder, pc + 1 + table_src.length);
    length = table_src.length + table_dst.length;
  }
};

563
// An entry on the value stack.
564
struct ValueBase {
565 566
  const byte* pc = nullptr;
  ValueType type = kWasmStmt;
567

568
  ValueBase(const byte* pc, ValueType type) : pc(pc), type(type) {}
569 570
};

571 572
template <typename Value>
struct Merge {
573 574
  uint32_t arity = 0;
  union {  // Either multiple values or a single value.
575 576
    Value* array;
    Value first;
577
  } vals = {nullptr};  // Initialize {array} with {nullptr}.
578

579 580 581 582 583 584
  // Tracks whether this merge was ever reached. Uses precise reachability, like
  // Reachability::kReachable.
  bool reached;

  Merge(bool reached = false) : reached(reached) {}

585
  Value& operator[](uint32_t i) {
586 587 588 589 590
    DCHECK_GT(arity, i);
    return arity == 1 ? vals.first : vals.array[i];
  }
};

591
enum ControlKind : uint8_t {
592 593 594 595 596
  kControlIf,
  kControlIfElse,
  kControlBlock,
  kControlLoop,
  kControlTry,
597
  kControlTryCatch
598 599
};

600 601 602 603 604 605 606 607 608
enum Reachability : uint8_t {
  // reachable code.
  kReachable,
  // reachable code in unreachable block (implies normal validation).
  kSpecOnlyReachable,
  // code unreachable in its own block (implies polymorphic validation).
  kUnreachable
};

609
// An entry on the control stack (i.e. if, block, loop, or try).
610 611
template <typename Value>
struct ControlBase {
612 613 614
  ControlKind kind = kControlBlock;
  uint32_t stack_depth = 0;  // stack height at the beginning of the construct.
  const uint8_t* pc = nullptr;
615
  Reachability reachability = kReachable;
616

617 618 619
  // Values merged into the start or end of this control construct.
  Merge<Value> start_merge;
  Merge<Value> end_merge;
620

621 622 623 624 625 626 627 628 629
  MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(ControlBase);

  ControlBase(ControlKind kind, uint32_t stack_depth, const uint8_t* pc,
              Reachability reachability)
      : kind(kind),
        stack_depth(stack_depth),
        pc(pc),
        reachability(reachability),
        start_merge(reachability == kReachable) {}
630

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  // Check whether the current block is reachable.
  bool reachable() const { return reachability == kReachable; }

  // Check whether the rest of the block is unreachable.
  // Note that this is different from {!reachable()}, as there is also the
  // "indirect unreachable state", for which both {reachable()} and
  // {unreachable()} return false.
  bool unreachable() const { return reachability == kUnreachable; }

  // Return the reachability of new control structs started in this block.
  Reachability innerReachability() const {
    return reachability == kReachable ? kReachable : kSpecOnlyReachable;
  }

  bool is_if() const { return is_onearmed_if() || is_if_else(); }
  bool is_onearmed_if() const { return kind == kControlIf; }
  bool is_if_else() const { return kind == kControlIfElse; }
  bool is_block() const { return kind == kControlBlock; }
  bool is_loop() const { return kind == kControlLoop; }
  bool is_incomplete_try() const { return kind == kControlTry; }
  bool is_try_catch() const { return kind == kControlTryCatch; }
652
  bool is_try() const { return is_incomplete_try() || is_try_catch(); }
653

654 655 656
  inline Merge<Value>* br_merge() {
    return is_loop() ? &this->start_merge : &this->end_merge;
  }
657 658
};

659 660 661
// This is the list of callback functions that an interface for the
// WasmFullDecoder should implement.
// F(Name, args...)
662 663 664 665 666 667 668 669 670 671 672
#define INTERFACE_FUNCTIONS(F)                                                \
  /* General: */                                                              \
  F(StartFunction)                                                            \
  F(StartFunctionBody, Control* block)                                        \
  F(FinishFunction)                                                           \
  F(OnFirstError)                                                             \
  F(NextInstruction, WasmOpcode)                                              \
  /* Control: */                                                              \
  F(Block, Control* block)                                                    \
  F(Loop, Control* block)                                                     \
  F(Try, Control* block)                                                      \
673
  F(Catch, Control* block, Value* exception)                                  \
674 675 676 677 678
  F(If, const Value& cond, Control* if_block)                                 \
  F(FallThruTo, Control* c)                                                   \
  F(PopControl, Control* block)                                               \
  F(EndControl, Control* block)                                               \
  /* Instructions: */                                                         \
679 680 681
  F(UnOp, WasmOpcode opcode, const Value& value, Value* result)               \
  F(BinOp, WasmOpcode opcode, const Value& lhs, const Value& rhs,             \
    Value* result)                                                            \
682 683 684 685 686
  F(I32Const, Value* result, int32_t value)                                   \
  F(I64Const, Value* result, int64_t value)                                   \
  F(F32Const, Value* result, float value)                                     \
  F(F64Const, Value* result, double value)                                    \
  F(RefNull, Value* result)                                                   \
687
  F(RefFunc, uint32_t function_index, Value* result)                          \
688
  F(Drop, const Value& value)                                                 \
689
  F(DoReturn, Vector<Value> values)                                           \
690 691 692 693 694 695
  F(GetLocal, Value* result, const LocalIndexImmediate<validate>& imm)        \
  F(SetLocal, const Value& value, const LocalIndexImmediate<validate>& imm)   \
  F(TeeLocal, const Value& value, Value* result,                              \
    const LocalIndexImmediate<validate>& imm)                                 \
  F(GetGlobal, Value* result, const GlobalIndexImmediate<validate>& imm)      \
  F(SetGlobal, const Value& value, const GlobalIndexImmediate<validate>& imm) \
696 697 698 699
  F(GetTable, const Value& index, Value* result,                              \
    const TableIndexImmediate<validate>& imm)                                 \
  F(SetTable, const Value& index, const Value& value,                         \
    const TableIndexImmediate<validate>& imm)                                 \
700 701 702 703
  F(Unreachable)                                                              \
  F(Select, const Value& cond, const Value& fval, const Value& tval,          \
    Value* result)                                                            \
  F(Br, Control* target)                                                      \
704
  F(BrIf, const Value& cond, uint32_t depth)                                  \
705 706 707 708 709 710 711 712 713 714 715 716 717
  F(BrTable, const BranchTableImmediate<validate>& imm, const Value& key)     \
  F(Else, Control* if_block)                                                  \
  F(LoadMem, LoadType type, const MemoryAccessImmediate<validate>& imm,       \
    const Value& index, Value* result)                                        \
  F(StoreMem, StoreType type, const MemoryAccessImmediate<validate>& imm,     \
    const Value& index, const Value& value)                                   \
  F(CurrentMemoryPages, Value* result)                                        \
  F(MemoryGrow, const Value& value, Value* result)                            \
  F(CallDirect, const CallFunctionImmediate<validate>& imm,                   \
    const Value args[], Value returns[])                                      \
  F(CallIndirect, const Value& index,                                         \
    const CallIndirectImmediate<validate>& imm, const Value args[],           \
    Value returns[])                                                          \
718 719 720 721
  F(ReturnCall, const CallFunctionImmediate<validate>& imm,                   \
    const Value args[])                                                       \
  F(ReturnCallIndirect, const Value& index,                                   \
    const CallIndirectImmediate<validate>& imm, const Value args[])           \
722 723 724 725 726 727 728 729 730
  F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result)             \
  F(SimdLaneOp, WasmOpcode opcode, const SimdLaneImmediate<validate>& imm,    \
    const Vector<Value> inputs, Value* result)                                \
  F(SimdShiftOp, WasmOpcode opcode, const SimdShiftImmediate<validate>& imm,  \
    const Value& input, Value* result)                                        \
  F(Simd8x16ShuffleOp, const Simd8x16ShuffleImmediate<validate>& imm,         \
    const Value& input0, const Value& input1, Value* result)                  \
  F(Throw, const ExceptionIndexImmediate<validate>& imm,                      \
    const Vector<Value>& args)                                                \
731 732 733 734
  F(Rethrow, const Value& exception)                                          \
  F(BrOnException, const Value& exception,                                    \
    const ExceptionIndexImmediate<validate>& imm, uint32_t depth,             \
    Vector<Value> values)                                                     \
735 736
  F(AtomicOp, WasmOpcode opcode, Vector<Value> args,                          \
    const MemoryAccessImmediate<validate>& imm, Value* result)                \
737 738
  F(MemoryInit, const MemoryInitImmediate<validate>& imm, const Value& dst,   \
    const Value& src, const Value& size)                                      \
739
  F(DataDrop, const DataDropImmediate<validate>& imm)                         \
740
  F(MemoryCopy, const MemoryCopyImmediate<validate>& imm, const Value& dst,   \
741 742 743 744
    const Value& src, const Value& size)                                      \
  F(MemoryFill, const MemoryIndexImmediate<validate>& imm, const Value& dst,  \
    const Value& value, const Value& size)                                    \
  F(TableInit, const TableInitImmediate<validate>& imm, Vector<Value> args)   \
745
  F(ElemDrop, const ElemDropImmediate<validate>& imm)                         \
746 747
  F(TableCopy, const TableCopyImmediate<validate>& imm, Vector<Value> args)   \
  F(TableGrow, const TableIndexImmediate<validate>& imm, const Value& value,  \
748
    const Value& delta, Value* result)                                        \
749 750 751
  F(TableSize, const TableIndexImmediate<validate>& imm, Value* result)       \
  F(TableFill, const TableIndexImmediate<validate>& imm, const Value& start,  \
    const Value& value, const Value& count)
752 753

// Generic Wasm bytecode decoder with utilities for decoding immediates,
754
// lengths, etc.
755
template <Decoder::ValidateFlag validate>
756 757
class WasmDecoder : public Decoder {
 public:
758 759
  WasmDecoder(const WasmModule* module, const WasmFeatures& enabled,
              WasmFeatures* detected, FunctionSig* sig, const byte* start,
760 761 762
              const byte* end, uint32_t buffer_offset = 0)
      : Decoder(start, end, buffer_offset),
        module_(module),
763 764
        enabled_(enabled),
        detected_(detected),
765 766 767
        sig_(sig),
        local_types_(nullptr) {}
  const WasmModule* module_;
768 769
  const WasmFeatures enabled_;
  WasmFeatures* detected_;
770 771 772 773
  FunctionSig* sig_;

  ZoneVector<ValueType>* local_types_;

774 775 776 777
  uint32_t total_locals() const {
    return local_types_ == nullptr
               ? 0
               : static_cast<uint32_t>(local_types_->size());
778 779
  }

780 781
  static bool DecodeLocals(const WasmFeatures& enabled, Decoder* decoder,
                           const FunctionSig* sig,
782 783 784 785 786 787 788 789 790 791 792 793
                           ZoneVector<ValueType>* type_list) {
    DCHECK_NOT_NULL(type_list);
    DCHECK_EQ(0, type_list->size());
    // Initialize from signature.
    if (sig != nullptr) {
      type_list->assign(sig->parameters().begin(), sig->parameters().end());
    }
    // Decode local declarations, if any.
    uint32_t entries = decoder->consume_u32v("local decls count");
    if (decoder->failed()) return false;

    TRACE("local decls count: %u\n", entries);
794
    while (entries-- > 0 && decoder->more()) {
795 796 797
      uint32_t count = decoder->consume_u32v("local count");
      if (decoder->failed()) return false;

798 799
      DCHECK_LE(type_list->size(), kV8MaxWasmFunctionLocals);
      if (count > kV8MaxWasmFunctionLocals - type_list->size()) {
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
        decoder->error(decoder->pc() - 1, "local count too large");
        return false;
      }
      byte code = decoder->consume_u8("local type");
      if (decoder->failed()) return false;

      ValueType type;
      switch (code) {
        case kLocalI32:
          type = kWasmI32;
          break;
        case kLocalI64:
          type = kWasmI64;
          break;
        case kLocalF32:
          type = kWasmF32;
          break;
        case kLocalF64:
          type = kWasmF64;
          break;
820
        case kLocalAnyRef:
821
          if (enabled.anyref) {
822 823 824 825 826
            type = kWasmAnyRef;
            break;
          }
          decoder->error(decoder->pc() - 1, "invalid local type");
          return false;
827 828 829 830 831 832 833 834 835
        case kLocalAnyFunc:
          if (enabled.anyref) {
            type = kWasmAnyFunc;
            break;
          }
          decoder->error(decoder->pc() - 1,
                         "local type 'anyfunc' is not enabled with "
                         "--experimental-wasm-anyref");
          return false;
836 837 838 839 840 841 842
        case kLocalExceptRef:
          if (enabled.eh) {
            type = kWasmExceptRef;
            break;
          }
          decoder->error(decoder->pc() - 1, "invalid local type");
          return false;
843
        case kLocalS128:
844
          if (enabled.simd) {
845 846 847
            type = kWasmS128;
            break;
          }
848
          V8_FALLTHROUGH;
849 850 851 852 853 854 855 856 857 858 859
        default:
          decoder->error(decoder->pc() - 1, "invalid local type");
          return false;
      }
      type_list->insert(type_list->end(), count, type);
    }
    DCHECK(decoder->ok());
    return true;
  }

  static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc,
860
                                          uint32_t locals_count, Zone* zone) {
861 862 863
    if (pc >= decoder->end()) return nullptr;
    if (*pc != kExprLoop) return nullptr;

864 865
    // The number of locals_count is augmented by 2 so that 'locals_count - 2'
    // can be used to track mem_size, and 'locals_count - 1' to track mem_start.
866 867 868
    BitVector* assigned = new (zone) BitVector(locals_count, zone);
    int depth = 0;
    // Iteratively process all AST nodes nested inside the loop.
869
    while (pc < decoder->end() && VALIDATE(decoder->ok())) {
870
      WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
871
      uint32_t length = 1;
872 873 874 875 876 877 878 879 880 881
      switch (opcode) {
        case kExprLoop:
        case kExprIf:
        case kExprBlock:
        case kExprTry:
          length = OpcodeLength(decoder, pc);
          depth++;
          break;
        case kExprSetLocal:  // fallthru
        case kExprTeeLocal: {
882
          LocalIndexImmediate<validate> imm(decoder, pc);
883
          if (assigned->length() > 0 &&
884
              imm.index < static_cast<uint32_t>(assigned->length())) {
885
            // Unverified code might have an out-of-bounds index.
886
            assigned->Add(imm.index);
887
          }
888
          length = 1 + imm.length;
889 890
          break;
        }
891
        case kExprMemoryGrow:
892 893
        case kExprCallFunction:
        case kExprCallIndirect:
894 895
        case kExprReturnCall:
        case kExprReturnCallIndirect:
896
          // Add instance cache nodes to the assigned set.
897 898
          // TODO(titzer): make this more clear.
          assigned->Add(locals_count - 1);
899 900
          length = OpcodeLength(decoder, pc);
          break;
901 902 903 904 905 906 907 908 909 910
        case kExprEnd:
          depth--;
          break;
        default:
          length = OpcodeLength(decoder, pc);
          break;
      }
      if (depth <= 0) break;
      pc += length;
    }
911
    return VALIDATE(decoder->ok()) ? assigned : nullptr;
912 913
  }

914
  inline bool Validate(const byte* pc, LocalIndexImmediate<validate>& imm) {
915 916
    if (!VALIDATE(imm.index < total_locals())) {
      errorf(pc + 1, "invalid local index: %u", imm.index);
917
      return false;
918
    }
919
    imm.type = local_types_ ? local_types_->at(imm.index) : kWasmStmt;
920
    return true;
921 922
  }

923
  inline bool Complete(const byte* pc, ExceptionIndexImmediate<validate>& imm) {
924
    if (!VALIDATE(module_ != nullptr &&
925
                  imm.index < module_->exceptions.size())) {
926
      return false;
927
    }
928
    imm.exception = &module_->exceptions[imm.index];
929
    return true;
930 931
  }

932 933 934 935 936 937 938 939
  inline bool Validate(const byte* pc, ExceptionIndexImmediate<validate>& imm) {
    if (!Complete(pc, imm)) {
      errorf(pc + 1, "Invalid exception index: %u", imm.index);
      return false;
    }
    return true;
  }

940 941 942
  inline bool Validate(const byte* pc, GlobalIndexImmediate<validate>& imm) {
    if (!VALIDATE(module_ != nullptr && imm.index < module_->globals.size())) {
      errorf(pc + 1, "invalid global index: %u", imm.index);
943
      return false;
944
    }
945 946
    imm.global = &module_->globals[imm.index];
    imm.type = imm.global->type;
947
    return true;
948 949
  }

950 951
  inline bool CanReturnCall(FunctionSig* target_sig) {
    if (target_sig == nullptr) return false;
952
    size_t num_returns = sig_->return_count();
953
    if (num_returns != target_sig->return_count()) return false;
954
    for (size_t i = 0; i < num_returns; ++i) {
955
      if (sig_->GetReturn(i) != target_sig->GetReturn(i)) return false;
956 957 958 959
    }
    return true;
  }

960
  inline bool Complete(const byte* pc, CallFunctionImmediate<validate>& imm) {
961
    if (!VALIDATE(module_ != nullptr &&
962
                  imm.index < module_->functions.size())) {
963
      return false;
964
    }
965
    imm.sig = module_->functions[imm.index].sig;
966
    return true;
967 968
  }

969 970
  inline bool Validate(const byte* pc, CallFunctionImmediate<validate>& imm) {
    if (Complete(pc, imm)) {
971 972
      return true;
    }
973
    errorf(pc + 1, "invalid function index: %u", imm.index);
974 975 976
    return false;
  }

977
  inline bool Complete(const byte* pc, CallIndirectImmediate<validate>& imm) {
978
    if (!VALIDATE(module_ != nullptr &&
979
                  imm.sig_index < module_->signatures.size())) {
980
      return false;
981
    }
982
    imm.sig = module_->signatures[imm.sig_index];
983
    return true;
984 985
  }

986
  inline bool Validate(const byte* pc, CallIndirectImmediate<validate>& imm) {
987 988
    if (!VALIDATE(module_ != nullptr &&
                  imm.table_index < module_->tables.size())) {
989 990 991
      error("function table has to exist to execute call_indirect");
      return false;
    }
992 993 994 995 996
    if (!VALIDATE(module_ != nullptr &&
                  module_->tables[imm.table_index].type == kWasmAnyFunc)) {
      error("table of call_indirect must be of type anyfunc");
      return false;
    }
997 998
    if (!Complete(pc, imm)) {
      errorf(pc + 1, "invalid signature index: #%u", imm.sig_index);
999
      return false;
1000
    }
1001
    return true;
1002 1003
  }

1004
  inline bool Validate(const byte* pc, BranchDepthImmediate<validate>& imm,
1005
                       size_t control_depth) {
1006
    if (!VALIDATE(imm.depth < control_depth)) {
1007
      errorf(pc + 1, "invalid branch depth: %u", imm.depth);
1008
      return false;
1009
    }
1010
    return true;
1011 1012
  }

1013
  bool Validate(const byte* pc, BranchTableImmediate<validate>& imm,
1014
                size_t block_depth) {
1015
    if (!VALIDATE(imm.table_count < kV8MaxWasmFunctionSize)) {
1016
      errorf(pc + 1, "invalid table count (> max function size): %u",
1017
             imm.table_count);
1018 1019
      return false;
    }
1020
    return checkAvailable(imm.table_count);
1021 1022 1023
  }

  inline bool Validate(const byte* pc, WasmOpcode opcode,
1024
                       SimdLaneImmediate<validate>& imm) {
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    uint8_t num_lanes = 0;
    switch (opcode) {
      case kExprF32x4ExtractLane:
      case kExprF32x4ReplaceLane:
      case kExprI32x4ExtractLane:
      case kExprI32x4ReplaceLane:
        num_lanes = 4;
        break;
      case kExprI16x8ExtractLane:
      case kExprI16x8ReplaceLane:
        num_lanes = 8;
        break;
      case kExprI8x16ExtractLane:
      case kExprI8x16ReplaceLane:
        num_lanes = 16;
        break;
      default:
        UNREACHABLE();
        break;
    }
1045
    if (!VALIDATE(imm.lane >= 0 && imm.lane < num_lanes)) {
1046 1047 1048 1049 1050 1051 1052 1053
      error(pc_ + 2, "invalid lane index");
      return false;
    } else {
      return true;
    }
  }

  inline bool Validate(const byte* pc, WasmOpcode opcode,
1054
                       SimdShiftImmediate<validate>& imm) {
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    uint8_t max_shift = 0;
    switch (opcode) {
      case kExprI32x4Shl:
      case kExprI32x4ShrS:
      case kExprI32x4ShrU:
        max_shift = 32;
        break;
      case kExprI16x8Shl:
      case kExprI16x8ShrS:
      case kExprI16x8ShrU:
        max_shift = 16;
        break;
      case kExprI8x16Shl:
      case kExprI8x16ShrS:
      case kExprI8x16ShrU:
        max_shift = 8;
        break;
      default:
        UNREACHABLE();
        break;
    }
1076
    if (!VALIDATE(imm.shift >= 0 && imm.shift < max_shift)) {
1077 1078 1079 1080 1081 1082 1083 1084
      error(pc_ + 2, "invalid shift amount");
      return false;
    } else {
      return true;
    }
  }

  inline bool Validate(const byte* pc,
1085
                       Simd8x16ShuffleImmediate<validate>& imm) {
1086
    uint8_t max_lane = 0;
1087
    for (uint32_t i = 0; i < kSimd128Size; ++i) {
1088
      max_lane = std::max(max_lane, imm.shuffle[i]);
1089
    }
1090
    // Shuffle indices must be in [0..31] for a 16 lane shuffle.
1091
    if (!VALIDATE(max_lane <= 2 * kSimd128Size)) {
1092 1093 1094
      error(pc_ + 2, "invalid shuffle mask");
      return false;
    }
1095
    return true;
1096 1097
  }

1098 1099
  inline bool Complete(BlockTypeImmediate<validate>& imm) {
    if (imm.type != kWasmVar) return true;
1100
    if (!VALIDATE(module_ && imm.sig_index < module_->signatures.size())) {
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      return false;
    }
    imm.sig = module_->signatures[imm.sig_index];
    return true;
  }

  inline bool Validate(BlockTypeImmediate<validate>& imm) {
    if (!Complete(imm)) {
      errorf(pc_, "block type index %u out of bounds (%zu signatures)",
             imm.sig_index, module_ ? module_->signatures.size() : 0);
      return false;
    }
    return true;
  }

1116 1117 1118 1119 1120 1121 1122 1123 1124
  inline bool Validate(const byte* pc, FunctionIndexImmediate<validate>& imm) {
    if (!VALIDATE(module_ != nullptr &&
                  imm.index < module_->functions.size())) {
      errorf(pc, "invalid function index: %u", imm.index);
      return false;
    }
    return true;
  }

1125
  inline bool Validate(const byte* pc, MemoryIndexImmediate<validate>& imm) {
1126
    if (!VALIDATE(module_ != nullptr && module_->has_memory)) {
1127
      errorf(pc + 1, "memory instruction with no memory");
1128 1129 1130 1131 1132 1133
      return false;
    }
    return true;
  }

  inline bool Validate(MemoryInitImmediate<validate>& imm) {
1134 1135 1136 1137 1138 1139
    if (!VALIDATE(module_ != nullptr &&
                  imm.data_segment_index <
                      module_->num_declared_data_segments)) {
      errorf(pc_ + 2, "invalid data segment index: %u", imm.data_segment_index);
      return false;
    }
1140 1141
    if (!Validate(pc_ + imm.length - imm.memory.length - 1, imm.memory))
      return false;
1142 1143 1144
    return true;
  }

1145
  inline bool Validate(DataDropImmediate<validate>& imm) {
1146 1147 1148 1149 1150
    if (!VALIDATE(module_ != nullptr &&
                  imm.index < module_->num_declared_data_segments)) {
      errorf(pc_ + 2, "invalid data segment index: %u", imm.index);
      return false;
    }
1151 1152 1153
    return true;
  }

1154 1155 1156 1157 1158 1159
  inline bool Validate(MemoryCopyImmediate<validate>& imm) {
    if (!Validate(pc_ + 1, imm.memory_src)) return false;
    if (!Validate(pc_ + 2, imm.memory_dst)) return false;
    return true;
  }

1160 1161
  inline bool Validate(const byte* pc, TableIndexImmediate<validate>& imm) {
    if (!VALIDATE(module_ != nullptr && imm.index < module_->tables.size())) {
1162
      errorf(pc, "invalid table index: %u", imm.index);
1163 1164 1165 1166 1167 1168 1169
      return false;
    }
    return true;
  }

  inline bool Validate(TableInitImmediate<validate>& imm) {
    if (!VALIDATE(module_ != nullptr &&
1170
                  imm.elem_segment_index < module_->elem_segments.size())) {
1171 1172 1173 1174
      errorf(pc_ + 2, "invalid element segment index: %u",
             imm.elem_segment_index);
      return false;
    }
1175 1176
    if (!Validate(pc_ + imm.length - imm.table.length - 1, imm.table))
      return false;
1177 1178 1179
    return true;
  }

1180
  inline bool Validate(ElemDropImmediate<validate>& imm) {
1181
    if (!VALIDATE(module_ != nullptr &&
1182
                  imm.index < module_->elem_segments.size())) {
1183 1184 1185 1186 1187 1188
      errorf(pc_ + 2, "invalid element segment index: %u", imm.index);
      return false;
    }
    return true;
  }

1189 1190 1191 1192 1193 1194
  inline bool Validate(TableCopyImmediate<validate>& imm) {
    if (!Validate(pc_ + 1, imm.table_src)) return false;
    if (!Validate(pc_ + 2, imm.table_dst)) return false;
    return true;
  }

1195
  static uint32_t OpcodeLength(Decoder* decoder, const byte* pc) {
1196 1197 1198 1199 1200 1201 1202
    WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
    switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
      FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
      FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
      {
1203 1204
        MemoryAccessImmediate<validate> imm(decoder, pc, UINT32_MAX);
        return 1 + imm.length;
1205 1206 1207
      }
      case kExprBr:
      case kExprBrIf: {
1208
        BranchDepthImmediate<validate> imm(decoder, pc);
1209
        return 1 + imm.length;
1210
      }
1211 1212
      case kExprGetGlobal:
      case kExprSetGlobal: {
1213 1214
        GlobalIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1215
      }
1216 1217 1218 1219 1220
      case kExprGetTable:
      case kExprSetTable: {
        TableIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
      }
1221 1222
      case kExprCallFunction:
      case kExprReturnCall: {
1223 1224
        CallFunctionImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1225
      }
1226 1227
      case kExprCallIndirect:
      case kExprReturnCallIndirect: {
1228
        CallIndirectImmediate<validate> imm(kAllWasmFeatures, decoder, pc);
1229
        return 1 + imm.length;
1230 1231 1232 1233 1234 1235
      }

      case kExprTry:
      case kExprIf:  // fall through
      case kExprLoop:
      case kExprBlock: {
1236
        BlockTypeImmediate<validate> imm(kAllWasmFeatures, decoder, pc);
1237
        return 1 + imm.length;
1238 1239
      }

1240
      case kExprThrow: {
1241 1242
        ExceptionIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1243 1244
      }

1245
      case kExprBrOnExn: {
1246 1247
        BranchOnExceptionImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1248 1249
      }

1250 1251 1252
      case kExprSetLocal:
      case kExprTeeLocal:
      case kExprGetLocal: {
1253
        LocalIndexImmediate<validate> imm(decoder, pc);
1254
        return 1 + imm.length;
1255 1256
      }
      case kExprBrTable: {
1257 1258
        BranchTableImmediate<validate> imm(decoder, pc);
        BranchTableIterator<validate> iterator(decoder, imm);
1259 1260 1261
        return 1 + iterator.length();
      }
      case kExprI32Const: {
1262 1263
        ImmI32Immediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1264 1265
      }
      case kExprI64Const: {
1266 1267
        ImmI64Immediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1268
      }
1269 1270 1271
      case kExprRefNull: {
        return 1;
      }
1272 1273 1274 1275
      case kExprRefFunc: {
        FunctionIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
      }
1276
      case kExprMemoryGrow:
1277
      case kExprMemorySize: {
1278 1279
        MemoryIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1280 1281 1282 1283 1284
      }
      case kExprF32Const:
        return 5;
      case kExprF64Const:
        return 9;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
      case kNumericPrefix: {
        byte numeric_index =
            decoder->read_u8<validate>(pc + 1, "numeric_index");
        WasmOpcode opcode =
            static_cast<WasmOpcode>(kNumericPrefix << 8 | numeric_index);
        switch (opcode) {
          case kExprI32SConvertSatF32:
          case kExprI32UConvertSatF32:
          case kExprI32SConvertSatF64:
          case kExprI32UConvertSatF64:
          case kExprI64SConvertSatF32:
          case kExprI64UConvertSatF32:
          case kExprI64SConvertSatF64:
          case kExprI64UConvertSatF64:
            return 2;
          case kExprMemoryInit: {
            MemoryInitImmediate<validate> imm(decoder, pc);
            return 2 + imm.length;
          }
1304 1305
          case kExprDataDrop: {
            DataDropImmediate<validate> imm(decoder, pc);
1306 1307
            return 2 + imm.length;
          }
1308 1309 1310 1311
          case kExprMemoryCopy: {
            MemoryCopyImmediate<validate> imm(decoder, pc);
            return 2 + imm.length;
          }
1312 1313 1314 1315 1316 1317 1318 1319
          case kExprMemoryFill: {
            MemoryIndexImmediate<validate> imm(decoder, pc + 1);
            return 2 + imm.length;
          }
          case kExprTableInit: {
            TableInitImmediate<validate> imm(decoder, pc);
            return 2 + imm.length;
          }
1320 1321
          case kExprElemDrop: {
            ElemDropImmediate<validate> imm(decoder, pc);
1322 1323 1324
            return 2 + imm.length;
          }
          case kExprTableCopy: {
1325
            TableCopyImmediate<validate> imm(decoder, pc);
1326 1327
            return 2 + imm.length;
          }
1328
          case kExprTableGrow:
1329 1330
          case kExprTableSize:
          case kExprTableFill: {
1331 1332 1333
            TableIndexImmediate<validate> imm(decoder, pc);
            return 2 + imm.length;
          }
1334 1335 1336 1337 1338
          default:
            decoder->error(pc, "invalid numeric opcode");
            return 2;
        }
      }
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
      case kSimdPrefix: {
        byte simd_index = decoder->read_u8<validate>(pc + 1, "simd_index");
        WasmOpcode opcode =
            static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index);
        switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          return 2;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          return 3;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          {
1356 1357
            MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX);
            return 2 + imm.length;
1358 1359 1360 1361 1362 1363 1364 1365 1366
          }
          // Shuffles require a byte per lane, or 16 immediate bytes.
          case kExprS8x16Shuffle:
            return 2 + kSimd128Size;
          default:
            decoder->error(pc, "invalid SIMD opcode");
            return 2;
        }
      }
1367 1368 1369 1370 1371 1372 1373 1374 1375
      case kAtomicPrefix: {
        byte atomic_index = decoder->read_u8<validate>(pc + 1, "atomic_index");
        WasmOpcode opcode =
            static_cast<WasmOpcode>(kAtomicPrefix << 8 | atomic_index);
        switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_ATOMIC_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          {
1376 1377
            MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX);
            return 2 + imm.length;
1378 1379 1380 1381 1382 1383
          }
          default:
            decoder->error(pc, "invalid Atomics opcode");
            return 2;
        }
      }
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
      default:
        return 1;
    }
  }

  std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) {
    WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
    // Handle "simple" opcodes with a fixed signature first.
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
    if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode);
    if (sig) return {sig->parameter_count(), sig->return_count()};

#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
    // clang-format off
    switch (opcode) {
      case kExprSelect:
        return {3, 1};
1401
      case kExprSetTable:
1402 1403 1404
      FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
        return {2, 0};
      FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
1405
      case kExprGetTable:
1406
      case kExprTeeLocal:
1407
      case kExprMemoryGrow:
1408 1409 1410 1411 1412 1413 1414
        return {1, 1};
      case kExprSetLocal:
      case kExprSetGlobal:
      case kExprDrop:
      case kExprBrIf:
      case kExprBrTable:
      case kExprIf:
1415
      case kExprRethrow:
1416 1417 1418 1419 1420 1421 1422
        return {1, 0};
      case kExprGetLocal:
      case kExprGetGlobal:
      case kExprI32Const:
      case kExprI64Const:
      case kExprF32Const:
      case kExprF64Const:
1423
      case kExprRefNull:
1424
      case kExprRefFunc:
1425 1426 1427
      case kExprMemorySize:
        return {0, 1};
      case kExprCallFunction: {
1428 1429 1430
        CallFunctionImmediate<validate> imm(this, pc);
        CHECK(Complete(pc, imm));
        return {imm.sig->parameter_count(), imm.sig->return_count()};
1431 1432
      }
      case kExprCallIndirect: {
1433
        CallIndirectImmediate<validate> imm(this->enabled_, this, pc);
1434
        CHECK(Complete(pc, imm));
1435
        // Indirect calls pop an additional argument for the table index.
1436 1437
        return {imm.sig->parameter_count() + 1,
                imm.sig->return_count()};
1438
      }
1439 1440 1441 1442 1443 1444
      case kExprThrow: {
        ExceptionIndexImmediate<validate> imm(this, pc);
        CHECK(Complete(pc, imm));
        DCHECK_EQ(0, imm.exception->sig->return_count());
        return {imm.exception->sig->parameter_count(), 0};
      }
1445 1446 1447 1448 1449
      case kExprBr:
      case kExprBlock:
      case kExprLoop:
      case kExprEnd:
      case kExprElse:
1450
      case kExprTry:
1451
      case kExprCatch:
1452
      case kExprBrOnExn:
1453 1454
      case kExprNop:
      case kExprReturn:
1455 1456
      case kExprReturnCall:
      case kExprReturnCallIndirect:
1457 1458
      case kExprUnreachable:
        return {0, 0};
1459
      case kNumericPrefix:
1460 1461 1462 1463
      case kAtomicPrefix:
      case kSimdPrefix: {
        opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1));
        switch (opcode) {
1464
          FOREACH_SIMD_1_OPERAND_1_PARAM_OPCODE(DECLARE_OPCODE_CASE)
1465
            return {1, 1};
1466
          FOREACH_SIMD_1_OPERAND_2_PARAM_OPCODE(DECLARE_OPCODE_CASE)
1467
          FOREACH_SIMD_MASK_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
1468
            return {2, 1};
1469 1470 1471 1472 1473 1474 1475
          default: {
            sig = WasmOpcodes::Signature(opcode);
            if (sig) {
              return {sig->parameter_count(), sig->return_count()};
            }
          }
        }
1476
        V8_FALLTHROUGH;
1477
      }
1478
      default:
1479 1480
        FATAL("unimplemented opcode: %x (%s)", opcode,
              WasmOpcodes::OpcodeName(opcode));
1481 1482 1483 1484 1485 1486 1487
        return {0, 0};
    }
#undef DECLARE_OPCODE_CASE
    // clang-format on
  }
};

1488
#define CALL_INTERFACE(name, ...) interface_.name(this, ##__VA_ARGS__)
1489 1490 1491 1492 1493 1494
#define CALL_INTERFACE_IF_REACHABLE(name, ...)                 \
  do {                                                         \
    DCHECK(!control_.empty());                                 \
    if (VALIDATE(this->ok()) && control_.back().reachable()) { \
      interface_.name(this, ##__VA_ARGS__);                    \
    }                                                          \
1495
  } while (false)
1496 1497 1498 1499 1500 1501 1502
#define CALL_INTERFACE_IF_PARENT_REACHABLE(name, ...)           \
  do {                                                          \
    DCHECK(!control_.empty());                                  \
    if (VALIDATE(this->ok()) &&                                 \
        (control_.size() == 1 || control_at(1)->reachable())) { \
      interface_.name(this, ##__VA_ARGS__);                     \
    }                                                           \
1503 1504
  } while (false)

1505
template <Decoder::ValidateFlag validate, typename Interface>
1506
class WasmFullDecoder : public WasmDecoder<validate> {
1507 1508 1509
  using Value = typename Interface::Value;
  using Control = typename Interface::Control;
  using MergeValues = Merge<Value>;
1510
  using ArgVector = base::SmallVector<Value, 8>;
1511

1512 1513
  // All Value types should be trivially copyable for performance. We push, pop,
  // and store them in local variables.
1514
  ASSERT_TRIVIALLY_COPYABLE(Value);
1515 1516 1517

 public:
  template <typename... InterfaceArgs>
1518
  WasmFullDecoder(Zone* zone, const WasmModule* module,
1519
                  const WasmFeatures& enabled, WasmFeatures* detected,
1520
                  const FunctionBody& body, InterfaceArgs&&... interface_args)
1521 1522
      : WasmDecoder<validate>(module, enabled, detected, body.sig, body.start,
                              body.end, body.offset),
1523 1524 1525 1526
        zone_(zone),
        interface_(std::forward<InterfaceArgs>(interface_args)...),
        local_type_vec_(zone),
        stack_(zone),
1527
        control_(zone) {
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    this->local_types_ = &local_type_vec_;
  }

  Interface& interface() { return interface_; }

  bool Decode() {
    DCHECK(stack_.empty());
    DCHECK(control_.empty());

    base::ElapsedTimer decode_timer;
    if (FLAG_trace_wasm_decode_time) {
      decode_timer.Start();
    }

    if (this->end_ < this->pc_) {
      this->error("function body end < start");
      return false;
    }

    DCHECK_EQ(0, this->local_types_->size());
1548 1549
    WasmDecoder<validate>::DecodeLocals(this->enabled_, this, this->sig_,
                                        this->local_types_);
1550
    CALL_INTERFACE(StartFunction);
1551
    DecodeFunctionBody();
1552
    if (!this->failed()) CALL_INTERFACE(FinishFunction);
1553

1554 1555 1556 1557 1558
    // Generate a better error message whether the unterminated control
    // structure is the function body block or an innner structure.
    if (control_.size() > 1) {
      this->error(control_.back().pc, "unterminated control structure");
    } else if (control_.size() == 1) {
1559 1560 1561
      this->error("function body must end with \"end\" opcode");
    }

1562 1563
    if (this->failed()) return this->TraceFailed();

1564 1565
    if (FLAG_trace_wasm_decode_time) {
      double ms = decode_timer.Elapsed().InMillisecondsF();
1566 1567
      PrintF("wasm-decode %s (%0.3f ms)\n\n",
             VALIDATE(this->ok()) ? "ok" : "failed", ms);
1568
    } else {
1569
      TRACE("wasm-decode %s\n\n", VALIDATE(this->ok()) ? "ok" : "failed");
1570 1571 1572 1573 1574 1575
    }

    return true;
  }

  bool TraceFailed() {
1576 1577 1578
    TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_.offset(),
          this->GetBufferRelativeOffset(this->error_.offset()),
          this->error_.message().c_str());
1579 1580 1581 1582 1583
    return false;
  }

  const char* SafeOpcodeNameAt(const byte* pc) {
    if (pc >= this->end_) return "<end>";
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
    if (!WasmOpcodes::IsPrefixOpcode(opcode)) {
      return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(opcode));
    }
    // We need one more byte.
    ++pc;
    if (pc >= this->end_) return "<end>";
    byte sub_opcode = *pc;
    opcode = static_cast<WasmOpcode>(opcode << 8 | sub_opcode);
    return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(opcode));
1594 1595 1596 1597
  }

  inline Zone* zone() const { return zone_; }

1598
  inline uint32_t num_locals() const {
1599 1600 1601 1602 1603 1604 1605
    return static_cast<uint32_t>(local_type_vec_.size());
  }

  inline ValueType GetLocalType(uint32_t index) {
    return local_type_vec_[index];
  }

1606
  inline WasmCodePosition position() {
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
    int offset = static_cast<int>(this->pc_ - this->start_);
    DCHECK_EQ(this->pc_ - this->start_, offset);  // overflows cannot happen
    return offset;
  }

  inline uint32_t control_depth() const {
    return static_cast<uint32_t>(control_.size());
  }

  inline Control* control_at(uint32_t depth) {
    DCHECK_GT(control_.size(), depth);
1618
    return &control_.back() - depth;
1619 1620 1621
  }

  inline uint32_t stack_size() const {
1622
    DCHECK_GE(kMaxUInt32, stack_.size());
1623 1624 1625
    return static_cast<uint32_t>(stack_.size());
  }

1626 1627 1628 1629
  inline Value* stack_value(uint32_t depth) {
    DCHECK_LT(0, depth);
    DCHECK_GE(stack_.size(), depth);
    return &*(stack_.end() - depth);
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
  }

 private:
  Zone* zone_;

  Interface interface_;

  ZoneVector<ValueType> local_type_vec_;  // types of local variables.
  ZoneVector<Value> stack_;               // stack of values.
  ZoneVector<Control> control_;           // stack of blocks, loops, and ifs.

1641 1642 1643 1644
  static Value UnreachableValue(const uint8_t* pc) {
    return Value{pc, kWasmVar};
  }

1645
  bool CheckHasMemory() {
1646 1647 1648 1649 1650
    if (!VALIDATE(this->module_->has_memory)) {
      this->error(this->pc_ - 1, "memory instruction with no memory");
      return false;
    }
    return true;
1651 1652
  }

1653 1654 1655 1656 1657 1658 1659 1660
  bool CheckHasSharedMemory() {
    if (!VALIDATE(this->module_->has_shared_memory)) {
      this->error(this->pc_ - 1, "Atomic opcodes used without shared memory");
      return false;
    }
    return true;
  }

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
  class TraceLine {
   public:
    static constexpr int kMaxLen = 512;
    ~TraceLine() {
      if (!FLAG_trace_wasm_decoder) return;
      PrintF("%.*s\n", len_, buffer_);
    }

    // Appends a formatted string.
    PRINTF_FORMAT(2, 3)
    void Append(const char* format, ...) {
      if (!FLAG_trace_wasm_decoder) return;
      va_list va_args;
      va_start(va_args, format);
      size_t remaining_len = kMaxLen - len_;
      Vector<char> remaining_msg_space(buffer_ + len_, remaining_len);
      int len = VSNPrintF(remaining_msg_space, format, va_args);
      va_end(va_args);
      len_ += len < 0 ? remaining_len : len;
    }

   private:
    char buffer_[kMaxLen];
    int len_ = 0;
  };

1687 1688 1689 1690 1691 1692 1693 1694 1695
  // Decodes the body of a function.
  void DecodeFunctionBody() {
    TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n",
          reinterpret_cast<const void*>(this->start()),
          reinterpret_cast<const void*>(this->end()), this->pc_offset(),
          static_cast<int>(this->end() - this->start()));

    // Set up initial function block.
    {
1696
      auto* c = PushControl(kControlBlock);
1697
      InitMerge(&c->start_merge, 0, [](uint32_t) -> Value { UNREACHABLE(); });
1698 1699
      InitMerge(&c->end_merge,
                static_cast<uint32_t>(this->sig_->return_count()),
1700 1701 1702
                [&](uint32_t i) {
                  return Value{this->pc_, this->sig_->GetReturn(i)};
                });
1703
      CALL_INTERFACE(StartFunctionBody, c);
1704 1705 1706
    }

    while (this->pc_ < this->end_) {  // decoding loop.
1707
      uint32_t len = 1;
1708
      WasmOpcode opcode = static_cast<WasmOpcode>(*this->pc_);
1709 1710 1711

      CALL_INTERFACE_IF_REACHABLE(NextInstruction, opcode);

1712
#if DEBUG
1713 1714 1715
      TraceLine trace_msg;
#define TRACE_PART(...) trace_msg.Append(__VA_ARGS__)
      if (!WasmOpcodes::IsPrefixOpcode(opcode)) {
1716
        TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
1717
                   WasmOpcodes::OpcodeName(opcode));
1718
      }
1719 1720
#else
#define TRACE_PART(...)
1721 1722
#endif

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
      switch (opcode) {
#define BUILD_SIMPLE_OPCODE(op, _, sig) \
  case kExpr##op:                       \
    BuildSimpleOperator_##sig(opcode);  \
    break;
        FOREACH_SIMPLE_OPCODE(BUILD_SIMPLE_OPCODE)
#undef BUILD_SIMPLE_OPCODE
        case kExprNop:
          break;
        case kExprBlock: {
          BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_);
          if (!this->Validate(imm)) break;
1735
          auto args = PopArgs(imm.sig);
1736
          auto* block = PushControl(kControlBlock);
1737
          SetBlockType(block, imm, args.begin());
1738 1739 1740 1741 1742 1743 1744
          CALL_INTERFACE_IF_REACHABLE(Block, block);
          PushMergeValues(block, &block->start_merge);
          len = 1 + imm.length;
          break;
        }
        case kExprRethrow: {
          CHECK_PROTOTYPE_OPCODE(eh);
1745 1746
          auto exception = Pop(0, kWasmExceptRef);
          CALL_INTERFACE_IF_REACHABLE(Rethrow, exception);
1747 1748 1749 1750 1751 1752 1753 1754
          EndControl();
          break;
        }
        case kExprThrow: {
          CHECK_PROTOTYPE_OPCODE(eh);
          ExceptionIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
1755 1756
          auto args = PopArgs(imm.exception->ToFunctionSig());
          CALL_INTERFACE_IF_REACHABLE(Throw, imm, VectorOf(args));
1757 1758 1759 1760 1761 1762 1763
          EndControl();
          break;
        }
        case kExprTry: {
          CHECK_PROTOTYPE_OPCODE(eh);
          BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_);
          if (!this->Validate(imm)) break;
1764
          auto args = PopArgs(imm.sig);
1765
          auto* try_block = PushControl(kControlTry);
1766
          SetBlockType(try_block, imm, args.begin());
1767 1768 1769 1770 1771 1772 1773 1774 1775
          len = 1 + imm.length;
          CALL_INTERFACE_IF_REACHABLE(Try, try_block);
          PushMergeValues(try_block, &try_block->start_merge);
          break;
        }
        case kExprCatch: {
          CHECK_PROTOTYPE_OPCODE(eh);
          if (!VALIDATE(!control_.empty())) {
            this->error("catch does not match any try");
1776 1777
            break;
          }
1778 1779 1780
          Control* c = &control_.back();
          if (!VALIDATE(c->is_try())) {
            this->error("catch does not match any try");
1781 1782
            break;
          }
1783 1784
          if (!VALIDATE(c->is_incomplete_try())) {
            this->error("catch already present for try");
1785 1786
            break;
          }
1787 1788
          c->kind = kControlTryCatch;
          FallThruTo(c);
1789
          stack_.erase(stack_.begin() + c->stack_depth, stack_.end());
1790
          c->reachability = control_at(1)->innerReachability();
1791 1792
          auto* exception = Push(kWasmExceptRef);
          CALL_INTERFACE_IF_PARENT_REACHABLE(Catch, c, exception);
1793 1794
          break;
        }
1795
        case kExprBrOnExn: {
1796
          CHECK_PROTOTYPE_OPCODE(eh);
1797 1798 1799 1800
          BranchOnExceptionImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm.depth, control_.size())) break;
          if (!this->Validate(this->pc_ + imm.depth.length, imm.index)) break;
          Control* c = control_at(imm.depth.depth);
1801
          auto exception = Pop(0, kWasmExceptRef);
1802
          const WasmExceptionSig* sig = imm.index.exception->sig;
1803 1804 1805 1806 1807 1808 1809 1810 1811
          size_t value_count = sig->parameter_count();
          // TODO(mstarzinger): This operand stack mutation is an ugly hack to
          // make both type checking here as well as environment merging in the
          // graph builder interface work out of the box. We should introduce
          // special handling for both and do minimal/no stack mutation here.
          for (size_t i = 0; i < value_count; ++i) Push(sig->GetParam(i));
          Vector<Value> values(stack_.data() + c->stack_depth, value_count);
          if (!TypeCheckBranch(c)) break;
          if (control_.back().reachable()) {
1812
            CALL_INTERFACE(BrOnException, exception, imm.index, imm.depth.depth,
1813 1814
                           values);
            c->br_merge()->reached = true;
1815
          }
1816
          len = 1 + imm.length;
1817 1818 1819
          for (size_t i = 0; i < value_count; ++i) Pop();
          auto* pexception = Push(kWasmExceptRef);
          *pexception = exception;
1820 1821 1822 1823 1824
          break;
        }
        case kExprLoop: {
          BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_);
          if (!this->Validate(imm)) break;
1825
          auto args = PopArgs(imm.sig);
1826
          auto* block = PushControl(kControlLoop);
1827
          SetBlockType(&control_.back(), imm, args.begin());
1828 1829 1830 1831 1832 1833 1834 1835 1836
          len = 1 + imm.length;
          CALL_INTERFACE_IF_REACHABLE(Loop, block);
          PushMergeValues(block, &block->start_merge);
          break;
        }
        case kExprIf: {
          BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_);
          if (!this->Validate(imm)) break;
          auto cond = Pop(0, kWasmI32);
1837
          auto args = PopArgs(imm.sig);
1838
          if (!VALIDATE(this->ok())) break;
1839
          auto* if_block = PushControl(kControlIf);
1840
          SetBlockType(if_block, imm, args.begin());
1841 1842 1843 1844 1845 1846 1847 1848
          CALL_INTERFACE_IF_REACHABLE(If, cond, if_block);
          len = 1 + imm.length;
          PushMergeValues(if_block, &if_block->start_merge);
          break;
        }
        case kExprElse: {
          if (!VALIDATE(!control_.empty())) {
            this->error("else does not match any if");
1849 1850
            break;
          }
1851 1852 1853
          Control* c = &control_.back();
          if (!VALIDATE(c->is_if())) {
            this->error(this->pc_, "else does not match an if");
1854 1855
            break;
          }
1856 1857
          if (c->is_if_else()) {
            this->error(this->pc_, "else already present for if");
1858 1859
            break;
          }
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
          if (!TypeCheckFallThru(c)) break;
          c->kind = kControlIfElse;
          CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c);
          if (c->reachable()) c->end_merge.reached = true;
          PushMergeValues(c, &c->start_merge);
          c->reachability = control_at(1)->innerReachability();
          break;
        }
        case kExprEnd: {
          if (!VALIDATE(!control_.empty())) {
            this->error("end does not match any if, try, or block");
1871 1872
            break;
          }
1873 1874 1875
          Control* c = &control_.back();
          if (!VALIDATE(!c->is_incomplete_try())) {
            this->error(this->pc_, "missing catch or catch-all in try");
1876 1877
            break;
          }
1878 1879 1880 1881 1882 1883
          if (c->is_onearmed_if()) {
            if (!VALIDATE(c->end_merge.arity == c->start_merge.arity)) {
              this->error(
                  c->pc,
                  "start-arity and end-arity of one-armed if must match");
              break;
1884
            }
1885
          }
1886

1887 1888 1889
          if (!TypeCheckFallThru(c)) break;

          if (control_.size() == 1) {
1890 1891 1892 1893 1894 1895 1896 1897 1898
            // If at the last (implicit) control, check we are at end.
            if (!VALIDATE(this->pc_ + 1 == this->end_)) {
              this->error(this->pc_ + 1, "trailing code after function end");
              break;
            }
            // The result of the block is the return value.
            TRACE_PART("\n" TRACE_INST_FORMAT, startrel(this->pc_),
                       "(implicit) return");
            DoReturn();
1899 1900
            control_.clear();
            break;
1901
          }
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923

          PopControl(c);
          break;
        }
        case kExprSelect: {
          auto cond = Pop(2, kWasmI32);
          auto fval = Pop();
          auto tval = Pop(0, fval.type);
          auto* result = Push(tval.type == kWasmVar ? fval.type : tval.type);
          CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result);
          break;
        }
        case kExprBr: {
          BranchDepthImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm, control_.size())) break;
          Control* c = control_at(imm.depth);
          if (!TypeCheckBranch(c)) break;
          if (imm.depth == control_.size() - 1) {
            DoReturn();
          } else if (control_.back().reachable()) {
            CALL_INTERFACE(Br, c);
            c->br_merge()->reached = true;
1924
          }
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
          len = 1 + imm.length;
          EndControl();
          break;
        }
        case kExprBrIf: {
          BranchDepthImmediate<validate> imm(this, this->pc_);
          auto cond = Pop(0, kWasmI32);
          if (this->failed()) break;
          if (!this->Validate(this->pc_, imm, control_.size())) break;
          Control* c = control_at(imm.depth);
          if (!TypeCheckBranch(c)) break;
          if (control_.back().reachable()) {
            CALL_INTERFACE(BrIf, cond, imm.depth);
            c->br_merge()->reached = true;
1939
          }
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
          len = 1 + imm.length;
          break;
        }
        case kExprBrTable: {
          BranchTableImmediate<validate> imm(this, this->pc_);
          BranchTableIterator<validate> iterator(this, imm);
          auto key = Pop(0, kWasmI32);
          if (this->failed()) break;
          if (!this->Validate(this->pc_, imm, control_.size())) break;
          uint32_t br_arity = 0;
          std::vector<bool> br_targets(control_.size());
          while (iterator.has_next()) {
            const uint32_t i = iterator.cur_index();
            const byte* pos = iterator.pc();
            uint32_t target = iterator.next();
            if (!VALIDATE(target < control_.size())) {
              this->errorf(pos,
                           "improper branch in br_table target %u (depth %u)",
                           i, target);
1959 1960
              break;
            }
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
            // Avoid redundant branch target checks.
            if (br_targets[target]) continue;
            br_targets[target] = true;
            // Check that label types match up.
            Control* c = control_at(target);
            uint32_t arity = c->br_merge()->arity;
            if (i == 0) {
              br_arity = arity;
            } else if (!VALIDATE(br_arity == arity)) {
              this->errorf(pos,
                           "inconsistent arity in br_table target %u"
                           " (previous was %u, this one %u)",
                           i, br_arity, arity);
1974
            }
1975
            if (!TypeCheckBranch(c)) break;
1976
          }
1977 1978 1979 1980 1981 1982 1983 1984
          if (this->failed()) break;

          if (control_.back().reachable()) {
            CALL_INTERFACE(BrTable, imm, key);

            for (uint32_t depth = control_depth(); depth-- > 0;) {
              if (!br_targets[depth]) continue;
              control_at(depth)->br_merge()->reached = true;
1985
            }
1986
          }
1987 1988 1989 1990 1991 1992 1993 1994

          len = 1 + iterator.length();
          EndControl();
          break;
        }
        case kExprReturn: {
          if (!TypeCheckReturn()) break;
          DoReturn();
1995
          EndControl();
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
          break;
        }
        case kExprUnreachable: {
          CALL_INTERFACE_IF_REACHABLE(Unreachable);
          EndControl();
          break;
        }
        case kExprI32Const: {
          ImmI32Immediate<validate> imm(this, this->pc_);
          auto* value = Push(kWasmI32);
          CALL_INTERFACE_IF_REACHABLE(I32Const, value, imm.value);
          len = 1 + imm.length;
          break;
        }
        case kExprI64Const: {
          ImmI64Immediate<validate> imm(this, this->pc_);
          auto* value = Push(kWasmI64);
          CALL_INTERFACE_IF_REACHABLE(I64Const, value, imm.value);
          len = 1 + imm.length;
          break;
        }
        case kExprF32Const: {
          ImmF32Immediate<validate> imm(this, this->pc_);
          auto* value = Push(kWasmF32);
          CALL_INTERFACE_IF_REACHABLE(F32Const, value, imm.value);
          len = 1 + imm.length;
          break;
        }
        case kExprF64Const: {
          ImmF64Immediate<validate> imm(this, this->pc_);
          auto* value = Push(kWasmF64);
          CALL_INTERFACE_IF_REACHABLE(F64Const, value, imm.value);
          len = 1 + imm.length;
          break;
        }
        case kExprRefNull: {
          CHECK_PROTOTYPE_OPCODE(anyref);
2033
          auto* value = Push(kWasmNullRef);
2034 2035 2036 2037
          CALL_INTERFACE_IF_REACHABLE(RefNull, value);
          len = 1;
          break;
        }
2038 2039 2040 2041 2042 2043 2044 2045 2046
        case kExprRefFunc: {
          CHECK_PROTOTYPE_OPCODE(anyref);
          FunctionIndexImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm)) break;
          auto* value = Push(kWasmAnyFunc);
          CALL_INTERFACE_IF_REACHABLE(RefFunc, imm.index, value);
          len = 1 + imm.length;
          break;
        }
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
        case kExprGetLocal: {
          LocalIndexImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm)) break;
          auto* value = Push(imm.type);
          CALL_INTERFACE_IF_REACHABLE(GetLocal, value, imm);
          len = 1 + imm.length;
          break;
        }
        case kExprSetLocal: {
          LocalIndexImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm)) break;
          auto value = Pop(0, local_type_vec_[imm.index]);
          CALL_INTERFACE_IF_REACHABLE(SetLocal, value, imm);
          len = 1 + imm.length;
          break;
        }
        case kExprTeeLocal: {
          LocalIndexImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(this->pc_, imm)) break;
          auto value = Pop(0, local_type_vec_[imm.index]);
          auto* result = Push(value.type);
          CALL_INTERFACE_IF_REACHABLE(TeeLocal, value, result, imm);
          len = 1 + imm.length;
          break;
        }
        case kExprDrop: {
          auto value = Pop();
          CALL_INTERFACE_IF_REACHABLE(Drop, value);
          break;
        }
        case kExprGetGlobal: {
          GlobalIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
          auto* result = Push(imm.type);
          CALL_INTERFACE_IF_REACHABLE(GetGlobal, result, imm);
          break;
        }
        case kExprSetGlobal: {
          GlobalIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
          if (!VALIDATE(imm.global->mutability)) {
            this->errorf(this->pc_, "immutable global #%u cannot be assigned",
                         imm.index);
2092 2093
            break;
          }
2094 2095 2096 2097
          auto value = Pop(0, imm.type);
          CALL_INTERFACE_IF_REACHABLE(SetGlobal, value, imm);
          break;
        }
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
        case kExprGetTable: {
          CHECK_PROTOTYPE_OPCODE(anyref);
          TableIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
          DCHECK_NOT_NULL(this->module_);
          auto index = Pop(0, kWasmI32);
          auto* result = Push(this->module_->tables[imm.index].type);
          CALL_INTERFACE_IF_REACHABLE(GetTable, index, result, imm);
          break;
        }
        case kExprSetTable: {
          CHECK_PROTOTYPE_OPCODE(anyref);
          TableIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
2114
          auto value = Pop(1, this->module_->tables[imm.index].type);
2115 2116 2117 2118 2119
          auto index = Pop(0, kWasmI32);
          CALL_INTERFACE_IF_REACHABLE(SetTable, index, value, imm);
          break;
        }

2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
        case kExprI32LoadMem8S:
          len = 1 + DecodeLoadMem(LoadType::kI32Load8S);
          break;
        case kExprI32LoadMem8U:
          len = 1 + DecodeLoadMem(LoadType::kI32Load8U);
          break;
        case kExprI32LoadMem16S:
          len = 1 + DecodeLoadMem(LoadType::kI32Load16S);
          break;
        case kExprI32LoadMem16U:
          len = 1 + DecodeLoadMem(LoadType::kI32Load16U);
          break;
        case kExprI32LoadMem:
          len = 1 + DecodeLoadMem(LoadType::kI32Load);
          break;
        case kExprI64LoadMem8S:
          len = 1 + DecodeLoadMem(LoadType::kI64Load8S);
          break;
        case kExprI64LoadMem8U:
          len = 1 + DecodeLoadMem(LoadType::kI64Load8U);
          break;
        case kExprI64LoadMem16S:
          len = 1 + DecodeLoadMem(LoadType::kI64Load16S);
          break;
        case kExprI64LoadMem16U:
          len = 1 + DecodeLoadMem(LoadType::kI64Load16U);
          break;
        case kExprI64LoadMem32S:
          len = 1 + DecodeLoadMem(LoadType::kI64Load32S);
          break;
        case kExprI64LoadMem32U:
          len = 1 + DecodeLoadMem(LoadType::kI64Load32U);
          break;
        case kExprI64LoadMem:
          len = 1 + DecodeLoadMem(LoadType::kI64Load);
          break;
        case kExprF32LoadMem:
          len = 1 + DecodeLoadMem(LoadType::kF32Load);
          break;
        case kExprF64LoadMem:
          len = 1 + DecodeLoadMem(LoadType::kF64Load);
          break;
        case kExprI32StoreMem8:
          len = 1 + DecodeStoreMem(StoreType::kI32Store8);
          break;
        case kExprI32StoreMem16:
          len = 1 + DecodeStoreMem(StoreType::kI32Store16);
          break;
        case kExprI32StoreMem:
          len = 1 + DecodeStoreMem(StoreType::kI32Store);
          break;
        case kExprI64StoreMem8:
          len = 1 + DecodeStoreMem(StoreType::kI64Store8);
          break;
        case kExprI64StoreMem16:
          len = 1 + DecodeStoreMem(StoreType::kI64Store16);
          break;
        case kExprI64StoreMem32:
          len = 1 + DecodeStoreMem(StoreType::kI64Store32);
          break;
        case kExprI64StoreMem:
          len = 1 + DecodeStoreMem(StoreType::kI64Store);
          break;
        case kExprF32StoreMem:
          len = 1 + DecodeStoreMem(StoreType::kF32Store);
          break;
        case kExprF64StoreMem:
          len = 1 + DecodeStoreMem(StoreType::kF64Store);
          break;
        case kExprMemoryGrow: {
          if (!CheckHasMemory()) break;
          MemoryIndexImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          DCHECK_NOT_NULL(this->module_);
          if (!VALIDATE(this->module_->origin == kWasmOrigin)) {
            this->error("grow_memory is not supported for asmjs modules");
2196 2197
            break;
          }
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
          auto value = Pop(0, kWasmI32);
          auto* result = Push(kWasmI32);
          CALL_INTERFACE_IF_REACHABLE(MemoryGrow, value, result);
          break;
        }
        case kExprMemorySize: {
          if (!CheckHasMemory()) break;
          MemoryIndexImmediate<validate> imm(this, this->pc_);
          auto* result = Push(kWasmI32);
          len = 1 + imm.length;
          CALL_INTERFACE_IF_REACHABLE(CurrentMemoryPages, result);
          break;
        }
        case kExprCallFunction: {
          CallFunctionImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
2215
          auto args = PopArgs(imm.sig);
2216
          auto* returns = PushReturns(imm.sig);
2217
          CALL_INTERFACE_IF_REACHABLE(CallDirect, imm, args.begin(), returns);
2218 2219 2220
          break;
        }
        case kExprCallIndirect: {
2221
          CallIndirectImmediate<validate> imm(this->enabled_, this, this->pc_);
2222 2223 2224
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
          auto index = Pop(0, kWasmI32);
2225
          auto args = PopArgs(imm.sig);
2226
          auto* returns = PushReturns(imm.sig);
2227
          CALL_INTERFACE_IF_REACHABLE(CallIndirect, index, imm, args.begin(),
2228 2229 2230
                                      returns);
          break;
        }
2231 2232 2233 2234 2235 2236
        case kExprReturnCall: {
          CHECK_PROTOTYPE_OPCODE(return_call);

          CallFunctionImmediate<validate> imm(this, this->pc_);
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
2237
          if (!this->CanReturnCall(imm.sig)) {
2238 2239 2240 2241
            OPCODE_ERROR(opcode, "tail call return types mismatch");
            break;
          }

2242
          auto args = PopArgs(imm.sig);
2243

2244
          CALL_INTERFACE_IF_REACHABLE(ReturnCall, imm, args.begin());
2245 2246 2247 2248 2249
          EndControl();
          break;
        }
        case kExprReturnCallIndirect: {
          CHECK_PROTOTYPE_OPCODE(return_call);
2250
          CallIndirectImmediate<validate> imm(this->enabled_, this, this->pc_);
2251 2252
          len = 1 + imm.length;
          if (!this->Validate(this->pc_, imm)) break;
2253
          if (!this->CanReturnCall(imm.sig)) {
2254 2255 2256 2257
            OPCODE_ERROR(opcode, "tail call return types mismatch");
            break;
          }
          auto index = Pop(0, kWasmI32);
2258
          auto args = PopArgs(imm.sig);
2259
          CALL_INTERFACE_IF_REACHABLE(ReturnCallIndirect, index, imm,
2260
                                      args.begin());
2261 2262 2263
          EndControl();
          break;
        }
2264 2265 2266 2267 2268 2269 2270
        case kNumericPrefix: {
          ++len;
          byte numeric_index =
              this->template read_u8<validate>(this->pc_ + 1, "numeric index");
          opcode = static_cast<WasmOpcode>(opcode << 8 | numeric_index);
          if (opcode < kExprMemoryInit) {
            CHECK_PROTOTYPE_OPCODE(sat_f2i_conversions);
2271 2272
          } else if (opcode == kExprTableGrow || opcode == kExprTableSize ||
                     opcode == kExprTableFill) {
2273
            CHECK_PROTOTYPE_OPCODE(anyref);
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
          } else {
            CHECK_PROTOTYPE_OPCODE(bulk_memory);
          }
          TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
                     WasmOpcodes::OpcodeName(opcode));
          len += DecodeNumericOpcode(opcode);
          break;
        }
        case kSimdPrefix: {
          CHECK_PROTOTYPE_OPCODE(simd);
          len++;
          byte simd_index =
              this->template read_u8<validate>(this->pc_ + 1, "simd index");
          opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index);
          TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
                     WasmOpcodes::OpcodeName(opcode));
          len += DecodeSimdOpcode(opcode);
          break;
        }
        case kAtomicPrefix: {
          CHECK_PROTOTYPE_OPCODE(threads);
          if (!CheckHasSharedMemory()) break;
          len++;
          byte atomic_index =
              this->template read_u8<validate>(this->pc_ + 1, "atomic index");
          opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index);
          TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
                     WasmOpcodes::OpcodeName(opcode));
          len += DecodeAtomicOpcode(opcode);
          break;
        }
2305 2306 2307 2308
// Note that prototype opcodes are not handled in the fastpath
// above this switch, to avoid checking a feature flag.
#define SIMPLE_PROTOTYPE_CASE(name, opc, sig) \
  case kExpr##name: /* fallthrough */
2309
          FOREACH_SIMPLE_PROTOTYPE_OPCODE(SIMPLE_PROTOTYPE_CASE)
2310
#undef SIMPLE_PROTOTYPE_CASE
2311 2312 2313 2314 2315 2316 2317 2318 2319
          BuildSimplePrototypeOperator(opcode);
          break;
        default: {
          // Deal with special asmjs opcodes.
          if (this->module_ != nullptr &&
              this->module_->origin == kAsmJsOrigin) {
            FunctionSig* sig = WasmOpcodes::AsmjsSignature(opcode);
            if (sig) {
              BuildSimpleOperator(opcode, sig);
2320
            }
2321 2322 2323
          } else {
            this->error("Invalid opcode");
            return;
2324 2325 2326 2327 2328 2329
          }
        }
      }

#if DEBUG
      if (FLAG_trace_wasm_decoder) {
2330
        TRACE_PART(" ");
2331 2332
        for (Control& c : control_) {
          switch (c.kind) {
2333
            case kControlIf:
2334
              TRACE_PART("I");
2335 2336
              break;
            case kControlBlock:
2337
              TRACE_PART("B");
2338 2339
              break;
            case kControlLoop:
2340
              TRACE_PART("L");
2341 2342
              break;
            case kControlTry:
2343
              TRACE_PART("T");
2344 2345 2346 2347
              break;
            default:
              break;
          }
2348 2349 2350
          if (c.start_merge.arity) TRACE_PART("%u-", c.start_merge.arity);
          TRACE_PART("%u", c.end_merge.arity);
          if (!c.reachable()) TRACE_PART("%c", c.unreachable() ? '*' : '#');
2351
        }
2352
        TRACE_PART(" | ");
2353 2354 2355 2356 2357 2358
        for (size_t i = 0; i < stack_.size(); ++i) {
          auto& val = stack_[i];
          WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc);
          if (WasmOpcodes::IsPrefixOpcode(opcode)) {
            opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1));
          }
2359
          TRACE_PART(" %c@%d:%s", ValueTypes::ShortNameOf(val.type),
2360 2361
                     static_cast<int>(val.pc - this->start_),
                     WasmOpcodes::OpcodeName(opcode));
2362
          // If the decoder failed, don't try to decode the immediates, as this
2363 2364
          // can trigger a DCHECK failure.
          if (this->failed()) continue;
2365 2366
          switch (opcode) {
            case kExprI32Const: {
2367 2368
              ImmI32Immediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%d]", imm.value);
2369 2370
              break;
            }
2371 2372 2373
            case kExprGetLocal:
            case kExprSetLocal:
            case kExprTeeLocal: {
2374 2375
              LocalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%u]", imm.index);
2376 2377
              break;
            }
2378 2379
            case kExprGetGlobal:
            case kExprSetGlobal: {
2380 2381
              GlobalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%u]", imm.index);
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
              break;
            }
            default:
              break;
          }
        }
      }
#endif
      this->pc_ += len;
    }  // end decode loop
2392 2393 2394
    if (!VALIDATE(this->pc_ == this->end_) && this->ok()) {
      this->error("Beyond end of code");
    }
2395 2396 2397 2398 2399
  }

  void EndControl() {
    DCHECK(!control_.empty());
    auto* current = &control_.back();
2400
    stack_.erase(stack_.begin() + current->stack_depth, stack_.end());
2401
    CALL_INTERFACE_IF_REACHABLE(EndControl, current);
2402
    current->reachability = kUnreachable;
2403 2404
  }

2405 2406 2407 2408 2409 2410 2411
  template<typename func>
  void InitMerge(Merge<Value>* merge, uint32_t arity, func get_val) {
    merge->arity = arity;
    if (arity == 1) {
      merge->vals.first = get_val(0);
    } else if (arity > 1) {
      merge->vals.array = zone_->NewArray<Value>(arity);
2412
      for (uint32_t i = 0; i < arity; i++) {
2413
        merge->vals.array[i] = get_val(i);
2414 2415 2416 2417
      }
    }
  }

2418 2419
  void SetBlockType(Control* c, BlockTypeImmediate<validate>& imm,
                    Value* args) {
2420
    const byte* pc = this->pc_;
2421
    InitMerge(&c->end_merge, imm.out_arity(), [pc, &imm](uint32_t i) {
2422
      return Value{pc, imm.out_type(i)};
2423
    });
2424
    InitMerge(&c->start_merge, imm.in_arity(),
2425
              [args](uint32_t i) { return args[i]; });
2426 2427
  }

2428 2429
  // Pops arguments as required by signature.
  V8_INLINE ArgVector PopArgs(FunctionSig* sig) {
2430
    int count = sig ? static_cast<int>(sig->parameter_count()) : 0;
2431
    ArgVector args(count);
2432
    for (int i = count - 1; i >= 0; --i) {
2433
      args[i] = Pop(i, sig->GetParam(i));
2434
    }
2435
    return args;
2436 2437 2438 2439 2440 2441 2442
  }

  ValueType GetReturnType(FunctionSig* sig) {
    DCHECK_GE(1, sig->return_count());
    return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn();
  }

2443
  Control* PushControl(ControlKind kind) {
2444 2445
    Reachability reachability =
        control_.empty() ? kReachable : control_.back().innerReachability();
2446 2447
    control_.emplace_back(kind, stack_size(), this->pc_, reachability);
    return &control_.back();
2448 2449 2450 2451
  }

  void PopControl(Control* c) {
    DCHECK_EQ(c, &control_.back());
2452
    CALL_INTERFACE_IF_PARENT_REACHABLE(PopControl, c);
2453 2454 2455 2456 2457 2458

    // A loop just leaves the values on the stack.
    if (!c->is_loop()) PushMergeValues(c, &c->end_merge);

    bool parent_reached =
        c->reachable() || c->end_merge.reached || c->is_onearmed_if();
2459
    control_.pop_back();
2460
    // If the parent block was reachable before, but the popped control does not
2461 2462
    // return to here, this block becomes "spec only reachable".
    if (!parent_reached && control_.back().reachable()) {
2463 2464
      control_.back().reachability = kSpecOnlyReachable;
    }
2465 2466
  }

2467
  int DecodeLoadMem(LoadType type, int prefix_len = 0) {
2468
    if (!CheckHasMemory()) return 0;
2469 2470
    MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len,
                                        type.size_log_2());
2471
    auto index = Pop(0, kWasmI32);
2472
    auto* result = Push(type.value_type());
2473 2474
    CALL_INTERFACE_IF_REACHABLE(LoadMem, type, imm, index, result);
    return imm.length;
2475 2476
  }

2477
  int DecodeStoreMem(StoreType store, int prefix_len = 0) {
2478
    if (!CheckHasMemory()) return 0;
2479 2480
    MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len,
                                        store.size_log_2());
2481
    auto value = Pop(1, store.value_type());
2482
    auto index = Pop(0, kWasmI32);
2483 2484
    CALL_INTERFACE_IF_REACHABLE(StoreMem, store, imm, index, value);
    return imm.length;
2485 2486
  }

2487
  uint32_t SimdExtractLane(WasmOpcode opcode, ValueType type) {
2488 2489
    SimdLaneImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2490
      Value inputs[] = {Pop(0, kWasmS128)};
2491
      auto* result = Push(type);
2492 2493
      CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs),
                                  result);
2494
    }
2495
    return imm.length;
2496 2497
  }

2498
  uint32_t SimdReplaceLane(WasmOpcode opcode, ValueType type) {
2499 2500
    SimdLaneImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2501 2502
      Value inputs[2] = {UnreachableValue(this->pc_),
                         UnreachableValue(this->pc_)};
2503
      inputs[1] = Pop(1, type);
2504 2505
      inputs[0] = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2506 2507
      CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs),
                                  result);
2508
    }
2509
    return imm.length;
2510 2511
  }

2512
  uint32_t SimdShiftOp(WasmOpcode opcode) {
2513 2514
    SimdShiftImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2515 2516
      auto input = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2517
      CALL_INTERFACE_IF_REACHABLE(SimdShiftOp, opcode, imm, input, result);
2518
    }
2519
    return imm.length;
2520 2521
  }

2522
  uint32_t Simd8x16ShuffleOp() {
2523 2524
    Simd8x16ShuffleImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, imm)) {
2525 2526 2527
      auto input1 = Pop(1, kWasmS128);
      auto input0 = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2528
      CALL_INTERFACE_IF_REACHABLE(Simd8x16ShuffleOp, imm, input0, input1,
2529
                                  result);
2530 2531 2532 2533
    }
    return 16;
  }

2534 2535
  uint32_t DecodeSimdOpcode(WasmOpcode opcode) {
    uint32_t len = 0;
2536 2537
    switch (opcode) {
      case kExprF32x4ExtractLane: {
2538
        len = SimdExtractLane(opcode, kWasmF32);
2539 2540 2541 2542 2543
        break;
      }
      case kExprI32x4ExtractLane:
      case kExprI16x8ExtractLane:
      case kExprI8x16ExtractLane: {
2544
        len = SimdExtractLane(opcode, kWasmI32);
2545 2546 2547
        break;
      }
      case kExprF32x4ReplaceLane: {
2548
        len = SimdReplaceLane(opcode, kWasmF32);
2549 2550 2551 2552 2553
        break;
      }
      case kExprI32x4ReplaceLane:
      case kExprI16x8ReplaceLane:
      case kExprI8x16ReplaceLane: {
2554
        len = SimdReplaceLane(opcode, kWasmI32);
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
        break;
      }
      case kExprI32x4Shl:
      case kExprI32x4ShrS:
      case kExprI32x4ShrU:
      case kExprI16x8Shl:
      case kExprI16x8ShrS:
      case kExprI16x8ShrU:
      case kExprI8x16Shl:
      case kExprI8x16ShrS:
      case kExprI8x16ShrU: {
        len = SimdShiftOp(opcode);
        break;
      }
      case kExprS8x16Shuffle: {
        len = Simd8x16ShuffleOp();
        break;
      }
      case kExprS128LoadMem:
2574
        len = DecodeLoadMem(LoadType::kS128Load, 1);
2575 2576
        break;
      case kExprS128StoreMem:
2577
        len = DecodeStoreMem(StoreType::kS128Store, 1);
2578 2579 2580
        break;
      default: {
        FunctionSig* sig = WasmOpcodes::Signature(opcode);
2581
        if (!VALIDATE(sig != nullptr)) {
2582 2583 2584
          this->error("invalid simd opcode");
          break;
        }
2585
        auto args = PopArgs(sig);
2586
        auto* results =
2587
            sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig));
2588
        CALL_INTERFACE_IF_REACHABLE(SimdOp, opcode, VectorOf(args), results);
2589 2590 2591 2592 2593
      }
    }
    return len;
  }

2594 2595
  uint32_t DecodeAtomicOpcode(WasmOpcode opcode) {
    uint32_t len = 0;
2596
    ValueType ret_type;
2597
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
2598
    if (sig != nullptr) {
2599 2600
      MachineType memtype;
      switch (opcode) {
2601 2602 2603 2604 2605
#define CASE_ATOMIC_STORE_OP(Name, Type) \
  case kExpr##Name: {                    \
    memtype = MachineType::Type();       \
    ret_type = kWasmStmt;                \
    break;                               \
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
  }
        ATOMIC_STORE_OP_LIST(CASE_ATOMIC_STORE_OP)
#undef CASE_ATOMIC_OP
#define CASE_ATOMIC_OP(Name, Type) \
  case kExpr##Name: {              \
    memtype = MachineType::Type(); \
    ret_type = GetReturnType(sig); \
    break;                         \
  }
        ATOMIC_OP_LIST(CASE_ATOMIC_OP)
#undef CASE_ATOMIC_OP
        default:
          this->error("invalid atomic opcode");
2619
          return 0;
2620
      }
2621
      MemoryAccessImmediate<validate> imm(
2622
          this, this->pc_ + 1, ElementSizeLog2Of(memtype.representation()));
2623
      len += imm.length;
2624
      auto args = PopArgs(sig);
2625
      auto result = ret_type == kWasmStmt ? nullptr : Push(GetReturnType(sig));
2626
      CALL_INTERFACE_IF_REACHABLE(AtomicOp, opcode, VectorOf(args), imm,
2627
                                  result);
2628 2629 2630 2631 2632 2633
    } else {
      this->error("invalid atomic opcode");
    }
    return len;
  }

2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
  unsigned DecodeNumericOpcode(WasmOpcode opcode) {
    unsigned len = 0;
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
    if (sig != nullptr) {
      switch (opcode) {
        case kExprI32SConvertSatF32:
        case kExprI32UConvertSatF32:
        case kExprI32SConvertSatF64:
        case kExprI32UConvertSatF64:
        case kExprI64SConvertSatF32:
        case kExprI64UConvertSatF32:
        case kExprI64SConvertSatF64:
        case kExprI64UConvertSatF64:
          BuildSimpleOperator(opcode, sig);
          break;
        case kExprMemoryInit: {
          MemoryInitImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(imm)) break;
          len += imm.length;
2653 2654 2655 2656
          auto size = Pop(2, sig->GetParam(2));
          auto src = Pop(1, sig->GetParam(1));
          auto dst = Pop(0, sig->GetParam(0));
          CALL_INTERFACE_IF_REACHABLE(MemoryInit, imm, dst, src, size);
2657 2658
          break;
        }
2659 2660
        case kExprDataDrop: {
          DataDropImmediate<validate> imm(this, this->pc_);
2661 2662
          if (!this->Validate(imm)) break;
          len += imm.length;
2663
          CALL_INTERFACE_IF_REACHABLE(DataDrop, imm);
2664 2665 2666
          break;
        }
        case kExprMemoryCopy: {
2667
          MemoryCopyImmediate<validate> imm(this, this->pc_);
2668 2669
          if (!this->Validate(imm)) break;
          len += imm.length;
2670 2671 2672 2673
          auto size = Pop(2, sig->GetParam(2));
          auto src = Pop(1, sig->GetParam(1));
          auto dst = Pop(0, sig->GetParam(0));
          CALL_INTERFACE_IF_REACHABLE(MemoryCopy, imm, dst, src, size);
2674 2675 2676 2677
          break;
        }
        case kExprMemoryFill: {
          MemoryIndexImmediate<validate> imm(this, this->pc_ + 1);
2678
          if (!this->Validate(this->pc_ + 1, imm)) break;
2679
          len += imm.length;
2680 2681 2682 2683
          auto size = Pop(2, sig->GetParam(2));
          auto value = Pop(1, sig->GetParam(1));
          auto dst = Pop(0, sig->GetParam(0));
          CALL_INTERFACE_IF_REACHABLE(MemoryFill, imm, dst, value, size);
2684 2685 2686 2687 2688 2689
          break;
        }
        case kExprTableInit: {
          TableInitImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(imm)) break;
          len += imm.length;
2690 2691
          auto args = PopArgs(sig);
          CALL_INTERFACE_IF_REACHABLE(TableInit, imm, VectorOf(args));
2692 2693
          break;
        }
2694 2695
        case kExprElemDrop: {
          ElemDropImmediate<validate> imm(this, this->pc_);
2696 2697
          if (!this->Validate(imm)) break;
          len += imm.length;
2698
          CALL_INTERFACE_IF_REACHABLE(ElemDrop, imm);
2699 2700 2701
          break;
        }
        case kExprTableCopy: {
2702 2703
          TableCopyImmediate<validate> imm(this, this->pc_);
          if (!this->Validate(imm)) break;
2704
          len += imm.length;
2705 2706
          auto args = PopArgs(sig);
          CALL_INTERFACE_IF_REACHABLE(TableCopy, imm, VectorOf(args));
2707 2708
          break;
        }
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
        case kExprTableGrow: {
          TableIndexImmediate<validate> imm(this, this->pc_ + 1);
          if (!this->Validate(this->pc_, imm)) break;
          len += imm.length;
          auto delta = Pop(1, sig->GetParam(1));
          auto value = Pop(0, this->module_->tables[imm.index].type);
          auto* result = Push(kWasmI32);
          CALL_INTERFACE_IF_REACHABLE(TableGrow, imm, value, delta, result);
          break;
        }
2719 2720 2721 2722 2723 2724 2725 2726
        case kExprTableSize: {
          TableIndexImmediate<validate> imm(this, this->pc_ + 1);
          if (!this->Validate(this->pc_, imm)) break;
          len += imm.length;
          auto* result = Push(kWasmI32);
          CALL_INTERFACE_IF_REACHABLE(TableSize, imm, result);
          break;
        }
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
        case kExprTableFill: {
          TableIndexImmediate<validate> imm(this, this->pc_ + 1);
          if (!this->Validate(this->pc_, imm)) break;
          len += imm.length;
          auto count = Pop(2, sig->GetParam(2));
          auto value = Pop(1, this->module_->tables[imm.index].type);
          auto start = Pop(0, sig->GetParam(0));
          CALL_INTERFACE_IF_REACHABLE(TableFill, imm, start, value, count);
          break;
        }
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
        default:
          this->error("invalid numeric opcode");
          break;
      }
    } else {
      this->error("invalid numeric opcode");
    }
    return len;
  }

2747
  void DoReturn() {
2748
    size_t return_count = this->sig_->return_count();
2749
    DCHECK_GE(stack_.size(), return_count);
2750 2751 2752 2753
    Vector<Value> return_values =
        return_count == 0
            ? Vector<Value>{}
            : Vector<Value>{&*(stack_.end() - return_count), return_count};
2754

2755
    CALL_INTERFACE_IF_REACHABLE(DoReturn, return_values);
2756 2757 2758
  }

  inline Value* Push(ValueType type) {
2759
    DCHECK_NE(kWasmStmt, type);
2760
    stack_.emplace_back(this->pc_, type);
2761 2762 2763
    return &stack_.back();
  }

2764
  void PushMergeValues(Control* c, Merge<Value>* merge) {
2765
    DCHECK_EQ(c, &control_.back());
2766
    DCHECK(merge == &c->start_merge || merge == &c->end_merge);
2767
    stack_.erase(stack_.begin() + c->stack_depth, stack_.end());
2768 2769
    if (merge->arity == 1) {
      stack_.push_back(merge->vals.first);
2770
    } else {
2771
      for (uint32_t i = 0; i < merge->arity; i++) {
2772
        stack_.push_back(merge->vals.array[i]);
2773 2774
      }
    }
2775
    DCHECK_EQ(c->stack_depth + merge->arity, stack_.size());
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
  }

  Value* PushReturns(FunctionSig* sig) {
    size_t return_count = sig->return_count();
    if (return_count == 0) return nullptr;
    size_t old_size = stack_.size();
    for (size_t i = 0; i < return_count; ++i) {
      Push(sig->GetReturn(i));
    }
    return stack_.data() + old_size;
  }

2788
  V8_INLINE Value Pop(int index, ValueType expected) {
2789
    auto val = Pop();
2790 2791
    if (!VALIDATE(ValueTypes::IsSubType(expected, val.type) ||
                  val.type == kWasmVar || expected == kWasmVar)) {
2792 2793
      this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s",
                   SafeOpcodeNameAt(this->pc_), index,
2794 2795
                   ValueTypes::TypeName(expected), SafeOpcodeNameAt(val.pc),
                   ValueTypes::TypeName(val.type));
2796 2797 2798 2799
    }
    return val;
  }

2800
  V8_INLINE Value Pop() {
2801
    DCHECK(!control_.empty());
2802
    uint32_t limit = control_.back().stack_depth;
2803 2804
    if (stack_.size() <= limit) {
      // Popping past the current control start in reachable code.
2805
      if (!VALIDATE(control_.back().unreachable())) {
2806 2807 2808
        this->errorf(this->pc_, "%s found empty stack",
                     SafeOpcodeNameAt(this->pc_));
      }
2809
      return UnreachableValue(this->pc_);
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
    }
    auto val = stack_.back();
    stack_.pop_back();
    return val;
  }

  int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); }

  void FallThruTo(Control* c) {
    DCHECK_EQ(c, &control_.back());
    if (!TypeCheckFallThru(c)) return;
2821
    if (!c->reachable()) return;
2822

2823 2824
    if (!c->is_loop()) CALL_INTERFACE(FallThruTo, c);
    c->end_merge.reached = true;
2825 2826
  }

2827 2828 2829
  bool TypeCheckMergeValues(Control* c, Merge<Value>* merge) {
    DCHECK(merge == &c->start_merge || merge == &c->end_merge);
    DCHECK_GE(stack_.size(), c->stack_depth + merge->arity);
2830 2831 2832
    // The computation of {stack_values} is only valid if {merge->arity} is >0.
    DCHECK_LT(0, merge->arity);
    Value* stack_values = &*(stack_.end() - merge->arity);
2833 2834
    // Typecheck the topmost {merge->arity} values on the stack.
    for (uint32_t i = 0; i < merge->arity; ++i) {
2835 2836
      Value& val = stack_values[i];
      Value& old = (*merge)[i];
2837
      if (ValueTypes::IsSubType(old.type, val.type)) continue;
2838 2839 2840 2841 2842 2843 2844 2845
      // If {val.type} is polymorphic, which results from unreachable, make
      // it more specific by using the merge value's expected type.
      // If it is not polymorphic, this is a type error.
      if (!VALIDATE(val.type == kWasmVar)) {
        this->errorf(this->pc_, "type error in merge[%u] (expected %s, got %s)",
                     i, ValueTypes::TypeName(old.type),
                     ValueTypes::TypeName(val.type));
        return false;
2846
      }
2847
      val.type = old.type;
2848 2849 2850 2851 2852 2853 2854 2855
    }

    return true;
  }

  bool TypeCheckFallThru(Control* c) {
    DCHECK_EQ(c, &control_.back());
    if (!validate) return true;
2856
    uint32_t expected = c->end_merge.arity;
2857 2858
    DCHECK_GE(stack_.size(), c->stack_depth);
    uint32_t actual = static_cast<uint32_t>(stack_.size()) - c->stack_depth;
2859 2860
    // Fallthrus must match the arity of the control exactly.
    if (!InsertUnreachablesIfNecessary(expected, actual) || actual > expected) {
2861 2862 2863 2864
      this->errorf(
          this->pc_,
          "expected %u elements on the stack for fallthru to @%d, found %u",
          expected, startrel(c->pc), actual);
2865 2866
      return false;
    }
2867
    if (expected == 0) return true;  // Fast path.
2868

2869
    return TypeCheckMergeValues(c, &c->end_merge);
2870 2871
  }

2872 2873
  bool TypeCheckBranch(Control* c) {
    // Branches must have at least the number of values expected; can have more.
2874
    uint32_t expected = c->br_merge()->arity;
2875
    if (expected == 0) return true;  // Fast path.
2876 2877 2878
    DCHECK_GE(stack_.size(), control_.back().stack_depth);
    uint32_t actual =
        static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth;
2879
    if (!InsertUnreachablesIfNecessary(expected, actual)) {
2880 2881 2882
      this->errorf(this->pc_,
                   "expected %u elements on the stack for br to @%d, found %u",
                   expected, startrel(c->pc), actual);
2883 2884
      return false;
    }
2885
    return TypeCheckMergeValues(c, c->br_merge());
2886 2887
  }

2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
  bool TypeCheckReturn() {
    // Returns must have at least the number of values expected; can have more.
    uint32_t num_returns = static_cast<uint32_t>(this->sig_->return_count());
    DCHECK_GE(stack_.size(), control_.back().stack_depth);
    uint32_t actual =
        static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth;
    if (!InsertUnreachablesIfNecessary(num_returns, actual)) {
      this->errorf(this->pc_,
                   "expected %u elements on the stack for return, found %u",
                   num_returns, actual);
      return false;
    }

    // Typecheck the topmost {num_returns} values on the stack.
2902 2903
    if (num_returns == 0) return true;
    // This line requires num_returns > 0.
2904 2905 2906 2907
    Value* stack_values = &*(stack_.end() - num_returns);
    for (uint32_t i = 0; i < num_returns; ++i) {
      auto& val = stack_values[i];
      ValueType expected_type = this->sig_->GetReturn(i);
2908
      if (ValueTypes::IsSubType(expected_type, val.type)) continue;
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
      // If {val.type} is polymorphic, which results from unreachable,
      // make it more specific by using the return's expected type.
      // If it is not polymorphic, this is a type error.
      if (!VALIDATE(val.type == kWasmVar)) {
        this->errorf(this->pc_,
                     "type error in return[%u] (expected %s, got %s)", i,
                     ValueTypes::TypeName(expected_type),
                     ValueTypes::TypeName(val.type));
        return false;
      }
      val.type = expected_type;
    }
    return true;
  }

2924 2925
  inline bool InsertUnreachablesIfNecessary(uint32_t expected,
                                            uint32_t actual) {
2926 2927
    if (V8_LIKELY(actual >= expected)) {
      return true;  // enough actual values are there.
2928
    }
2929
    if (!VALIDATE(control_.back().unreachable())) {
2930 2931 2932 2933 2934 2935 2936 2937
      // There aren't enough values on the stack.
      return false;
    }
    // A slow path. When the actual number of values on the stack is less
    // than the expected number of values and the current control is
    // unreachable, insert unreachable values below the actual values.
    // This simplifies {TypeCheckMergeValues}.
    auto pos = stack_.begin() + (stack_.size() - actual);
2938
    stack_.insert(pos, expected - actual, UnreachableValue(this->pc_));
2939
    return true;
2940 2941
  }

2942
  void onFirstError() override {
2943
    this->end_ = this->pc_;  // Terminate decoding loop.
2944
    TRACE(" !%s\n", this->error_.message().c_str());
2945
    CALL_INTERFACE(OnFirstError);
2946 2947
  }

2948
  void BuildSimplePrototypeOperator(WasmOpcode opcode) {
2949 2950 2951
    if (WasmOpcodes::IsSignExtensionOpcode(opcode)) {
      RET_ON_PROTOTYPE_OPCODE(se);
    }
2952 2953 2954
    if (WasmOpcodes::IsAnyRefOpcode(opcode)) {
      RET_ON_PROTOTYPE_OPCODE(anyref);
    }
2955 2956 2957
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
    BuildSimpleOperator(opcode, sig);
  }
2958

2959
  void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) {
2960 2961 2962 2963 2964
    switch (sig->parameter_count()) {
      case 1: {
        auto val = Pop(0, sig->GetParam(0));
        auto* ret =
            sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
2965
        CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, val, ret);
2966 2967 2968 2969 2970 2971 2972
        break;
      }
      case 2: {
        auto rval = Pop(1, sig->GetParam(1));
        auto lval = Pop(0, sig->GetParam(0));
        auto* ret =
            sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
2973
        CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, lval, rval, ret);
2974 2975 2976 2977 2978 2979
        break;
      }
      default:
        UNREACHABLE();
    }
  }
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001

  void BuildSimpleOperator(WasmOpcode opcode, ValueType return_type,
                           ValueType arg_type) {
    auto val = Pop(0, arg_type);
    auto* ret = return_type == kWasmStmt ? nullptr : Push(return_type);
    CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, val, ret);
  }

  void BuildSimpleOperator(WasmOpcode opcode, ValueType return_type,
                           ValueType lhs_type, ValueType rhs_type) {
    auto rval = Pop(1, rhs_type);
    auto lval = Pop(0, lhs_type);
    auto* ret = return_type == kWasmStmt ? nullptr : Push(return_type);
    CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, lval, rval, ret);
  }

#define DEFINE_SIMPLE_SIG_OPERATOR(sig, ...)          \
  void BuildSimpleOperator_##sig(WasmOpcode opcode) { \
    BuildSimpleOperator(opcode, __VA_ARGS__);         \
  }
  FOREACH_SIGNATURE(DEFINE_SIMPLE_SIG_OPERATOR)
#undef DEFINE_SIMPLE_SIG_OPERATOR
3002 3003
};

3004 3005 3006 3007
#undef CALL_INTERFACE
#undef CALL_INTERFACE_IF_REACHABLE
#undef CALL_INTERFACE_IF_PARENT_REACHABLE

3008
class EmptyInterface {
3009
 public:
3010
  static constexpr Decoder::ValidateFlag validate = Decoder::kValidate;
3011 3012
  using Value = ValueBase;
  using Control = ControlBase<Value>;
3013
  using FullDecoder = WasmFullDecoder<validate, EmptyInterface>;
3014 3015

#define DEFINE_EMPTY_CALLBACK(name, ...) \
3016
  void name(FullDecoder* decoder, ##__VA_ARGS__) {}
3017 3018 3019 3020
  INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK)
#undef DEFINE_EMPTY_CALLBACK
};

3021
#undef TRACE
3022
#undef TRACE_INST_FORMAT
3023 3024
#undef VALIDATE
#undef CHECK_PROTOTYPE_OPCODE
3025
#undef OPCODE_ERROR
3026

3027 3028 3029 3030 3031
}  // namespace wasm
}  // namespace internal
}  // namespace v8

#endif  // V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_