wasm-compiler.cc 165 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#include "src/compiler/wasm-compiler.h"

7 8
#include <memory>

9
#include "src/assembler-inl.h"
10
#include "src/base/optional.h"
11
#include "src/base/platform/elapsed-timer.h"
12
#include "src/base/platform/platform.h"
13
#include "src/builtins/builtins.h"
14
#include "src/code-factory.h"
15 16
#include "src/compiler/access-builder.h"
#include "src/compiler/common-operator.h"
17
#include "src/compiler/compiler-source-position-table.h"
18 19
#include "src/compiler/diamond.h"
#include "src/compiler/graph-visualizer.h"
20
#include "src/compiler/graph.h"
21
#include "src/compiler/instruction-selector.h"
22
#include "src/compiler/int64-lowering.h"
23 24 25 26 27 28
#include "src/compiler/js-graph.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/linkage.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/pipeline.h"
29
#include "src/compiler/simd-scalar-lowering.h"
30
#include "src/compiler/zone-stats.h"
31
#include "src/factory.h"
32
#include "src/isolate-inl.h"
33
#include "src/log-inl.h"
34
#include "src/wasm/function-body-decoder.h"
35
#include "src/wasm/wasm-limits.h"
36
#include "src/wasm/wasm-module.h"
37
#include "src/wasm/wasm-objects-inl.h"
38
#include "src/wasm/wasm-opcodes.h"
39
#include "src/wasm/wasm-text.h"
40

41 42 43 44
namespace v8 {
namespace internal {
namespace compiler {

45 46 47 48 49 50 51
// TODO(titzer): pull WASM_64 up to a common header.
#if !V8_TARGET_ARCH_32_BIT || V8_TARGET_ARCH_X64
#define WASM_64 1
#else
#define WASM_64 0
#endif

52 53 54 55
#define FATAL_UNSUPPORTED_OPCODE(opcode)                              \
  V8_Fatal(__FILE__, __LINE__, "Unsupported opcode #%d:%s", (opcode), \
           wasm::WasmOpcodes::OpcodeName(opcode));

56 57 58 59 60 61 62 63 64 65 66 67 68
namespace {

void MergeControlToEnd(JSGraph* jsgraph, Node* node) {
  Graph* g = jsgraph->graph();
  if (g->end()) {
    NodeProperties::MergeControlToEnd(g, jsgraph->common(), node);
  } else {
    g->SetEnd(g->NewNode(jsgraph->common()->End(1), node));
  }
}

}  // namespace

69
WasmGraphBuilder::WasmGraphBuilder(
70 71
    ModuleEnv* env, Zone* zone, JSGraph* jsgraph, Handle<Code> centry_stub,
    wasm::FunctionSig* sig,
72 73
    compiler::SourcePositionTable* source_position_table,
    RuntimeExceptionSupport exception_support)
74 75
    : zone_(zone),
      jsgraph_(jsgraph),
76
      centry_stub_node_(jsgraph_->HeapConstant(centry_stub)),
77
      env_(env),
78
      signature_tables_(zone),
79
      function_tables_(zone),
80
      function_table_sizes_(zone),
81 82
      cur_buffer_(def_buffer_),
      cur_bufsize_(kDefaultBufferSize),
83
      runtime_exception_support_(exception_support),
84
      sig_(sig),
85
      source_position_table_(source_position_table) {
86 87
  for (size_t i = sig->parameter_count(); i > 0 && !has_simd_; --i) {
    if (sig->GetParam(i - 1) == wasm::kWasmS128) has_simd_ = true;
88
  }
89 90
  for (size_t i = sig->return_count(); i > 0 && !has_simd_; --i) {
    if (sig->GetReturn(i - 1) == wasm::kWasmS128) has_simd_ = true;
91
  }
92 93 94 95 96 97 98 99 100 101 102
  DCHECK_NOT_NULL(jsgraph_);
}

Node* WasmGraphBuilder::Error() { return jsgraph()->Dead(); }

Node* WasmGraphBuilder::Start(unsigned params) {
  Node* start = graph()->NewNode(jsgraph()->common()->Start(params));
  graph()->SetStart(start);
  return start;
}

103
Node* WasmGraphBuilder::Param(unsigned index) {
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  return graph()->NewNode(jsgraph()->common()->Parameter(index),
                          graph()->start());
}

Node* WasmGraphBuilder::Loop(Node* entry) {
  return graph()->NewNode(jsgraph()->common()->Loop(1), entry);
}

Node* WasmGraphBuilder::Terminate(Node* effect, Node* control) {
  Node* terminate =
      graph()->NewNode(jsgraph()->common()->Terminate(), effect, control);
  MergeControlToEnd(jsgraph(), terminate);
  return terminate;
}

unsigned WasmGraphBuilder::InputCount(Node* node) {
  return static_cast<unsigned>(node->InputCount());
}

bool WasmGraphBuilder::IsPhiWithMerge(Node* phi, Node* merge) {
  return phi && IrOpcode::IsPhiOpcode(phi->opcode()) &&
         NodeProperties::GetControlInput(phi) == merge;
}

128 129 130 131 132 133 134 135 136 137 138 139 140
bool WasmGraphBuilder::ThrowsException(Node* node, Node** if_success,
                                       Node** if_exception) {
  if (node->op()->HasProperty(compiler::Operator::kNoThrow)) {
    return false;
  }

  *if_success = graph()->NewNode(jsgraph()->common()->IfSuccess(), node);
  *if_exception =
      graph()->NewNode(jsgraph()->common()->IfException(), node, node);

  return true;
}

141 142 143 144 145 146 147 148
void WasmGraphBuilder::AppendToMerge(Node* merge, Node* from) {
  DCHECK(IrOpcode::IsMergeOpcode(merge->opcode()));
  merge->AppendInput(jsgraph()->zone(), from);
  int new_size = merge->InputCount();
  NodeProperties::ChangeOp(
      merge, jsgraph()->common()->ResizeMergeOrPhi(merge->op(), new_size));
}

149
void WasmGraphBuilder::AppendToPhi(Node* phi, Node* from) {
150 151 152 153 154 155 156 157 158 159 160
  DCHECK(IrOpcode::IsPhiOpcode(phi->opcode()));
  int new_size = phi->InputCount();
  phi->InsertInput(jsgraph()->zone(), phi->InputCount() - 1, from);
  NodeProperties::ChangeOp(
      phi, jsgraph()->common()->ResizeMergeOrPhi(phi->op(), new_size));
}

Node* WasmGraphBuilder::Merge(unsigned count, Node** controls) {
  return graph()->NewNode(jsgraph()->common()->Merge(count), count, controls);
}

161
Node* WasmGraphBuilder::Phi(wasm::ValueType type, unsigned count, Node** vals,
162 163
                            Node* control) {
  DCHECK(IrOpcode::IsMergeOpcode(control->opcode()));
164
  Node** buf = Realloc(vals, count, count + 1);
165 166 167 168 169 170 171 172
  buf[count] = control;
  return graph()->NewNode(jsgraph()->common()->Phi(type, count), count + 1,
                          buf);
}

Node* WasmGraphBuilder::EffectPhi(unsigned count, Node** effects,
                                  Node* control) {
  DCHECK(IrOpcode::IsMergeOpcode(control->opcode()));
173
  Node** buf = Realloc(effects, count, count + 1);
174 175 176 177 178
  buf[count] = control;
  return graph()->NewNode(jsgraph()->common()->EffectPhi(count), count + 1,
                          buf);
}

179 180 181
Node* WasmGraphBuilder::NumberConstant(int32_t value) {
  return jsgraph()->Constant(value);
}
182

183 184 185 186
Node* WasmGraphBuilder::Uint32Constant(uint32_t value) {
  return jsgraph()->Uint32Constant(value);
}

187 188 189 190 191 192 193 194
Node* WasmGraphBuilder::Int32Constant(int32_t value) {
  return jsgraph()->Int32Constant(value);
}

Node* WasmGraphBuilder::Int64Constant(int64_t value) {
  return jsgraph()->Int64Constant(value);
}

195 196
void WasmGraphBuilder::StackCheck(wasm::WasmCodePosition position,
                                  Node** effect, Node** control) {
197
  // TODO(mtrofin): "!env_" happens when we generate a wrapper.
198
  // We should factor wrappers separately from wasm codegen.
199
  if (FLAG_wasm_no_stack_checks || !env_ || !runtime_exception_support_) {
200
    return;
201
  }
202 203 204 205 206 207 208 209
  if (effect == nullptr) effect = effect_;
  if (control == nullptr) control = control_;

  Node* limit = graph()->NewNode(
      jsgraph()->machine()->Load(MachineType::Pointer()),
      jsgraph()->ExternalConstant(
          ExternalReference::address_of_stack_limit(jsgraph()->isolate())),
      jsgraph()->IntPtrConstant(0), *effect, *control);
210
  *effect = limit;
211 212 213 214
  Node* pointer = graph()->NewNode(jsgraph()->machine()->LoadStackPointer());

  Node* check =
      graph()->NewNode(jsgraph()->machine()->UintLessThan(), limit, pointer);
215

216 217
  Diamond stack_check(graph(), jsgraph()->common(), check, BranchHint::kTrue);
  stack_check.Chain(*control);
218

219
  Handle<Code> code = BUILTIN_CODE(jsgraph()->isolate(), WasmStackGuard);
220
  CallInterfaceDescriptor idesc =
221
      WasmRuntimeCallDescriptor(jsgraph()->isolate());
222 223
  CallDescriptor* desc = Linkage::GetStubCallDescriptor(
      jsgraph()->isolate(), jsgraph()->zone(), idesc, 0,
224 225
      CallDescriptor::kNoFlags, Operator::kNoProperties,
      MachineType::AnyTagged(), 1, Linkage::kNoContext);
226
  Node* stub_code = jsgraph()->HeapConstant(code);
227

228
  Node* call = graph()->NewNode(jsgraph()->common()->Call(desc), stub_code,
229
                                *effect, stack_check.if_false);
230

231
  SetSourcePosition(call, position);
232

233
  Node* ephi = graph()->NewNode(jsgraph()->common()->EffectPhi(2), *effect,
234 235 236 237
                                call, stack_check.merge);

  *control = stack_check.merge;
  *effect = ephi;
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
void WasmGraphBuilder::PatchInStackCheckIfNeeded() {
  if (!needs_stack_check_) return;

  Node* start = graph()->start();
  // Place a stack check which uses a dummy node as control and effect.
  Node* dummy = graph()->NewNode(jsgraph()->common()->Dead());
  Node* control = dummy;
  Node* effect = dummy;
  // The function-prologue stack check is associated with position 0, which
  // is never a position of any instruction in the function.
  StackCheck(0, &effect, &control);

  // In testing, no steck checks were emitted. Nothing to rewire then.
  if (effect == dummy) return;

  // Now patch all control uses of {start} to use {control} and all effect uses
  // to use {effect} instead. Then rewire the dummy node to use start instead.
  NodeProperties::ReplaceUses(start, start, effect, control);
  NodeProperties::ReplaceUses(dummy, nullptr, start, start);
}

261 262
Node* WasmGraphBuilder::Binop(wasm::WasmOpcode opcode, Node* left, Node* right,
                              wasm::WasmCodePosition position) {
263 264 265 266 267 268 269 270 271 272 273 274
  const Operator* op;
  MachineOperatorBuilder* m = jsgraph()->machine();
  switch (opcode) {
    case wasm::kExprI32Add:
      op = m->Int32Add();
      break;
    case wasm::kExprI32Sub:
      op = m->Int32Sub();
      break;
    case wasm::kExprI32Mul:
      op = m->Int32Mul();
      break;
275
    case wasm::kExprI32DivS:
276
      return BuildI32DivS(left, right, position);
277
    case wasm::kExprI32DivU:
278
      return BuildI32DivU(left, right, position);
279
    case wasm::kExprI32RemS:
280
      return BuildI32RemS(left, right, position);
281
    case wasm::kExprI32RemU:
282
      return BuildI32RemU(left, right, position);
283 284 285 286 287 288 289 290 291 292 293
    case wasm::kExprI32And:
      op = m->Word32And();
      break;
    case wasm::kExprI32Ior:
      op = m->Word32Or();
      break;
    case wasm::kExprI32Xor:
      op = m->Word32Xor();
      break;
    case wasm::kExprI32Shl:
      op = m->Word32Shl();
294
      right = MaskShiftCount32(right);
295 296 297
      break;
    case wasm::kExprI32ShrU:
      op = m->Word32Shr();
298
      right = MaskShiftCount32(right);
299 300 301
      break;
    case wasm::kExprI32ShrS:
      op = m->Word32Sar();
302
      right = MaskShiftCount32(right);
303
      break;
304 305
    case wasm::kExprI32Ror:
      op = m->Word32Ror();
306
      right = MaskShiftCount32(right);
307 308
      break;
    case wasm::kExprI32Rol:
309
      right = MaskShiftCount32(right);
310
      return BuildI32Rol(left, right);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    case wasm::kExprI32Eq:
      op = m->Word32Equal();
      break;
    case wasm::kExprI32Ne:
      return Invert(Binop(wasm::kExprI32Eq, left, right));
    case wasm::kExprI32LtS:
      op = m->Int32LessThan();
      break;
    case wasm::kExprI32LeS:
      op = m->Int32LessThanOrEqual();
      break;
    case wasm::kExprI32LtU:
      op = m->Uint32LessThan();
      break;
    case wasm::kExprI32LeU:
      op = m->Uint32LessThanOrEqual();
      break;
    case wasm::kExprI32GtS:
      op = m->Int32LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprI32GeS:
      op = m->Int32LessThanOrEqual();
      std::swap(left, right);
      break;
    case wasm::kExprI32GtU:
      op = m->Uint32LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprI32GeU:
      op = m->Uint32LessThanOrEqual();
      std::swap(left, right);
      break;
344 345 346
    case wasm::kExprI64And:
      op = m->Word64And();
      break;
347 348 349
    case wasm::kExprI64Add:
      op = m->Int64Add();
      break;
350 351 352
    case wasm::kExprI64Sub:
      op = m->Int64Sub();
      break;
353 354 355
    case wasm::kExprI64Mul:
      op = m->Int64Mul();
      break;
356
    case wasm::kExprI64DivS:
357
      return BuildI64DivS(left, right, position);
358
    case wasm::kExprI64DivU:
359
      return BuildI64DivU(left, right, position);
360
    case wasm::kExprI64RemS:
361
      return BuildI64RemS(left, right, position);
362
    case wasm::kExprI64RemU:
363
      return BuildI64RemU(left, right, position);
364 365 366
    case wasm::kExprI64Ior:
      op = m->Word64Or();
      break;
367 368 369
    case wasm::kExprI64Xor:
      op = m->Word64Xor();
      break;
370 371
    case wasm::kExprI64Shl:
      op = m->Word64Shl();
372
      right = MaskShiftCount64(right);
373
      break;
374 375
    case wasm::kExprI64ShrU:
      op = m->Word64Shr();
376
      right = MaskShiftCount64(right);
377 378 379
      break;
    case wasm::kExprI64ShrS:
      op = m->Word64Sar();
380
      right = MaskShiftCount64(right);
381
      break;
382 383 384
    case wasm::kExprI64Eq:
      op = m->Word64Equal();
      break;
385 386
    case wasm::kExprI64Ne:
      return Invert(Binop(wasm::kExprI64Eq, left, right));
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    case wasm::kExprI64LtS:
      op = m->Int64LessThan();
      break;
    case wasm::kExprI64LeS:
      op = m->Int64LessThanOrEqual();
      break;
    case wasm::kExprI64LtU:
      op = m->Uint64LessThan();
      break;
    case wasm::kExprI64LeU:
      op = m->Uint64LessThanOrEqual();
      break;
    case wasm::kExprI64GtS:
      op = m->Int64LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprI64GeS:
      op = m->Int64LessThanOrEqual();
      std::swap(left, right);
      break;
    case wasm::kExprI64GtU:
      op = m->Uint64LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprI64GeU:
      op = m->Uint64LessThanOrEqual();
      std::swap(left, right);
      break;
415 416
    case wasm::kExprI64Ror:
      op = m->Word64Ror();
417
      right = MaskShiftCount64(right);
418 419 420
      break;
    case wasm::kExprI64Rol:
      return BuildI64Rol(left, right);
421 422 423 424 425 426 427 428
    case wasm::kExprF32CopySign:
      return BuildF32CopySign(left, right);
    case wasm::kExprF64CopySign:
      return BuildF64CopySign(left, right);
    case wasm::kExprF32Add:
      op = m->Float32Add();
      break;
    case wasm::kExprF32Sub:
429
      op = m->Float32Sub();
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
      break;
    case wasm::kExprF32Mul:
      op = m->Float32Mul();
      break;
    case wasm::kExprF32Div:
      op = m->Float32Div();
      break;
    case wasm::kExprF32Eq:
      op = m->Float32Equal();
      break;
    case wasm::kExprF32Ne:
      return Invert(Binop(wasm::kExprF32Eq, left, right));
    case wasm::kExprF32Lt:
      op = m->Float32LessThan();
      break;
    case wasm::kExprF32Ge:
      op = m->Float32LessThanOrEqual();
      std::swap(left, right);
      break;
    case wasm::kExprF32Gt:
      op = m->Float32LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprF32Le:
      op = m->Float32LessThanOrEqual();
      break;
    case wasm::kExprF64Add:
      op = m->Float64Add();
      break;
    case wasm::kExprF64Sub:
460
      op = m->Float64Sub();
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
      break;
    case wasm::kExprF64Mul:
      op = m->Float64Mul();
      break;
    case wasm::kExprF64Div:
      op = m->Float64Div();
      break;
    case wasm::kExprF64Eq:
      op = m->Float64Equal();
      break;
    case wasm::kExprF64Ne:
      return Invert(Binop(wasm::kExprF64Eq, left, right));
    case wasm::kExprF64Lt:
      op = m->Float64LessThan();
      break;
    case wasm::kExprF64Le:
      op = m->Float64LessThanOrEqual();
      break;
    case wasm::kExprF64Gt:
      op = m->Float64LessThan();
      std::swap(left, right);
      break;
    case wasm::kExprF64Ge:
      op = m->Float64LessThanOrEqual();
      std::swap(left, right);
      break;
487
    case wasm::kExprF32Min:
488 489
      op = m->Float32Min();
      break;
490
    case wasm::kExprF64Min:
491 492
      op = m->Float64Min();
      break;
493
    case wasm::kExprF32Max:
494 495
      op = m->Float32Max();
      break;
496
    case wasm::kExprF64Max:
497 498
      op = m->Float64Max();
      break;
499
    case wasm::kExprF64Pow:
500
      return BuildF64Pow(left, right);
501
    case wasm::kExprF64Atan2:
502 503
      op = m->Float64Atan2();
      break;
504
    case wasm::kExprF64Mod:
505
      return BuildF64Mod(left, right);
506 507 508 509 510 511 512 513
    case wasm::kExprI32AsmjsDivS:
      return BuildI32AsmjsDivS(left, right);
    case wasm::kExprI32AsmjsDivU:
      return BuildI32AsmjsDivU(left, right);
    case wasm::kExprI32AsmjsRemS:
      return BuildI32AsmjsRemS(left, right);
    case wasm::kExprI32AsmjsRemU:
      return BuildI32AsmjsRemU(left, right);
514 515 516 517 518 519 520 521 522 523
    case wasm::kExprI32AsmjsStoreMem8:
      return BuildAsmjsStoreMem(MachineType::Int8(), left, right);
    case wasm::kExprI32AsmjsStoreMem16:
      return BuildAsmjsStoreMem(MachineType::Int16(), left, right);
    case wasm::kExprI32AsmjsStoreMem:
      return BuildAsmjsStoreMem(MachineType::Int32(), left, right);
    case wasm::kExprF32AsmjsStoreMem:
      return BuildAsmjsStoreMem(MachineType::Float32(), left, right);
    case wasm::kExprF64AsmjsStoreMem:
      return BuildAsmjsStoreMem(MachineType::Float64(), left, right);
524
    default:
525
      FATAL_UNSUPPORTED_OPCODE(opcode);
526 527 528 529
  }
  return graph()->NewNode(op, left, right);
}

530 531
Node* WasmGraphBuilder::Unop(wasm::WasmOpcode opcode, Node* input,
                             wasm::WasmCodePosition position) {
532 533 534
  const Operator* op;
  MachineOperatorBuilder* m = jsgraph()->machine();
  switch (opcode) {
535
    case wasm::kExprI32Eqz:
536 537 538 539 540
      op = m->Word32Equal();
      return graph()->NewNode(op, input, jsgraph()->Int32Constant(0));
    case wasm::kExprF32Abs:
      op = m->Float32Abs();
      break;
541
    case wasm::kExprF32Neg: {
542 543
      op = m->Float32Neg();
      break;
544
    }
545 546 547 548 549 550
    case wasm::kExprF32Sqrt:
      op = m->Float32Sqrt();
      break;
    case wasm::kExprF64Abs:
      op = m->Float64Abs();
      break;
551
    case wasm::kExprF64Neg: {
552 553
      op = m->Float64Neg();
      break;
554
    }
555 556 557 558
    case wasm::kExprF64Sqrt:
      op = m->Float64Sqrt();
      break;
    case wasm::kExprI32SConvertF64:
559
      return BuildI32SConvertF64(input, position);
560
    case wasm::kExprI32UConvertF64:
561
      return BuildI32UConvertF64(input, position);
562 563 564 565
    case wasm::kExprI32AsmjsSConvertF64:
      return BuildI32AsmjsSConvertF64(input);
    case wasm::kExprI32AsmjsUConvertF64:
      return BuildI32AsmjsUConvertF64(input);
566 567 568 569 570 571 572 573 574 575
    case wasm::kExprF32ConvertF64:
      op = m->TruncateFloat64ToFloat32();
      break;
    case wasm::kExprF64SConvertI32:
      op = m->ChangeInt32ToFloat64();
      break;
    case wasm::kExprF64UConvertI32:
      op = m->ChangeUint32ToFloat64();
      break;
    case wasm::kExprF32SConvertI32:
576
      op = m->RoundInt32ToFloat32();
577 578
      break;
    case wasm::kExprF32UConvertI32:
579
      op = m->RoundUint32ToFloat32();
580 581
      break;
    case wasm::kExprI32SConvertF32:
582
      return BuildI32SConvertF32(input, position);
583
    case wasm::kExprI32UConvertF32:
584
      return BuildI32UConvertF32(input, position);
585 586 587 588
    case wasm::kExprI32AsmjsSConvertF32:
      return BuildI32AsmjsSConvertF32(input);
    case wasm::kExprI32AsmjsUConvertF32:
      return BuildI32AsmjsUConvertF32(input);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    case wasm::kExprF64ConvertF32:
      op = m->ChangeFloat32ToFloat64();
      break;
    case wasm::kExprF32ReinterpretI32:
      op = m->BitcastInt32ToFloat32();
      break;
    case wasm::kExprI32ReinterpretF32:
      op = m->BitcastFloat32ToInt32();
      break;
    case wasm::kExprI32Clz:
      op = m->Word32Clz();
      break;
    case wasm::kExprI32Ctz: {
      if (m->Word32Ctz().IsSupported()) {
        op = m->Word32Ctz().op();
        break;
605 606 607 608
      } else if (m->Word32ReverseBits().IsSupported()) {
        Node* reversed = graph()->NewNode(m->Word32ReverseBits().op(), input);
        Node* result = graph()->NewNode(m->Word32Clz(), reversed);
        return result;
609 610 611 612 613 614 615 616 617 618 619 620 621
      } else {
        return BuildI32Ctz(input);
      }
    }
    case wasm::kExprI32Popcnt: {
      if (m->Word32Popcnt().IsSupported()) {
        op = m->Word32Popcnt().op();
        break;
      } else {
        return BuildI32Popcnt(input);
      }
    }
    case wasm::kExprF32Floor: {
622 623 624
      if (!m->Float32RoundDown().IsSupported()) return BuildF32Floor(input);
      op = m->Float32RoundDown().op();
      break;
625 626
    }
    case wasm::kExprF32Ceil: {
627 628 629
      if (!m->Float32RoundUp().IsSupported()) return BuildF32Ceil(input);
      op = m->Float32RoundUp().op();
      break;
630 631
    }
    case wasm::kExprF32Trunc: {
632 633
      if (!m->Float32RoundTruncate().IsSupported()) return BuildF32Trunc(input);
      op = m->Float32RoundTruncate().op();
634
      break;
635 636
    }
    case wasm::kExprF32NearestInt: {
637 638 639 640
      if (!m->Float32RoundTiesEven().IsSupported())
        return BuildF32NearestInt(input);
      op = m->Float32RoundTiesEven().op();
      break;
641 642
    }
    case wasm::kExprF64Floor: {
643 644 645
      if (!m->Float64RoundDown().IsSupported()) return BuildF64Floor(input);
      op = m->Float64RoundDown().op();
      break;
646 647
    }
    case wasm::kExprF64Ceil: {
648 649 650
      if (!m->Float64RoundUp().IsSupported()) return BuildF64Ceil(input);
      op = m->Float64RoundUp().op();
      break;
651 652
    }
    case wasm::kExprF64Trunc: {
653 654 655
      if (!m->Float64RoundTruncate().IsSupported()) return BuildF64Trunc(input);
      op = m->Float64RoundTruncate().op();
      break;
656 657
    }
    case wasm::kExprF64NearestInt: {
658 659 660 661
      if (!m->Float64RoundTiesEven().IsSupported())
        return BuildF64NearestInt(input);
      op = m->Float64RoundTiesEven().op();
      break;
662
    }
663 664 665 666 667 668
    case wasm::kExprF64Acos: {
      return BuildF64Acos(input);
    }
    case wasm::kExprF64Asin: {
      return BuildF64Asin(input);
    }
669 670 671
    case wasm::kExprF64Atan:
      op = m->Float64Atan();
      break;
672
    case wasm::kExprF64Cos: {
673 674
      op = m->Float64Cos();
      break;
675 676
    }
    case wasm::kExprF64Sin: {
677 678
      op = m->Float64Sin();
      break;
679 680
    }
    case wasm::kExprF64Tan: {
681 682
      op = m->Float64Tan();
      break;
683 684
    }
    case wasm::kExprF64Exp: {
685 686
      op = m->Float64Exp();
      break;
687
    }
688 689 690
    case wasm::kExprF64Log:
      op = m->Float64Log();
      break;
691 692 693
    case wasm::kExprI32ConvertI64:
      op = m->TruncateInt64ToInt32();
      break;
694 695 696 697 698 699
    case wasm::kExprI64SConvertI32:
      op = m->ChangeInt32ToInt64();
      break;
    case wasm::kExprI64UConvertI32:
      op = m->ChangeUint32ToUint64();
      break;
700 701 702
    case wasm::kExprF64ReinterpretI64:
      op = m->BitcastInt64ToFloat64();
      break;
703 704 705
    case wasm::kExprI64ReinterpretF64:
      op = m->BitcastFloat64ToInt64();
      break;
706 707 708
    case wasm::kExprI64Clz:
      op = m->Word64Clz();
      break;
709
    case wasm::kExprI64Ctz: {
710 711 712
      OptionalOperator ctz64 = m->Word64Ctz();
      if (ctz64.IsSupported()) {
        op = ctz64.op();
713 714
        break;
      } else if (m->Is32() && m->Word32Ctz().IsSupported()) {
715
        op = ctz64.placeholder();
716 717 718 719 720 721 722 723 724
        break;
      } else if (m->Word64ReverseBits().IsSupported()) {
        Node* reversed = graph()->NewNode(m->Word64ReverseBits().op(), input);
        Node* result = graph()->NewNode(m->Word64Clz(), reversed);
        return result;
      } else {
        return BuildI64Ctz(input);
      }
    }
725
    case wasm::kExprI64Popcnt: {
726 727 728
      OptionalOperator popcnt64 = m->Word64Popcnt();
      if (popcnt64.IsSupported()) {
        op = popcnt64.op();
729
      } else if (m->Is32() && m->Word32Popcnt().IsSupported()) {
730
        op = popcnt64.placeholder();
731 732 733 734 735
      } else {
        return BuildI64Popcnt(input);
      }
      break;
    }
titzer's avatar
titzer committed
736 737 738
    case wasm::kExprI64Eqz:
      op = m->Word64Equal();
      return graph()->NewNode(op, input, jsgraph()->Int64Constant(0));
739
    case wasm::kExprF32SConvertI64:
740
      if (m->Is32()) {
741 742
        return BuildF32SConvertI64(input);
      }
743 744 745
      op = m->RoundInt64ToFloat32();
      break;
    case wasm::kExprF32UConvertI64:
746
      if (m->Is32()) {
747 748
        return BuildF32UConvertI64(input);
      }
749 750 751
      op = m->RoundUint64ToFloat32();
      break;
    case wasm::kExprF64SConvertI64:
752
      if (m->Is32()) {
753 754
        return BuildF64SConvertI64(input);
      }
755 756 757
      op = m->RoundInt64ToFloat64();
      break;
    case wasm::kExprF64UConvertI64:
758
      if (m->Is32()) {
759 760
        return BuildF64UConvertI64(input);
      }
761 762
      op = m->RoundUint64ToFloat64();
      break;
763
    case wasm::kExprI64SConvertF32:
764
      return BuildI64SConvertF32(input, position);
765
    case wasm::kExprI64SConvertF64:
766
      return BuildI64SConvertF64(input, position);
767
    case wasm::kExprI64UConvertF32:
768
      return BuildI64UConvertF32(input, position);
769
    case wasm::kExprI64UConvertF64:
770
      return BuildI64UConvertF64(input, position);
771 772 773 774 775 776 777 778 779 780 781 782 783 784
    case wasm::kExprI32AsmjsLoadMem8S:
      return BuildAsmjsLoadMem(MachineType::Int8(), input);
    case wasm::kExprI32AsmjsLoadMem8U:
      return BuildAsmjsLoadMem(MachineType::Uint8(), input);
    case wasm::kExprI32AsmjsLoadMem16S:
      return BuildAsmjsLoadMem(MachineType::Int16(), input);
    case wasm::kExprI32AsmjsLoadMem16U:
      return BuildAsmjsLoadMem(MachineType::Uint16(), input);
    case wasm::kExprI32AsmjsLoadMem:
      return BuildAsmjsLoadMem(MachineType::Int32(), input);
    case wasm::kExprF32AsmjsLoadMem:
      return BuildAsmjsLoadMem(MachineType::Float32(), input);
    case wasm::kExprF64AsmjsLoadMem:
      return BuildAsmjsLoadMem(MachineType::Float64(), input);
785
    default:
786
      FATAL_UNSUPPORTED_OPCODE(opcode);
787 788 789 790 791 792 793 794 795 796 797 798
  }
  return graph()->NewNode(op, input);
}

Node* WasmGraphBuilder::Float32Constant(float value) {
  return jsgraph()->Float32Constant(value);
}

Node* WasmGraphBuilder::Float64Constant(double value) {
  return jsgraph()->Float64Constant(value);
}

799 800
Node* WasmGraphBuilder::HeapConstant(Handle<HeapObject> value) {
  return jsgraph()->HeapConstant(value);
801 802
}

803 804 805
namespace {
Node* Branch(JSGraph* jsgraph, Node* cond, Node** true_node, Node** false_node,
             Node* control, BranchHint hint) {
806
  DCHECK_NOT_NULL(cond);
807
  DCHECK_NOT_NULL(control);
808
  Node* branch =
809 810 811
      jsgraph->graph()->NewNode(jsgraph->common()->Branch(hint), cond, control);
  *true_node = jsgraph->graph()->NewNode(jsgraph->common()->IfTrue(), branch);
  *false_node = jsgraph->graph()->NewNode(jsgraph->common()->IfFalse(), branch);
812 813
  return branch;
}
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
}  // namespace

Node* WasmGraphBuilder::BranchNoHint(Node* cond, Node** true_node,
                                     Node** false_node) {
  return Branch(jsgraph(), cond, true_node, false_node, *control_,
                BranchHint::kNone);
}

Node* WasmGraphBuilder::BranchExpectTrue(Node* cond, Node** true_node,
                                         Node** false_node) {
  return Branch(jsgraph(), cond, true_node, false_node, *control_,
                BranchHint::kTrue);
}

Node* WasmGraphBuilder::BranchExpectFalse(Node* cond, Node** true_node,
                                          Node** false_node) {
  return Branch(jsgraph(), cond, true_node, false_node, *control_,
                BranchHint::kFalse);
}
833

834
Builtins::Name WasmGraphBuilder::GetBuiltinIdForTrap(wasm::TrapReason reason) {
835
  if (runtime_exception_support_ == kNoRuntimeExceptionSupport) {
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    // We use Builtins::builtin_count as a marker to tell the code generator
    // to generate a call to a testing c-function instead of a runtime
    // function. This code should only be called from a cctest.
    return Builtins::builtin_count;
  }

  switch (reason) {
#define TRAPREASON_TO_MESSAGE(name) \
  case wasm::k##name:               \
    return Builtins::kThrowWasm##name;
    FOREACH_WASM_TRAPREASON(TRAPREASON_TO_MESSAGE)
#undef TRAPREASON_TO_MESSAGE
    default:
      UNREACHABLE();
  }
}

Node* WasmGraphBuilder::TrapIfTrue(wasm::TrapReason reason, Node* cond,
                                   wasm::WasmCodePosition position) {
855
  Builtins::Name trap_id = GetBuiltinIdForTrap(reason);
856 857 858 859 860 861 862 863 864
  Node* node = graph()->NewNode(jsgraph()->common()->TrapIf(trap_id), cond,
                                Effect(), Control());
  *control_ = node;
  SetSourcePosition(node, position);
  return node;
}

Node* WasmGraphBuilder::TrapIfFalse(wasm::TrapReason reason, Node* cond,
                                    wasm::WasmCodePosition position) {
865
  Builtins::Name trap_id = GetBuiltinIdForTrap(reason);
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913

  Node* node = graph()->NewNode(jsgraph()->common()->TrapUnless(trap_id), cond,
                                Effect(), Control());
  *control_ = node;
  SetSourcePosition(node, position);
  return node;
}

// Add a check that traps if {node} is equal to {val}.
Node* WasmGraphBuilder::TrapIfEq32(wasm::TrapReason reason, Node* node,
                                   int32_t val,
                                   wasm::WasmCodePosition position) {
  Int32Matcher m(node);
  if (m.HasValue() && !m.Is(val)) return graph()->start();
  if (val == 0) {
    return TrapIfFalse(reason, node, position);
  } else {
    return TrapIfTrue(reason,
                      graph()->NewNode(jsgraph()->machine()->Word32Equal(),
                                       node, jsgraph()->Int32Constant(val)),
                      position);
  }
}

// Add a check that traps if {node} is zero.
Node* WasmGraphBuilder::ZeroCheck32(wasm::TrapReason reason, Node* node,
                                    wasm::WasmCodePosition position) {
  return TrapIfEq32(reason, node, 0, position);
}

// Add a check that traps if {node} is equal to {val}.
Node* WasmGraphBuilder::TrapIfEq64(wasm::TrapReason reason, Node* node,
                                   int64_t val,
                                   wasm::WasmCodePosition position) {
  Int64Matcher m(node);
  if (m.HasValue() && !m.Is(val)) return graph()->start();
  return TrapIfTrue(reason,
                    graph()->NewNode(jsgraph()->machine()->Word64Equal(), node,
                                     jsgraph()->Int64Constant(val)),
                    position);
}

// Add a check that traps if {node} is zero.
Node* WasmGraphBuilder::ZeroCheck64(wasm::TrapReason reason, Node* node,
                                    wasm::WasmCodePosition position) {
  return TrapIfEq64(reason, node, 0, position);
}

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
Node* WasmGraphBuilder::Switch(unsigned count, Node* key) {
  return graph()->NewNode(jsgraph()->common()->Switch(count), key, *control_);
}

Node* WasmGraphBuilder::IfValue(int32_t value, Node* sw) {
  DCHECK_EQ(IrOpcode::kSwitch, sw->opcode());
  return graph()->NewNode(jsgraph()->common()->IfValue(value), sw);
}

Node* WasmGraphBuilder::IfDefault(Node* sw) {
  DCHECK_EQ(IrOpcode::kSwitch, sw->opcode());
  return graph()->NewNode(jsgraph()->common()->IfDefault(), sw);
}

Node* WasmGraphBuilder::Return(unsigned count, Node** vals) {
  DCHECK_NOT_NULL(*control_);
  DCHECK_NOT_NULL(*effect_);

932 933 934 935 936 937 938 939 940 941
  static const int kStackAllocatedNodeBufferSize = 8;
  Node* stack_buffer[kStackAllocatedNodeBufferSize];
  std::vector<Node*> heap_buffer;

  Node** buf = stack_buffer;
  if (count + 3 > kStackAllocatedNodeBufferSize) {
    heap_buffer.resize(count + 3);
    buf = heap_buffer.data();
  }

942
  buf[0] = jsgraph()->Int32Constant(0);
943
  memcpy(buf + 1, vals, sizeof(void*) * count);
944 945
  buf[count + 1] = *effect_;
  buf[count + 2] = *control_;
946
  Node* ret =
947
      graph()->NewNode(jsgraph()->common()->Return(count), count + 3, buf);
948 949 950 951 952

  MergeControlToEnd(jsgraph(), ret);
  return ret;
}

953
Node* WasmGraphBuilder::ReturnVoid() { return Return(0, nullptr); }
954

955
Node* WasmGraphBuilder::Unreachable(wasm::WasmCodePosition position) {
956
  TrapIfFalse(wasm::TrapReason::kTrapUnreachable, Int32Constant(0), position);
957
  ReturnVoid();
958 959 960
  return nullptr;
}

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
Node* WasmGraphBuilder::MaskShiftCount32(Node* node) {
  static const int32_t kMask32 = 0x1f;
  if (!jsgraph()->machine()->Word32ShiftIsSafe()) {
    // Shifts by constants are so common we pattern-match them here.
    Int32Matcher match(node);
    if (match.HasValue()) {
      int32_t masked = (match.Value() & kMask32);
      if (match.Value() != masked) node = jsgraph()->Int32Constant(masked);
    } else {
      node = graph()->NewNode(jsgraph()->machine()->Word32And(), node,
                              jsgraph()->Int32Constant(kMask32));
    }
  }
  return node;
}

Node* WasmGraphBuilder::MaskShiftCount64(Node* node) {
  static const int64_t kMask64 = 0x3f;
  if (!jsgraph()->machine()->Word32ShiftIsSafe()) {
    // Shifts by constants are so common we pattern-match them here.
    Int64Matcher match(node);
    if (match.HasValue()) {
      int64_t masked = (match.Value() & kMask64);
      if (match.Value() != masked) node = jsgraph()->Int64Constant(masked);
    } else {
      node = graph()->NewNode(jsgraph()->machine()->Word64And(), node,
                              jsgraph()->Int64Constant(kMask64));
    }
  }
  return node;
}
992

993 994 995 996
static bool ReverseBytesSupported(MachineOperatorBuilder* m,
                                  size_t size_in_bytes) {
  switch (size_in_bytes) {
    case 4:
997
    case 16:
998 999 1000 1001 1002 1003 1004 1005 1006
      return m->Word32ReverseBytes().IsSupported();
    case 8:
      return m->Word64ReverseBytes().IsSupported();
    default:
      break;
  }
  return false;
}

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
Node* WasmGraphBuilder::BuildChangeEndiannessStore(Node* node,
                                                   MachineType memtype,
                                                   wasm::ValueType wasmtype) {
  Node* result;
  Node* value = node;
  MachineOperatorBuilder* m = jsgraph()->machine();
  int valueSizeInBytes = 1 << ElementSizeLog2Of(wasmtype);
  int valueSizeInBits = 8 * valueSizeInBytes;
  bool isFloat = false;

  switch (wasmtype) {
    case wasm::kWasmF64:
      value = graph()->NewNode(m->BitcastFloat64ToInt64(), node);
      isFloat = true;
    case wasm::kWasmI64:
      result = jsgraph()->Int64Constant(0);
      break;
    case wasm::kWasmF32:
      value = graph()->NewNode(m->BitcastFloat32ToInt32(), node);
      isFloat = true;
    case wasm::kWasmI32:
      result = jsgraph()->Int32Constant(0);
      break;
    case wasm::kWasmS128:
      DCHECK(ReverseBytesSupported(m, valueSizeInBytes));
      break;
    default:
      UNREACHABLE();
      break;
  }

  if (memtype.representation() == MachineRepresentation::kWord8) {
    // No need to change endianness for byte size, return original node
    return node;
  }
  if (wasmtype == wasm::kWasmI64 &&
      memtype.representation() < MachineRepresentation::kWord64) {
    // In case we store lower part of WasmI64 expression, we can truncate
    // upper 32bits
    value = graph()->NewNode(m->TruncateInt64ToInt32(), value);
    valueSizeInBytes = 1 << ElementSizeLog2Of(wasm::kWasmI32);
    valueSizeInBits = 8 * valueSizeInBytes;
    if (memtype.representation() == MachineRepresentation::kWord16) {
      value =
          graph()->NewNode(m->Word32Shl(), value, jsgraph()->Int32Constant(16));
    }
  } else if (wasmtype == wasm::kWasmI32 &&
             memtype.representation() == MachineRepresentation::kWord16) {
    value =
        graph()->NewNode(m->Word32Shl(), value, jsgraph()->Int32Constant(16));
  }

  int i;
  uint32_t shiftCount;

  if (ReverseBytesSupported(m, valueSizeInBytes)) {
    switch (valueSizeInBytes) {
      case 4:
        result = graph()->NewNode(m->Word32ReverseBytes().op(), value);
        break;
      case 8:
        result = graph()->NewNode(m->Word64ReverseBytes().op(), value);
        break;
      case 16: {
        Node* byte_reversed_lanes[4];
        for (int lane = 0; lane < 4; lane++) {
          byte_reversed_lanes[lane] = graph()->NewNode(
              m->Word32ReverseBytes().op(),
              graph()->NewNode(jsgraph()->machine()->I32x4ExtractLane(lane),
                               value));
        }

        // This is making a copy of the value.
        result =
            graph()->NewNode(jsgraph()->machine()->S128And(), value, value);

        for (int lane = 0; lane < 4; lane++) {
          result =
              graph()->NewNode(jsgraph()->machine()->I32x4ReplaceLane(3 - lane),
                               result, byte_reversed_lanes[lane]);
        }

        break;
      }
      default:
        UNREACHABLE();
        break;
    }
  } else {
    for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2;
         i += 8, shiftCount -= 16) {
      Node* shiftLower;
      Node* shiftHigher;
      Node* lowerByte;
      Node* higherByte;

1103 1104
      DCHECK_LT(0, shiftCount);
      DCHECK_EQ(0, (shiftCount + 8) % 16);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

      if (valueSizeInBits > 32) {
        shiftLower = graph()->NewNode(m->Word64Shl(), value,
                                      jsgraph()->Int64Constant(shiftCount));
        shiftHigher = graph()->NewNode(m->Word64Shr(), value,
                                       jsgraph()->Int64Constant(shiftCount));
        lowerByte = graph()->NewNode(
            m->Word64And(), shiftLower,
            jsgraph()->Int64Constant(static_cast<uint64_t>(0xFF)
                                     << (valueSizeInBits - 8 - i)));
        higherByte = graph()->NewNode(
            m->Word64And(), shiftHigher,
            jsgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i));
        result = graph()->NewNode(m->Word64Or(), result, lowerByte);
        result = graph()->NewNode(m->Word64Or(), result, higherByte);
      } else {
        shiftLower = graph()->NewNode(m->Word32Shl(), value,
                                      jsgraph()->Int32Constant(shiftCount));
        shiftHigher = graph()->NewNode(m->Word32Shr(), value,
                                       jsgraph()->Int32Constant(shiftCount));
        lowerByte = graph()->NewNode(
            m->Word32And(), shiftLower,
            jsgraph()->Int32Constant(static_cast<uint32_t>(0xFF)
                                     << (valueSizeInBits - 8 - i)));
        higherByte = graph()->NewNode(
            m->Word32And(), shiftHigher,
            jsgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i));
        result = graph()->NewNode(m->Word32Or(), result, lowerByte);
        result = graph()->NewNode(m->Word32Or(), result, higherByte);
      }
    }
  }

  if (isFloat) {
    switch (wasmtype) {
      case wasm::kWasmF64:
        result = graph()->NewNode(m->BitcastInt64ToFloat64(), result);
        break;
      case wasm::kWasmF32:
        result = graph()->NewNode(m->BitcastInt32ToFloat32(), result);
        break;
      default:
        UNREACHABLE();
        break;
    }
  }

  return result;
}

Node* WasmGraphBuilder::BuildChangeEndiannessLoad(Node* node,
                                                  MachineType memtype,
                                                  wasm::ValueType wasmtype) {
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  Node* result;
  Node* value = node;
  MachineOperatorBuilder* m = jsgraph()->machine();
  int valueSizeInBytes = 1 << ElementSizeLog2Of(memtype.representation());
  int valueSizeInBits = 8 * valueSizeInBytes;
  bool isFloat = false;

  switch (memtype.representation()) {
    case MachineRepresentation::kFloat64:
      value = graph()->NewNode(m->BitcastFloat64ToInt64(), node);
      isFloat = true;
    case MachineRepresentation::kWord64:
      result = jsgraph()->Int64Constant(0);
      break;
    case MachineRepresentation::kFloat32:
      value = graph()->NewNode(m->BitcastFloat32ToInt32(), node);
      isFloat = true;
    case MachineRepresentation::kWord32:
    case MachineRepresentation::kWord16:
      result = jsgraph()->Int32Constant(0);
      break;
    case MachineRepresentation::kWord8:
      // No need to change endianness for byte size, return original node
      return node;
      break;
1183 1184 1185
    case MachineRepresentation::kSimd128:
      DCHECK(ReverseBytesSupported(m, valueSizeInBytes));
      break;
1186 1187 1188 1189 1190 1191 1192 1193
    default:
      UNREACHABLE();
      break;
  }

  int i;
  uint32_t shiftCount;

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
  if (ReverseBytesSupported(m, valueSizeInBytes < 4 ? 4 : valueSizeInBytes)) {
    switch (valueSizeInBytes) {
      case 2:
        result =
            graph()->NewNode(m->Word32ReverseBytes().op(),
                             graph()->NewNode(m->Word32Shl(), value,
                                              jsgraph()->Int32Constant(16)));
        break;
      case 4:
        result = graph()->NewNode(m->Word32ReverseBytes().op(), value);
        break;
      case 8:
        result = graph()->NewNode(m->Word64ReverseBytes().op(), value);
        break;
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
      case 16: {
        Node* byte_reversed_lanes[4];
        for (int lane = 0; lane < 4; lane++) {
          byte_reversed_lanes[lane] = graph()->NewNode(
              m->Word32ReverseBytes().op(),
              graph()->NewNode(jsgraph()->machine()->I32x4ExtractLane(lane),
                               value));
        }

        // This is making a copy of the value.
        result =
            graph()->NewNode(jsgraph()->machine()->S128And(), value, value);

        for (int lane = 0; lane < 4; lane++) {
          result =
              graph()->NewNode(jsgraph()->machine()->I32x4ReplaceLane(3 - lane),
                               result, byte_reversed_lanes[lane]);
        }

        break;
      }
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
      default:
        UNREACHABLE();
    }
  } else {
    for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2;
         i += 8, shiftCount -= 16) {
      Node* shiftLower;
      Node* shiftHigher;
      Node* lowerByte;
      Node* higherByte;

1240 1241
      DCHECK_LT(0, shiftCount);
      DCHECK_EQ(0, (shiftCount + 8) % 16);
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

      if (valueSizeInBits > 32) {
        shiftLower = graph()->NewNode(m->Word64Shl(), value,
                                      jsgraph()->Int64Constant(shiftCount));
        shiftHigher = graph()->NewNode(m->Word64Shr(), value,
                                       jsgraph()->Int64Constant(shiftCount));
        lowerByte = graph()->NewNode(
            m->Word64And(), shiftLower,
            jsgraph()->Int64Constant(static_cast<uint64_t>(0xFF)
                                     << (valueSizeInBits - 8 - i)));
        higherByte = graph()->NewNode(
            m->Word64And(), shiftHigher,
            jsgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i));
        result = graph()->NewNode(m->Word64Or(), result, lowerByte);
        result = graph()->NewNode(m->Word64Or(), result, higherByte);
      } else {
        shiftLower = graph()->NewNode(m->Word32Shl(), value,
                                      jsgraph()->Int32Constant(shiftCount));
        shiftHigher = graph()->NewNode(m->Word32Shr(), value,
                                       jsgraph()->Int32Constant(shiftCount));
        lowerByte = graph()->NewNode(
            m->Word32And(), shiftLower,
            jsgraph()->Int32Constant(static_cast<uint32_t>(0xFF)
                                     << (valueSizeInBits - 8 - i)));
        higherByte = graph()->NewNode(
            m->Word32And(), shiftHigher,
            jsgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i));
        result = graph()->NewNode(m->Word32Or(), result, lowerByte);
        result = graph()->NewNode(m->Word32Or(), result, higherByte);
      }
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    }
  }

  if (isFloat) {
    switch (memtype.representation()) {
      case MachineRepresentation::kFloat64:
        result = graph()->NewNode(m->BitcastInt64ToFloat64(), result);
        break;
      case MachineRepresentation::kFloat32:
        result = graph()->NewNode(m->BitcastInt32ToFloat32(), result);
        break;
      default:
        UNREACHABLE();
        break;
    }
  }

  // We need to sign extend the value
  if (memtype.IsSigned()) {
    DCHECK(!isFloat);
    if (valueSizeInBits < 32) {
      Node* shiftBitCount;
      // Perform sign extension using following trick
      // result = (x << machine_width - type_width) >> (machine_width -
      // type_width)
1297
      if (wasmtype == wasm::kWasmI64) {
1298 1299 1300
        shiftBitCount = jsgraph()->Int32Constant(64 - valueSizeInBits);
        result = graph()->NewNode(
            m->Word64Sar(),
1301 1302 1303
            graph()->NewNode(m->Word64Shl(),
                             graph()->NewNode(m->ChangeInt32ToInt64(), result),
                             shiftBitCount),
1304
            shiftBitCount);
1305
      } else if (wasmtype == wasm::kWasmI32) {
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        shiftBitCount = jsgraph()->Int32Constant(32 - valueSizeInBits);
        result = graph()->NewNode(
            m->Word32Sar(),
            graph()->NewNode(m->Word32Shl(), result, shiftBitCount),
            shiftBitCount);
      }
    }
  }

  return result;
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
Node* WasmGraphBuilder::BuildF32CopySign(Node* left, Node* right) {
  Node* result = Unop(
      wasm::kExprF32ReinterpretI32,
      Binop(wasm::kExprI32Ior,
            Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, left),
                  jsgraph()->Int32Constant(0x7fffffff)),
            Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, right),
                  jsgraph()->Int32Constant(0x80000000))));

  return result;
}

Node* WasmGraphBuilder::BuildF64CopySign(Node* left, Node* right) {
#if WASM_64
  Node* result = Unop(
      wasm::kExprF64ReinterpretI64,
      Binop(wasm::kExprI64Ior,
            Binop(wasm::kExprI64And, Unop(wasm::kExprI64ReinterpretF64, left),
                  jsgraph()->Int64Constant(0x7fffffffffffffff)),
            Binop(wasm::kExprI64And, Unop(wasm::kExprI64ReinterpretF64, right),
                  jsgraph()->Int64Constant(0x8000000000000000))));

  return result;
#else
  MachineOperatorBuilder* m = jsgraph()->machine();

  Node* high_word_left = graph()->NewNode(m->Float64ExtractHighWord32(), left);
  Node* high_word_right =
      graph()->NewNode(m->Float64ExtractHighWord32(), right);

  Node* new_high_word =
      Binop(wasm::kExprI32Ior, Binop(wasm::kExprI32And, high_word_left,
                                     jsgraph()->Int32Constant(0x7fffffff)),
            Binop(wasm::kExprI32And, high_word_right,
                  jsgraph()->Int32Constant(0x80000000)));

  return graph()->NewNode(m->Float64InsertHighWord32(), left, new_high_word);
#endif
}

1358 1359
Node* WasmGraphBuilder::BuildI32SConvertF32(Node* input,
                                            wasm::WasmCodePosition position) {
1360 1361 1362
  MachineOperatorBuilder* m = jsgraph()->machine();
  // Truncation of the input value is needed for the overflow check later.
  Node* trunc = Unop(wasm::kExprF32Trunc, input);
1363
  Node* result = graph()->NewNode(m->TruncateFloat32ToInt32(), trunc);
1364 1365 1366

  // Convert the result back to f64. If we end up at a different value than the
  // truncated input value, then there has been an overflow and we trap.
1367 1368
  Node* check = Unop(wasm::kExprF32SConvertI32, result);
  Node* overflow = Binop(wasm::kExprF32Ne, trunc, check);
1369
  TrapIfTrue(wasm::kTrapFloatUnrepresentable, overflow, position);
1370 1371 1372 1373

  return result;
}

1374 1375
Node* WasmGraphBuilder::BuildI32SConvertF64(Node* input,
                                            wasm::WasmCodePosition position) {
1376 1377 1378 1379 1380 1381 1382 1383 1384
  MachineOperatorBuilder* m = jsgraph()->machine();
  // Truncation of the input value is needed for the overflow check later.
  Node* trunc = Unop(wasm::kExprF64Trunc, input);
  Node* result = graph()->NewNode(m->ChangeFloat64ToInt32(), trunc);

  // Convert the result back to f64. If we end up at a different value than the
  // truncated input value, then there has been an overflow and we trap.
  Node* check = Unop(wasm::kExprF64SConvertI32, result);
  Node* overflow = Binop(wasm::kExprF64Ne, trunc, check);
1385
  TrapIfTrue(wasm::kTrapFloatUnrepresentable, overflow, position);
1386 1387 1388 1389

  return result;
}

1390 1391
Node* WasmGraphBuilder::BuildI32UConvertF32(Node* input,
                                            wasm::WasmCodePosition position) {
1392 1393 1394
  MachineOperatorBuilder* m = jsgraph()->machine();
  // Truncation of the input value is needed for the overflow check later.
  Node* trunc = Unop(wasm::kExprF32Trunc, input);
1395
  Node* result = graph()->NewNode(m->TruncateFloat32ToUint32(), trunc);
1396

1397
  // Convert the result back to f32. If we end up at a different value than the
1398
  // truncated input value, then there has been an overflow and we trap.
1399 1400
  Node* check = Unop(wasm::kExprF32UConvertI32, result);
  Node* overflow = Binop(wasm::kExprF32Ne, trunc, check);
1401
  TrapIfTrue(wasm::kTrapFloatUnrepresentable, overflow, position);
1402 1403 1404 1405

  return result;
}

1406 1407
Node* WasmGraphBuilder::BuildI32UConvertF64(Node* input,
                                            wasm::WasmCodePosition position) {
1408 1409 1410
  MachineOperatorBuilder* m = jsgraph()->machine();
  // Truncation of the input value is needed for the overflow check later.
  Node* trunc = Unop(wasm::kExprF64Trunc, input);
1411
  Node* result = graph()->NewNode(m->TruncateFloat64ToUint32(), trunc);
1412 1413 1414 1415 1416

  // Convert the result back to f64. If we end up at a different value than the
  // truncated input value, then there has been an overflow and we trap.
  Node* check = Unop(wasm::kExprF64UConvertI32, result);
  Node* overflow = Binop(wasm::kExprF64Ne, trunc, check);
1417
  TrapIfTrue(wasm::kTrapFloatUnrepresentable, overflow, position);
1418 1419 1420

  return result;
}
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

Node* WasmGraphBuilder::BuildI32AsmjsSConvertF32(Node* input) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js must use the wacky JS semantics.
  input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input);
  return graph()->NewNode(m->TruncateFloat64ToWord32(), input);
}

Node* WasmGraphBuilder::BuildI32AsmjsSConvertF64(Node* input) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js must use the wacky JS semantics.
  return graph()->NewNode(m->TruncateFloat64ToWord32(), input);
}

Node* WasmGraphBuilder::BuildI32AsmjsUConvertF32(Node* input) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js must use the wacky JS semantics.
  input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input);
  return graph()->NewNode(m->TruncateFloat64ToWord32(), input);
}

Node* WasmGraphBuilder::BuildI32AsmjsUConvertF64(Node* input) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js must use the wacky JS semantics.
  return graph()->NewNode(m->TruncateFloat64ToWord32(), input);
}
1447

1448 1449 1450 1451
Node* WasmGraphBuilder::BuildBitCountingCall(Node* input, ExternalReference ref,
                                             MachineRepresentation input_type) {
  Node* stack_slot_param =
      graph()->NewNode(jsgraph()->machine()->StackSlot(input_type));
1452

1453 1454 1455 1456 1457
  const Operator* store_op = jsgraph()->machine()->Store(
      StoreRepresentation(input_type, kNoWriteBarrier));
  *effect_ =
      graph()->NewNode(store_op, stack_slot_param, jsgraph()->Int32Constant(0),
                       input, *effect_, *control_);
1458

1459 1460 1461
  MachineSignature::Builder sig_builder(jsgraph()->zone(), 1, 1);
  sig_builder.AddReturn(MachineType::Int32());
  sig_builder.AddParam(MachineType::Pointer());
1462

1463 1464
  Node* function = graph()->NewNode(jsgraph()->common()->ExternalConstant(ref));
  Node* args[] = {function, stack_slot_param};
1465

1466
  return BuildCCall(sig_builder.Build(), args);
1467 1468
}

1469 1470 1471 1472 1473
Node* WasmGraphBuilder::BuildI32Ctz(Node* input) {
  return BuildBitCountingCall(
      input, ExternalReference::wasm_word32_ctz(jsgraph()->isolate()),
      MachineRepresentation::kWord32);
}
1474 1475

Node* WasmGraphBuilder::BuildI64Ctz(Node* input) {
1476 1477 1478 1479
  return Unop(wasm::kExprI64UConvertI32,
              BuildBitCountingCall(input, ExternalReference::wasm_word64_ctz(
                                              jsgraph()->isolate()),
                                   MachineRepresentation::kWord64));
1480 1481 1482
}

Node* WasmGraphBuilder::BuildI32Popcnt(Node* input) {
1483 1484 1485
  return BuildBitCountingCall(
      input, ExternalReference::wasm_word32_popcnt(jsgraph()->isolate()),
      MachineRepresentation::kWord32);
1486 1487 1488
}

Node* WasmGraphBuilder::BuildI64Popcnt(Node* input) {
1489 1490 1491 1492
  return Unop(wasm::kExprI64UConvertI32,
              BuildBitCountingCall(input, ExternalReference::wasm_word64_popcnt(
                                              jsgraph()->isolate()),
                                   MachineRepresentation::kWord64));
1493 1494
}

1495
Node* WasmGraphBuilder::BuildF32Trunc(Node* input) {
1496 1497
  MachineType type = MachineType::Float32();
  ExternalReference ref =
1498 1499
      ExternalReference::wasm_f32_trunc(jsgraph()->isolate());

1500
  return BuildCFuncInstruction(ref, type, input);
1501 1502 1503 1504 1505
}

Node* WasmGraphBuilder::BuildF32Floor(Node* input) {
  MachineType type = MachineType::Float32();
  ExternalReference ref =
1506
      ExternalReference::wasm_f32_floor(jsgraph()->isolate());
1507
  return BuildCFuncInstruction(ref, type, input);
1508 1509 1510 1511 1512
}

Node* WasmGraphBuilder::BuildF32Ceil(Node* input) {
  MachineType type = MachineType::Float32();
  ExternalReference ref =
1513
      ExternalReference::wasm_f32_ceil(jsgraph()->isolate());
1514
  return BuildCFuncInstruction(ref, type, input);
1515 1516 1517 1518 1519
}

Node* WasmGraphBuilder::BuildF32NearestInt(Node* input) {
  MachineType type = MachineType::Float32();
  ExternalReference ref =
1520
      ExternalReference::wasm_f32_nearest_int(jsgraph()->isolate());
1521
  return BuildCFuncInstruction(ref, type, input);
1522 1523
}

1524
Node* WasmGraphBuilder::BuildF64Trunc(Node* input) {
1525 1526
  MachineType type = MachineType::Float64();
  ExternalReference ref =
1527
      ExternalReference::wasm_f64_trunc(jsgraph()->isolate());
1528
  return BuildCFuncInstruction(ref, type, input);
1529 1530 1531 1532 1533
}

Node* WasmGraphBuilder::BuildF64Floor(Node* input) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
1534
      ExternalReference::wasm_f64_floor(jsgraph()->isolate());
1535
  return BuildCFuncInstruction(ref, type, input);
1536 1537 1538 1539 1540
}

Node* WasmGraphBuilder::BuildF64Ceil(Node* input) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
1541
      ExternalReference::wasm_f64_ceil(jsgraph()->isolate());
1542
  return BuildCFuncInstruction(ref, type, input);
1543 1544 1545 1546 1547
}

Node* WasmGraphBuilder::BuildF64NearestInt(Node* input) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
1548
      ExternalReference::wasm_f64_nearest_int(jsgraph()->isolate());
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  return BuildCFuncInstruction(ref, type, input);
}

Node* WasmGraphBuilder::BuildF64Acos(Node* input) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
      ExternalReference::f64_acos_wrapper_function(jsgraph()->isolate());
  return BuildCFuncInstruction(ref, type, input);
}

Node* WasmGraphBuilder::BuildF64Asin(Node* input) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
      ExternalReference::f64_asin_wrapper_function(jsgraph()->isolate());
  return BuildCFuncInstruction(ref, type, input);
}

1566 1567 1568 1569 1570 1571 1572
Node* WasmGraphBuilder::BuildF64Pow(Node* left, Node* right) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
      ExternalReference::wasm_float64_pow(jsgraph()->isolate());
  return BuildCFuncInstruction(ref, type, left, right);
}

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
Node* WasmGraphBuilder::BuildF64Mod(Node* left, Node* right) {
  MachineType type = MachineType::Float64();
  ExternalReference ref =
      ExternalReference::f64_mod_wrapper_function(jsgraph()->isolate());
  return BuildCFuncInstruction(ref, type, left, right);
}

Node* WasmGraphBuilder::BuildCFuncInstruction(ExternalReference ref,
                                              MachineType type, Node* input0,
                                              Node* input1) {
  // We do truncation by calling a C function which calculates the result.
  // The input is passed to the C function as a double*'s to avoid double
  // parameters. For this we reserve slots on the stack, store the parameters
  // in those slots, pass pointers to the slot to the C function,
  // and after calling the C function we collect the return value from
  // the stack slot.

  Node* stack_slot_param0 =
1591
      graph()->NewNode(jsgraph()->machine()->StackSlot(type.representation()));
1592

1593
  const Operator* store_op0 = jsgraph()->machine()->Store(
1594
      StoreRepresentation(type.representation(), kNoWriteBarrier));
1595 1596 1597
  *effect_ = graph()->NewNode(store_op0, stack_slot_param0,
                              jsgraph()->Int32Constant(0), input0, *effect_,
                              *control_);
1598

1599
  Node* function = graph()->NewNode(jsgraph()->common()->ExternalConstant(ref));
1600
  Node** args = Buffer(5);
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
  args[0] = function;
  args[1] = stack_slot_param0;
  int input_count = 1;

  if (input1 != nullptr) {
    Node* stack_slot_param1 = graph()->NewNode(
        jsgraph()->machine()->StackSlot(type.representation()));
    const Operator* store_op1 = jsgraph()->machine()->Store(
        StoreRepresentation(type.representation(), kNoWriteBarrier));
    *effect_ = graph()->NewNode(store_op1, stack_slot_param1,
                                jsgraph()->Int32Constant(0), input1, *effect_,
                                *control_);
    args[2] = stack_slot_param1;
    ++input_count;
  }
1616

1617 1618 1619 1620 1621 1622
  Signature<MachineType>::Builder sig_builder(jsgraph()->zone(), 0,
                                              input_count);
  sig_builder.AddParam(MachineType::Pointer());
  if (input1 != nullptr) {
    sig_builder.AddParam(MachineType::Pointer());
  }
1623 1624
  BuildCCall(sig_builder.Build(), args);

1625
  const Operator* load_op = jsgraph()->machine()->Load(type);
1626 1627

  Node* load =
1628
      graph()->NewNode(load_op, stack_slot_param0, jsgraph()->Int32Constant(0),
1629 1630 1631 1632 1633
                       *effect_, *control_);
  *effect_ = load;
  return load;
}

1634
Node* WasmGraphBuilder::BuildF32SConvertI64(Node* input) {
1635
  // TODO(titzer/bradnelson): Check handlng of asm.js case.
1636
  return BuildIntToFloatConversionInstruction(
1637 1638 1639 1640
      input, ExternalReference::wasm_int64_to_float32(jsgraph()->isolate()),
      MachineRepresentation::kWord64, MachineType::Float32());
}
Node* WasmGraphBuilder::BuildF32UConvertI64(Node* input) {
1641
  // TODO(titzer/bradnelson): Check handlng of asm.js case.
1642
  return BuildIntToFloatConversionInstruction(
1643 1644 1645 1646
      input, ExternalReference::wasm_uint64_to_float32(jsgraph()->isolate()),
      MachineRepresentation::kWord64, MachineType::Float32());
}
Node* WasmGraphBuilder::BuildF64SConvertI64(Node* input) {
1647
  return BuildIntToFloatConversionInstruction(
1648 1649 1650 1651
      input, ExternalReference::wasm_int64_to_float64(jsgraph()->isolate()),
      MachineRepresentation::kWord64, MachineType::Float64());
}
Node* WasmGraphBuilder::BuildF64UConvertI64(Node* input) {
1652
  return BuildIntToFloatConversionInstruction(
1653 1654 1655
      input, ExternalReference::wasm_uint64_to_float64(jsgraph()->isolate()),
      MachineRepresentation::kWord64, MachineType::Float64());
}
1656 1657

Node* WasmGraphBuilder::BuildIntToFloatConversionInstruction(
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
    Node* input, ExternalReference ref,
    MachineRepresentation parameter_representation,
    const MachineType result_type) {
  Node* stack_slot_param = graph()->NewNode(
      jsgraph()->machine()->StackSlot(parameter_representation));
  Node* stack_slot_result = graph()->NewNode(
      jsgraph()->machine()->StackSlot(result_type.representation()));
  const Operator* store_op = jsgraph()->machine()->Store(
      StoreRepresentation(parameter_representation, kNoWriteBarrier));
  *effect_ =
      graph()->NewNode(store_op, stack_slot_param, jsgraph()->Int32Constant(0),
                       input, *effect_, *control_);
  MachineSignature::Builder sig_builder(jsgraph()->zone(), 0, 2);
  sig_builder.AddParam(MachineType::Pointer());
  sig_builder.AddParam(MachineType::Pointer());
  Node* function = graph()->NewNode(jsgraph()->common()->ExternalConstant(ref));
  Node* args[] = {function, stack_slot_param, stack_slot_result};
  BuildCCall(sig_builder.Build(), args);
  const Operator* load_op = jsgraph()->machine()->Load(result_type);
  Node* load =
      graph()->NewNode(load_op, stack_slot_result, jsgraph()->Int32Constant(0),
                       *effect_, *control_);
1680 1681 1682 1683
  *effect_ = load;
  return load;
}

1684 1685
Node* WasmGraphBuilder::BuildI64SConvertF32(Node* input,
                                            wasm::WasmCodePosition position) {
1686 1687 1688
  if (jsgraph()->machine()->Is32()) {
    return BuildFloatToIntConversionInstruction(
        input, ExternalReference::wasm_float32_to_int64(jsgraph()->isolate()),
1689
        MachineRepresentation::kFloat32, MachineType::Int64(), position);
1690 1691 1692
  } else {
    Node* trunc = graph()->NewNode(
        jsgraph()->machine()->TryTruncateFloat32ToInt64(), input);
1693 1694 1695 1696
    Node* result = graph()->NewNode(jsgraph()->common()->Projection(0), trunc,
                                    graph()->start());
    Node* overflow = graph()->NewNode(jsgraph()->common()->Projection(1), trunc,
                                      graph()->start());
1697
    ZeroCheck64(wasm::kTrapFloatUnrepresentable, overflow, position);
1698 1699 1700 1701
    return result;
  }
}

1702 1703
Node* WasmGraphBuilder::BuildI64UConvertF32(Node* input,
                                            wasm::WasmCodePosition position) {
1704 1705 1706
  if (jsgraph()->machine()->Is32()) {
    return BuildFloatToIntConversionInstruction(
        input, ExternalReference::wasm_float32_to_uint64(jsgraph()->isolate()),
1707
        MachineRepresentation::kFloat32, MachineType::Int64(), position);
1708 1709 1710
  } else {
    Node* trunc = graph()->NewNode(
        jsgraph()->machine()->TryTruncateFloat32ToUint64(), input);
1711 1712 1713 1714
    Node* result = graph()->NewNode(jsgraph()->common()->Projection(0), trunc,
                                    graph()->start());
    Node* overflow = graph()->NewNode(jsgraph()->common()->Projection(1), trunc,
                                      graph()->start());
1715
    ZeroCheck64(wasm::kTrapFloatUnrepresentable, overflow, position);
1716 1717 1718 1719
    return result;
  }
}

1720 1721
Node* WasmGraphBuilder::BuildI64SConvertF64(Node* input,
                                            wasm::WasmCodePosition position) {
1722 1723 1724
  if (jsgraph()->machine()->Is32()) {
    return BuildFloatToIntConversionInstruction(
        input, ExternalReference::wasm_float64_to_int64(jsgraph()->isolate()),
1725
        MachineRepresentation::kFloat64, MachineType::Int64(), position);
1726 1727 1728
  } else {
    Node* trunc = graph()->NewNode(
        jsgraph()->machine()->TryTruncateFloat64ToInt64(), input);
1729 1730 1731 1732
    Node* result = graph()->NewNode(jsgraph()->common()->Projection(0), trunc,
                                    graph()->start());
    Node* overflow = graph()->NewNode(jsgraph()->common()->Projection(1), trunc,
                                      graph()->start());
1733
    ZeroCheck64(wasm::kTrapFloatUnrepresentable, overflow, position);
1734 1735 1736 1737
    return result;
  }
}

1738 1739
Node* WasmGraphBuilder::BuildI64UConvertF64(Node* input,
                                            wasm::WasmCodePosition position) {
1740 1741 1742
  if (jsgraph()->machine()->Is32()) {
    return BuildFloatToIntConversionInstruction(
        input, ExternalReference::wasm_float64_to_uint64(jsgraph()->isolate()),
1743
        MachineRepresentation::kFloat64, MachineType::Int64(), position);
1744 1745 1746
  } else {
    Node* trunc = graph()->NewNode(
        jsgraph()->machine()->TryTruncateFloat64ToUint64(), input);
1747 1748 1749 1750
    Node* result = graph()->NewNode(jsgraph()->common()->Projection(0), trunc,
                                    graph()->start());
    Node* overflow = graph()->NewNode(jsgraph()->common()->Projection(1), trunc,
                                      graph()->start());
1751
    ZeroCheck64(wasm::kTrapFloatUnrepresentable, overflow, position);
1752 1753 1754 1755 1756 1757 1758
    return result;
  }
}

Node* WasmGraphBuilder::BuildFloatToIntConversionInstruction(
    Node* input, ExternalReference ref,
    MachineRepresentation parameter_representation,
1759
    const MachineType result_type, wasm::WasmCodePosition position) {
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
  Node* stack_slot_param = graph()->NewNode(
      jsgraph()->machine()->StackSlot(parameter_representation));
  Node* stack_slot_result = graph()->NewNode(
      jsgraph()->machine()->StackSlot(result_type.representation()));
  const Operator* store_op = jsgraph()->machine()->Store(
      StoreRepresentation(parameter_representation, kNoWriteBarrier));
  *effect_ =
      graph()->NewNode(store_op, stack_slot_param, jsgraph()->Int32Constant(0),
                       input, *effect_, *control_);
  MachineSignature::Builder sig_builder(jsgraph()->zone(), 1, 2);
  sig_builder.AddReturn(MachineType::Int32());
  sig_builder.AddParam(MachineType::Pointer());
  sig_builder.AddParam(MachineType::Pointer());
  Node* function = graph()->NewNode(jsgraph()->common()->ExternalConstant(ref));
  Node* args[] = {function, stack_slot_param, stack_slot_result};
1775 1776
  ZeroCheck32(wasm::kTrapFloatUnrepresentable,
              BuildCCall(sig_builder.Build(), args), position);
1777 1778 1779 1780
  const Operator* load_op = jsgraph()->machine()->Load(result_type);
  Node* load =
      graph()->NewNode(load_op, stack_slot_result, jsgraph()->Int32Constant(0),
                       *effect_, *control_);
1781
  *effect_ = load;
1782 1783 1784
  return load;
}

1785
Node* WasmGraphBuilder::GrowMemory(Node* input) {
1786
  SetNeedsStackCheck();
1787 1788
  Diamond check_input_range(
      graph(), jsgraph()->common(),
1789
      graph()->NewNode(jsgraph()->machine()->Uint32LessThanOrEqual(), input,
1790
                       jsgraph()->Uint32Constant(FLAG_wasm_max_mem_pages)),
1791 1792
      BranchHint::kTrue);

1793 1794
  check_input_range.Chain(*control_);

1795 1796
  Node* parameters[] = {BuildChangeUint32ToSmi(input)};
  Node* old_effect = *effect_;
1797 1798 1799
  *control_ = check_input_range.if_true;
  Node* call = BuildCallToRuntime(Runtime::kWasmGrowMemory, parameters,
                                  arraysize(parameters));
1800 1801 1802 1803 1804

  Node* result = BuildChangeSmiToInt32(call);

  result = check_input_range.Phi(MachineRepresentation::kWord32, result,
                                 jsgraph()->Int32Constant(-1));
1805
  *effect_ = graph()->NewNode(jsgraph()->common()->EffectPhi(2), *effect_,
1806
                              old_effect, check_input_range.merge);
1807 1808
  *control_ = check_input_range.merge;
  return result;
1809 1810
}

1811
Node* WasmGraphBuilder::Throw(Node* input) {
1812
  SetNeedsStackCheck();
1813 1814 1815
  Node* parameters[] = {BuildChangeInt32ToSmi(input)};
  return BuildCallToRuntime(Runtime::kWasmThrow, parameters,
                            arraysize(parameters));
jpp's avatar
jpp committed
1816 1817
}

1818 1819 1820 1821 1822 1823
Node* WasmGraphBuilder::Rethrow() {
  SetNeedsStackCheck();
  Node* result = BuildCallToRuntime(Runtime::kWasmRethrow, nullptr, 0);
  return result;
}

1824
Node* WasmGraphBuilder::Catch(Node* input, wasm::WasmCodePosition position) {
1825
  SetNeedsStackCheck();
1826 1827
  Node* parameters[] = {input};  // caught value
  Node* value = BuildCallToRuntime(Runtime::kWasmSetCaughtExceptionValue,
1828
                                   parameters, arraysize(parameters));
1829 1830 1831 1832
  parameters[0] = value;
  value = BuildCallToRuntime(Runtime::kWasmGetExceptionTag, parameters,
                             arraysize(parameters));
  return BuildChangeSmiToInt32(value);
1833 1834
}

1835 1836
Node* WasmGraphBuilder::BuildI32DivS(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
1837
  MachineOperatorBuilder* m = jsgraph()->machine();
1838
  ZeroCheck32(wasm::kTrapDivByZero, right, position);
1839 1840 1841
  Node* before = *control_;
  Node* denom_is_m1;
  Node* denom_is_not_m1;
1842
  BranchExpectFalse(
1843 1844 1845
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(-1)),
      &denom_is_m1, &denom_is_not_m1);
  *control_ = denom_is_m1;
1846
  TrapIfEq32(wasm::kTrapDivUnrepresentable, left, kMinInt, position);
1847 1848 1849 1850 1851 1852 1853 1854 1855
  if (*control_ != denom_is_m1) {
    *control_ = graph()->NewNode(jsgraph()->common()->Merge(2), denom_is_not_m1,
                                 *control_);
  } else {
    *control_ = before;
  }
  return graph()->NewNode(m->Int32Div(), left, right, *control_);
}

1856 1857
Node* WasmGraphBuilder::BuildI32RemS(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
1858 1859
  MachineOperatorBuilder* m = jsgraph()->machine();

1860
  ZeroCheck32(wasm::kTrapRemByZero, right, position);
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871

  Diamond d(
      graph(), jsgraph()->common(),
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(-1)),
      BranchHint::kFalse);
  d.Chain(*control_);

  return d.Phi(MachineRepresentation::kWord32, jsgraph()->Int32Constant(0),
               graph()->NewNode(m->Int32Mod(), left, right, d.if_false));
}

1872 1873
Node* WasmGraphBuilder::BuildI32DivU(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
1874
  MachineOperatorBuilder* m = jsgraph()->machine();
1875 1876
  return graph()->NewNode(m->Uint32Div(), left, right,
                          ZeroCheck32(wasm::kTrapDivByZero, right, position));
1877 1878
}

1879 1880
Node* WasmGraphBuilder::BuildI32RemU(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
1881
  MachineOperatorBuilder* m = jsgraph()->machine();
1882 1883
  return graph()->NewNode(m->Uint32Mod(), left, right,
                          ZeroCheck32(wasm::kTrapRemByZero, right, position));
1884 1885
}

1886 1887
Node* WasmGraphBuilder::BuildI32AsmjsDivS(Node* left, Node* right) {
  MachineOperatorBuilder* m = jsgraph()->machine();
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899

  Int32Matcher mr(right);
  if (mr.HasValue()) {
    if (mr.Value() == 0) {
      return jsgraph()->Int32Constant(0);
    } else if (mr.Value() == -1) {
      // The result is the negation of the left input.
      return graph()->NewNode(m->Int32Sub(), jsgraph()->Int32Constant(0), left);
    }
    return graph()->NewNode(m->Int32Div(), left, right, *control_);
  }

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
  // asm.js semantics return 0 on divide or mod by zero.
  if (m->Int32DivIsSafe()) {
    // The hardware instruction does the right thing (e.g. arm).
    return graph()->NewNode(m->Int32Div(), left, right, graph()->start());
  }

  // Check denominator for zero.
  Diamond z(
      graph(), jsgraph()->common(),
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(0)),
      BranchHint::kFalse);

  // Check numerator for -1. (avoid minint / -1 case).
  Diamond n(
      graph(), jsgraph()->common(),
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(-1)),
      BranchHint::kFalse);

  Node* div = graph()->NewNode(m->Int32Div(), left, right, z.if_false);
  Node* neg =
      graph()->NewNode(m->Int32Sub(), jsgraph()->Int32Constant(0), left);

  return n.Phi(
      MachineRepresentation::kWord32, neg,
      z.Phi(MachineRepresentation::kWord32, jsgraph()->Int32Constant(0), div));
}

Node* WasmGraphBuilder::BuildI32AsmjsRemS(Node* left, Node* right) {
1928
  CommonOperatorBuilder* c = jsgraph()->common();
1929
  MachineOperatorBuilder* m = jsgraph()->machine();
1930
  Node* const zero = jsgraph()->Int32Constant(0);
1931 1932 1933

  Int32Matcher mr(right);
  if (mr.HasValue()) {
1934 1935
    if (mr.Value() == 0 || mr.Value() == -1) {
      return zero;
1936 1937 1938 1939
    }
    return graph()->NewNode(m->Int32Mod(), left, right, *control_);
  }

1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
  // General case for signed integer modulus, with optimization for (unknown)
  // power of 2 right hand side.
  //
  //   if 0 < right then
  //     msk = right - 1
  //     if right & msk != 0 then
  //       left % right
  //     else
  //       if left < 0 then
  //         -(-left & msk)
  //       else
  //         left & msk
  //   else
  //     if right < -1 then
  //       left % right
  //     else
  //       zero
  //
  // Note: We do not use the Diamond helper class here, because it really hurts
  // readability with nested diamonds.
  Node* const minus_one = jsgraph()->Int32Constant(-1);
1961

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
  const Operator* const merge_op = c->Merge(2);
  const Operator* const phi_op = c->Phi(MachineRepresentation::kWord32, 2);

  Node* check0 = graph()->NewNode(m->Int32LessThan(), zero, right);
  Node* branch0 =
      graph()->NewNode(c->Branch(BranchHint::kTrue), check0, graph()->start());

  Node* if_true0 = graph()->NewNode(c->IfTrue(), branch0);
  Node* true0;
  {
    Node* msk = graph()->NewNode(m->Int32Add(), right, minus_one);

    Node* check1 = graph()->NewNode(m->Word32And(), right, msk);
    Node* branch1 = graph()->NewNode(c->Branch(), check1, if_true0);

    Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1);
    Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1);

    Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1);
    Node* false1;
    {
      Node* check2 = graph()->NewNode(m->Int32LessThan(), left, zero);
      Node* branch2 =
          graph()->NewNode(c->Branch(BranchHint::kFalse), check2, if_false1);

      Node* if_true2 = graph()->NewNode(c->IfTrue(), branch2);
      Node* true2 = graph()->NewNode(
          m->Int32Sub(), zero,
          graph()->NewNode(m->Word32And(),
                           graph()->NewNode(m->Int32Sub(), zero, left), msk));

      Node* if_false2 = graph()->NewNode(c->IfFalse(), branch2);
      Node* false2 = graph()->NewNode(m->Word32And(), left, msk);

      if_false1 = graph()->NewNode(merge_op, if_true2, if_false2);
      false1 = graph()->NewNode(phi_op, true2, false2, if_false1);
    }

    if_true0 = graph()->NewNode(merge_op, if_true1, if_false1);
    true0 = graph()->NewNode(phi_op, true1, false1, if_true0);
  }

  Node* if_false0 = graph()->NewNode(c->IfFalse(), branch0);
  Node* false0;
  {
    Node* check1 = graph()->NewNode(m->Int32LessThan(), right, minus_one);
    Node* branch1 =
        graph()->NewNode(c->Branch(BranchHint::kTrue), check1, if_false0);

    Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1);
    Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1);

    Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1);
    Node* false1 = zero;

    if_false0 = graph()->NewNode(merge_op, if_true1, if_false1);
    false0 = graph()->NewNode(phi_op, true1, false1, if_false0);
  }
2020

2021 2022
  Node* merge0 = graph()->NewNode(merge_op, if_true0, if_false0);
  return graph()->NewNode(phi_op, true0, false0, merge0);
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
}

Node* WasmGraphBuilder::BuildI32AsmjsDivU(Node* left, Node* right) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js semantics return 0 on divide or mod by zero.
  if (m->Uint32DivIsSafe()) {
    // The hardware instruction does the right thing (e.g. arm).
    return graph()->NewNode(m->Uint32Div(), left, right, graph()->start());
  }

  // Explicit check for x % 0.
  Diamond z(
      graph(), jsgraph()->common(),
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(0)),
      BranchHint::kFalse);

  return z.Phi(MachineRepresentation::kWord32, jsgraph()->Int32Constant(0),
               graph()->NewNode(jsgraph()->machine()->Uint32Div(), left, right,
                                z.if_false));
}

Node* WasmGraphBuilder::BuildI32AsmjsRemU(Node* left, Node* right) {
  MachineOperatorBuilder* m = jsgraph()->machine();
  // asm.js semantics return 0 on divide or mod by zero.
  // Explicit check for x % 0.
  Diamond z(
      graph(), jsgraph()->common(),
      graph()->NewNode(m->Word32Equal(), right, jsgraph()->Int32Constant(0)),
      BranchHint::kFalse);

  Node* rem = graph()->NewNode(jsgraph()->machine()->Uint32Mod(), left, right,
                               z.if_false);
  return z.Phi(MachineRepresentation::kWord32, jsgraph()->Int32Constant(0),
               rem);
}

2059 2060
Node* WasmGraphBuilder::BuildI64DivS(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
2061 2062 2063
  if (jsgraph()->machine()->Is32()) {
    return BuildDiv64Call(
        left, right, ExternalReference::wasm_int64_div(jsgraph()->isolate()),
2064
        MachineType::Int64(), wasm::kTrapDivByZero, position);
2065
  }
2066
  ZeroCheck64(wasm::kTrapDivByZero, right, position);
2067 2068 2069
  Node* before = *control_;
  Node* denom_is_m1;
  Node* denom_is_not_m1;
2070 2071 2072
  BranchExpectFalse(graph()->NewNode(jsgraph()->machine()->Word64Equal(), right,
                                     jsgraph()->Int64Constant(-1)),
                    &denom_is_m1, &denom_is_not_m1);
2073
  *control_ = denom_is_m1;
2074 2075
  TrapIfEq64(wasm::kTrapDivUnrepresentable, left,
             std::numeric_limits<int64_t>::min(), position);
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
  if (*control_ != denom_is_m1) {
    *control_ = graph()->NewNode(jsgraph()->common()->Merge(2), denom_is_not_m1,
                                 *control_);
  } else {
    *control_ = before;
  }
  return graph()->NewNode(jsgraph()->machine()->Int64Div(), left, right,
                          *control_);
}

2086 2087
Node* WasmGraphBuilder::BuildI64RemS(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
2088 2089 2090
  if (jsgraph()->machine()->Is32()) {
    return BuildDiv64Call(
        left, right, ExternalReference::wasm_int64_mod(jsgraph()->isolate()),
2091
        MachineType::Int64(), wasm::kTrapRemByZero, position);
2092
  }
2093
  ZeroCheck64(wasm::kTrapRemByZero, right, position);
2094 2095 2096 2097
  Diamond d(jsgraph()->graph(), jsgraph()->common(),
            graph()->NewNode(jsgraph()->machine()->Word64Equal(), right,
                             jsgraph()->Int64Constant(-1)));

2098 2099
  d.Chain(*control_);

2100 2101 2102 2103 2104 2105 2106
  Node* rem = graph()->NewNode(jsgraph()->machine()->Int64Mod(), left, right,
                               d.if_false);

  return d.Phi(MachineRepresentation::kWord64, jsgraph()->Int64Constant(0),
               rem);
}

2107 2108
Node* WasmGraphBuilder::BuildI64DivU(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
2109 2110 2111
  if (jsgraph()->machine()->Is32()) {
    return BuildDiv64Call(
        left, right, ExternalReference::wasm_uint64_div(jsgraph()->isolate()),
2112
        MachineType::Int64(), wasm::kTrapDivByZero, position);
2113
  }
2114 2115
  return graph()->NewNode(jsgraph()->machine()->Uint64Div(), left, right,
                          ZeroCheck64(wasm::kTrapDivByZero, right, position));
2116
}
2117 2118
Node* WasmGraphBuilder::BuildI64RemU(Node* left, Node* right,
                                     wasm::WasmCodePosition position) {
2119 2120 2121
  if (jsgraph()->machine()->Is32()) {
    return BuildDiv64Call(
        left, right, ExternalReference::wasm_uint64_mod(jsgraph()->isolate()),
2122
        MachineType::Int64(), wasm::kTrapRemByZero, position);
2123
  }
2124 2125
  return graph()->NewNode(jsgraph()->machine()->Uint64Mod(), left, right,
                          ZeroCheck64(wasm::kTrapRemByZero, right, position));
2126 2127 2128 2129
}

Node* WasmGraphBuilder::BuildDiv64Call(Node* left, Node* right,
                                       ExternalReference ref,
2130 2131
                                       MachineType result_type, int trap_zero,
                                       wasm::WasmCodePosition position) {
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
  Node* stack_slot_dst = graph()->NewNode(
      jsgraph()->machine()->StackSlot(MachineRepresentation::kWord64));
  Node* stack_slot_src = graph()->NewNode(
      jsgraph()->machine()->StackSlot(MachineRepresentation::kWord64));

  const Operator* store_op = jsgraph()->machine()->Store(
      StoreRepresentation(MachineRepresentation::kWord64, kNoWriteBarrier));
  *effect_ =
      graph()->NewNode(store_op, stack_slot_dst, jsgraph()->Int32Constant(0),
                       left, *effect_, *control_);
  *effect_ =
      graph()->NewNode(store_op, stack_slot_src, jsgraph()->Int32Constant(0),
                       right, *effect_, *control_);

  MachineSignature::Builder sig_builder(jsgraph()->zone(), 1, 2);
  sig_builder.AddReturn(MachineType::Int32());
  sig_builder.AddParam(MachineType::Pointer());
  sig_builder.AddParam(MachineType::Pointer());

  Node* function = graph()->NewNode(jsgraph()->common()->ExternalConstant(ref));
  Node* args[] = {function, stack_slot_dst, stack_slot_src};

  Node* call = BuildCCall(sig_builder.Build(), args);

2156 2157
  ZeroCheck32(static_cast<wasm::TrapReason>(trap_zero), call, position);
  TrapIfEq32(wasm::kTrapDivUnrepresentable, call, -1, position);
2158 2159 2160 2161 2162
  const Operator* load_op = jsgraph()->machine()->Load(result_type);
  Node* load =
      graph()->NewNode(load_op, stack_slot_dst, jsgraph()->Int32Constant(0),
                       *effect_, *control_);
  *effect_ = load;
2163 2164 2165
  return load;
}

2166 2167 2168 2169 2170 2171
Node* WasmGraphBuilder::BuildCCall(MachineSignature* sig, Node** args) {
  const size_t params = sig->parameter_count();
  const size_t extra = 2;  // effect and control inputs.
  const size_t count = 1 + params + extra;

  // Reallocate the buffer to make space for extra inputs.
2172
  args = Realloc(args, 1 + params, count);
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185

  // Add effect and control inputs.
  args[params + 1] = *effect_;
  args[params + 2] = *control_;

  CallDescriptor* desc =
      Linkage::GetSimplifiedCDescriptor(jsgraph()->zone(), sig);

  const Operator* op = jsgraph()->common()->Call(desc);
  Node* call = graph()->NewNode(op, static_cast<int>(count), args);
  *effect_ = call;
  return call;
}
2186

2187 2188 2189
Node* WasmGraphBuilder::BuildWasmCall(wasm::FunctionSig* sig, Node** args,
                                      Node*** rets,
                                      wasm::WasmCodePosition position) {
2190
  SetNeedsStackCheck();
2191 2192 2193 2194 2195
  const size_t params = sig->parameter_count();
  const size_t extra = 2;  // effect and control inputs.
  const size_t count = 1 + params + extra;

  // Reallocate the buffer to make space for extra inputs.
2196
  args = Realloc(args, 1 + params, count);
2197 2198 2199 2200 2201

  // Add effect and control inputs.
  args[params + 1] = *effect_;
  args[params + 2] = *control_;

2202
  CallDescriptor* descriptor = GetWasmCallDescriptor(jsgraph()->zone(), sig);
2203
  const Operator* op = jsgraph()->common()->Call(descriptor);
2204
  Node* call = graph()->NewNode(op, static_cast<int>(count), args);
2205
  SetSourcePosition(call, position);
2206 2207

  *effect_ = call;
2208
  size_t ret_count = sig->return_count();
2209
  if (ret_count == 0) return call;  // No return value.
2210

2211
  *rets = Buffer(ret_count);
2212 2213
  if (ret_count == 1) {
    // Only a single return value.
2214
    (*rets)[0] = call;
2215 2216 2217
  } else {
    // Create projections for all return values.
    for (size_t i = 0; i < ret_count; i++) {
2218 2219
      (*rets)[i] = graph()->NewNode(jsgraph()->common()->Projection(i), call,
                                    graph()->start());
2220 2221
    }
  }
2222
  return call;
2223
}
2224

2225 2226
Node* WasmGraphBuilder::CallDirect(uint32_t index, Node** args, Node*** rets,
                                   wasm::WasmCodePosition position) {
2227 2228 2229
  DCHECK_NULL(args[0]);

  // Add code object as constant.
2230 2231 2232
  Handle<Code> code = index < env_->function_code.size()
                          ? env_->function_code[index]
                          : env_->default_function_code;
2233

2234 2235
  DCHECK(!code.is_null());
  args[0] = HeapConstant(code);
2236
  wasm::FunctionSig* sig = env_->module->functions[index].sig;
2237

2238
  return BuildWasmCall(sig, args, rets, position);
2239 2240
}

2241 2242
Node* WasmGraphBuilder::CallIndirect(uint32_t sig_index, Node** args,
                                     Node*** rets,
2243
                                     wasm::WasmCodePosition position) {
2244
  DCHECK_NOT_NULL(args[0]);
2245
  DCHECK_NOT_NULL(env_);
2246

2247
  // Assume only one table for now.
2248
  uint32_t table_index = 0;
2249
  wasm::FunctionSig* sig = env_->module->signatures[sig_index];
2250 2251 2252 2253 2254 2255 2256 2257

  EnsureFunctionTableNodes();
  MachineOperatorBuilder* machine = jsgraph()->machine();
  Node* key = args[0];

  // Bounds check against the table size.
  Node* size = function_table_sizes_[table_index];
  Node* in_bounds = graph()->NewNode(machine->Uint32LessThan(), key, size);
2258
  TrapIfFalse(wasm::kTrapFuncInvalid, in_bounds, position);
2259 2260 2261 2262 2263 2264 2265 2266
  Node* table_address = function_tables_[table_index];
  Node* table = graph()->NewNode(
      jsgraph()->machine()->Load(MachineType::AnyTagged()), table_address,
      jsgraph()->IntPtrConstant(0), *effect_, *control_);
  Node* signatures_address = signature_tables_[table_index];
  Node* signatures = graph()->NewNode(
      jsgraph()->machine()->Load(MachineType::AnyTagged()), signatures_address,
      jsgraph()->IntPtrConstant(0), *effect_, *control_);
2267 2268 2269 2270 2271 2272 2273
  // Load signature from the table and check.
  // The table is a FixedArray; signatures are encoded as SMIs.
  // [sig1, sig2, sig3, ...., code1, code2, code3 ...]
  ElementAccess access = AccessBuilder::ForFixedArrayElement();
  const int fixed_offset = access.header_size - access.tag();
  {
    Node* load_sig = graph()->NewNode(
2274
        machine->Load(MachineType::AnyTagged()), signatures,
2275 2276 2277 2278 2279
        graph()->NewNode(machine->Int32Add(),
                         graph()->NewNode(machine->Word32Shl(), key,
                                          Int32Constant(kPointerSizeLog2)),
                         Int32Constant(fixed_offset)),
        *effect_, *control_);
2280
    auto map = env_->signature_maps[table_index];
2281 2282
    Node* sig_match = graph()->NewNode(
        machine->WordEqual(), load_sig,
2283
        jsgraph()->SmiConstant(static_cast<int>(map->FindOrInsert(sig))));
2284
    TrapIfFalse(wasm::kTrapFuncSigMismatch, sig_match, position);
2285 2286 2287 2288 2289 2290 2291 2292
  }

  // Load code object from the table.
  Node* load_code = graph()->NewNode(
      machine->Load(MachineType::AnyTagged()), table,
      graph()->NewNode(machine->Int32Add(),
                       graph()->NewNode(machine->Word32Shl(), key,
                                        Int32Constant(kPointerSizeLog2)),
2293
                       Uint32Constant(fixed_offset)),
2294 2295 2296
      *effect_, *control_);

  args[0] = load_code;
2297
  return BuildWasmCall(sig, args, rets, position);
2298 2299
}

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
Node* WasmGraphBuilder::BuildI32Rol(Node* left, Node* right) {
  // Implement Rol by Ror since TurboFan does not have Rol opcode.
  // TODO(weiliang): support Word32Rol opcode in TurboFan.
  Int32Matcher m(right);
  if (m.HasValue()) {
    return Binop(wasm::kExprI32Ror, left,
                 jsgraph()->Int32Constant(32 - m.Value()));
  } else {
    return Binop(wasm::kExprI32Ror, left,
                 Binop(wasm::kExprI32Sub, jsgraph()->Int32Constant(32), right));
  }
}

Node* WasmGraphBuilder::BuildI64Rol(Node* left, Node* right) {
  // Implement Rol by Ror since TurboFan does not have Rol opcode.
  // TODO(weiliang): support Word64Rol opcode in TurboFan.
  Int64Matcher m(right);
  if (m.HasValue()) {
    return Binop(wasm::kExprI64Ror, left,
                 jsgraph()->Int64Constant(64 - m.Value()));
  } else {
    return Binop(wasm::kExprI64Ror, left,
                 Binop(wasm::kExprI64Sub, jsgraph()->Int64Constant(64), right));
  }
}

Node* WasmGraphBuilder::Invert(Node* node) {
  return Unop(wasm::kExprI32Eqz, node);
}

Node* WasmGraphBuilder::BuildChangeInt32ToTagged(Node* value) {
  MachineOperatorBuilder* machine = jsgraph()->machine();
  CommonOperatorBuilder* common = jsgraph()->common();

  if (machine->Is64()) {
    return BuildChangeInt32ToSmi(value);
  }

2338 2339
  Node* add = graph()->NewNode(machine->Int32AddWithOverflow(), value, value,
                               graph()->start());
2340

2341
  Node* ovf = graph()->NewNode(common->Projection(1), add, graph()->start());
2342 2343 2344 2345 2346 2347 2348 2349
  Node* branch = graph()->NewNode(common->Branch(BranchHint::kFalse), ovf,
                                  graph()->start());

  Node* if_true = graph()->NewNode(common->IfTrue(), branch);
  Node* vtrue = BuildAllocateHeapNumberWithValue(
      graph()->NewNode(machine->ChangeInt32ToFloat64(), value), if_true);

  Node* if_false = graph()->NewNode(common->IfFalse(), branch);
2350
  Node* vfalse = graph()->NewNode(common->Projection(0), add, if_false);
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361

  Node* merge = graph()->NewNode(common->Merge(2), if_true, if_false);
  Node* phi = graph()->NewNode(common->Phi(MachineRepresentation::kTagged, 2),
                               vtrue, vfalse, merge);
  return phi;
}

Node* WasmGraphBuilder::BuildChangeFloat64ToTagged(Node* value) {
  MachineOperatorBuilder* machine = jsgraph()->machine();
  CommonOperatorBuilder* common = jsgraph()->common();

2362
  Node* value32 = graph()->NewNode(machine->RoundFloat64ToInt32(), value);
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
  Node* check_same = graph()->NewNode(
      machine->Float64Equal(), value,
      graph()->NewNode(machine->ChangeInt32ToFloat64(), value32));
  Node* branch_same =
      graph()->NewNode(common->Branch(), check_same, graph()->start());

  Node* if_smi = graph()->NewNode(common->IfTrue(), branch_same);
  Node* vsmi;
  Node* if_box = graph()->NewNode(common->IfFalse(), branch_same);
  Node* vbox;

  // We only need to check for -0 if the {value} can potentially contain -0.
  Node* check_zero = graph()->NewNode(machine->Word32Equal(), value32,
                                      jsgraph()->Int32Constant(0));
  Node* branch_zero =
      graph()->NewNode(common->Branch(BranchHint::kFalse), check_zero, if_smi);

  Node* if_zero = graph()->NewNode(common->IfTrue(), branch_zero);
  Node* if_notzero = graph()->NewNode(common->IfFalse(), branch_zero);

  // In case of 0, we need to check the high bits for the IEEE -0 pattern.
  Node* check_negative = graph()->NewNode(
      machine->Int32LessThan(),
      graph()->NewNode(machine->Float64ExtractHighWord32(), value),
      jsgraph()->Int32Constant(0));
  Node* branch_negative = graph()->NewNode(common->Branch(BranchHint::kFalse),
                                           check_negative, if_zero);

  Node* if_negative = graph()->NewNode(common->IfTrue(), branch_negative);
  Node* if_notnegative = graph()->NewNode(common->IfFalse(), branch_negative);

  // We need to create a box for negative 0.
  if_smi = graph()->NewNode(common->Merge(2), if_notzero, if_notnegative);
  if_box = graph()->NewNode(common->Merge(2), if_box, if_negative);

  // On 64-bit machines we can just wrap the 32-bit integer in a smi, for 32-bit
  // machines we need to deal with potential overflow and fallback to boxing.
  if (machine->Is64()) {
    vsmi = BuildChangeInt32ToSmi(value32);
  } else {
2403 2404
    Node* smi_tag = graph()->NewNode(machine->Int32AddWithOverflow(), value32,
                                     value32, if_smi);
2405

2406
    Node* check_ovf = graph()->NewNode(common->Projection(1), smi_tag, if_smi);
2407 2408 2409 2410 2411 2412 2413
    Node* branch_ovf =
        graph()->NewNode(common->Branch(BranchHint::kFalse), check_ovf, if_smi);

    Node* if_ovf = graph()->NewNode(common->IfTrue(), branch_ovf);
    if_box = graph()->NewNode(common->Merge(2), if_ovf, if_box);

    if_smi = graph()->NewNode(common->IfFalse(), branch_ovf);
2414
    vsmi = graph()->NewNode(common->Projection(0), smi_tag, if_smi);
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
  }

  // Allocate the box for the {value}.
  vbox = BuildAllocateHeapNumberWithValue(value, if_box);

  Node* control = graph()->NewNode(common->Merge(2), if_smi, if_box);
  value = graph()->NewNode(common->Phi(MachineRepresentation::kTagged, 2), vsmi,
                           vbox, control);
  return value;
}
2425

2426
Node* WasmGraphBuilder::ToJS(Node* node, wasm::ValueType type) {
2427
  switch (type) {
2428
    case wasm::kWasmI32:
2429
      return BuildChangeInt32ToTagged(node);
2430 2431
    case wasm::kWasmS128:
    case wasm::kWasmI64:
2432
      UNREACHABLE();
2433
    case wasm::kWasmF32:
2434 2435
      node = graph()->NewNode(jsgraph()->machine()->ChangeFloat32ToFloat64(),
                              node);
2436
      return BuildChangeFloat64ToTagged(node);
2437
    case wasm::kWasmF64:
2438
      return BuildChangeFloat64ToTagged(node);
2439
    case wasm::kWasmStmt:
2440 2441 2442 2443 2444 2445
      return jsgraph()->UndefinedConstant();
    default:
      UNREACHABLE();
  }
}

2446
Node* WasmGraphBuilder::BuildJavaScriptToNumber(Node* node, Node* context) {
2447 2448
  Callable callable =
      Builtins::CallableFor(jsgraph()->isolate(), Builtins::kToNumber);
2449 2450
  CallDescriptor* desc = Linkage::GetStubCallDescriptor(
      jsgraph()->isolate(), jsgraph()->zone(), callable.descriptor(), 0,
2451
      CallDescriptor::kNoFlags, Operator::kNoProperties);
2452 2453
  Node* stub_code = jsgraph()->HeapConstant(callable.code());

2454
  Node* result = graph()->NewNode(jsgraph()->common()->Call(desc), stub_code,
2455
                                  node, context, *effect_, *control_);
2456

2457 2458
  SetSourcePosition(result, 1);

2459 2460 2461 2462
  *effect_ = result;

  return result;
}
2463

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
bool CanCover(Node* value, IrOpcode::Value opcode) {
  if (value->opcode() != opcode) return false;
  bool first = true;
  for (Edge const edge : value->use_edges()) {
    if (NodeProperties::IsControlEdge(edge)) continue;
    if (NodeProperties::IsEffectEdge(edge)) continue;
    DCHECK(NodeProperties::IsValueEdge(edge));
    if (!first) return false;
    first = false;
  }
  return true;
}

Node* WasmGraphBuilder::BuildChangeTaggedToFloat64(Node* value) {
  MachineOperatorBuilder* machine = jsgraph()->machine();
  CommonOperatorBuilder* common = jsgraph()->common();

  Node* check = BuildTestNotSmi(value);
  Node* branch = graph()->NewNode(common->Branch(BranchHint::kFalse), check,
                                  graph()->start());

  Node* if_not_smi = graph()->NewNode(common->IfTrue(), branch);

  Node* vnot_smi;
  Node* check_undefined = graph()->NewNode(machine->WordEqual(), value,
                                           jsgraph()->UndefinedConstant());
  Node* branch_undefined = graph()->NewNode(common->Branch(BranchHint::kFalse),
                                            check_undefined, if_not_smi);

  Node* if_undefined = graph()->NewNode(common->IfTrue(), branch_undefined);
  Node* vundefined =
      jsgraph()->Float64Constant(std::numeric_limits<double>::quiet_NaN());

  Node* if_not_undefined =
      graph()->NewNode(common->IfFalse(), branch_undefined);
  Node* vheap_number = BuildLoadHeapNumberValue(value, if_not_undefined);

  if_not_smi =
      graph()->NewNode(common->Merge(2), if_undefined, if_not_undefined);
  vnot_smi = graph()->NewNode(common->Phi(MachineRepresentation::kFloat64, 2),
                              vundefined, vheap_number, if_not_smi);

  Node* if_smi = graph()->NewNode(common->IfFalse(), branch);
  Node* vfrom_smi = BuildChangeSmiToFloat64(value);

  Node* merge = graph()->NewNode(common->Merge(2), if_not_smi, if_smi);
  Node* phi = graph()->NewNode(common->Phi(MachineRepresentation::kFloat64, 2),
                               vnot_smi, vfrom_smi, merge);

  return phi;
}

2516
Node* WasmGraphBuilder::FromJS(Node* node, Node* context,
2517 2518
                               wasm::ValueType type) {
  DCHECK_NE(wasm::kWasmStmt, type);
2519

2520
  // Do a JavaScript ToNumber.
2521
  Node* num = BuildJavaScriptToNumber(node, context);
2522 2523 2524

  // Change representation.
  SimplifiedOperatorBuilder simplified(jsgraph()->zone());
2525
  num = BuildChangeTaggedToFloat64(num);
2526 2527

  switch (type) {
2528
    case wasm::kWasmI32: {
2529
      num = graph()->NewNode(jsgraph()->machine()->TruncateFloat64ToWord32(),
2530 2531 2532
                             num);
      break;
    }
2533 2534
    case wasm::kWasmS128:
    case wasm::kWasmI64:
2535
      UNREACHABLE();
2536
    case wasm::kWasmF32:
2537 2538 2539
      num = graph()->NewNode(jsgraph()->machine()->TruncateFloat64ToFloat32(),
                             num);
      break;
2540
    case wasm::kWasmF64:
2541 2542 2543 2544 2545 2546 2547
      break;
    default:
      UNREACHABLE();
  }
  return num;
}

2548 2549 2550
Node* WasmGraphBuilder::BuildChangeInt32ToSmi(Node* value) {
  if (jsgraph()->machine()->Is64()) {
    value = graph()->NewNode(jsgraph()->machine()->ChangeInt32ToInt64(), value);
2551
  }
2552 2553
  return graph()->NewNode(jsgraph()->machine()->WordShl(), value,
                          BuildSmiShiftBitsConstant());
2554 2555
}

2556 2557 2558 2559 2560 2561
Node* WasmGraphBuilder::BuildChangeSmiToInt32(Node* value) {
  value = graph()->NewNode(jsgraph()->machine()->WordSar(), value,
                           BuildSmiShiftBitsConstant());
  if (jsgraph()->machine()->Is64()) {
    value =
        graph()->NewNode(jsgraph()->machine()->TruncateInt64ToInt32(), value);
2562
  }
2563
  return value;
2564
}
2565

2566 2567 2568 2569 2570 2571 2572 2573 2574
Node* WasmGraphBuilder::BuildChangeUint32ToSmi(Node* value) {
  if (jsgraph()->machine()->Is64()) {
    value =
        graph()->NewNode(jsgraph()->machine()->ChangeUint32ToUint64(), value);
  }
  return graph()->NewNode(jsgraph()->machine()->WordShl(), value,
                          BuildSmiShiftBitsConstant());
}

2575 2576 2577
Node* WasmGraphBuilder::BuildChangeSmiToFloat64(Node* value) {
  return graph()->NewNode(jsgraph()->machine()->ChangeInt32ToFloat64(),
                          BuildChangeSmiToInt32(value));
2578 2579
}

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
Node* WasmGraphBuilder::BuildTestNotSmi(Node* value) {
  STATIC_ASSERT(kSmiTag == 0);
  STATIC_ASSERT(kSmiTagMask == 1);
  return graph()->NewNode(jsgraph()->machine()->WordAnd(), value,
                          jsgraph()->IntPtrConstant(kSmiTagMask));
}

Node* WasmGraphBuilder::BuildSmiShiftBitsConstant() {
  return jsgraph()->IntPtrConstant(kSmiShiftSize + kSmiTagSize);
}

Node* WasmGraphBuilder::BuildAllocateHeapNumberWithValue(Node* value,
                                                         Node* control) {
  MachineOperatorBuilder* machine = jsgraph()->machine();
  CommonOperatorBuilder* common = jsgraph()->common();
  // The AllocateHeapNumberStub does not use the context, so we can safely pass
  // in Smi zero here.
  Callable callable = CodeFactory::AllocateHeapNumber(jsgraph()->isolate());
  Node* target = jsgraph()->HeapConstant(callable.code());
  Node* context = jsgraph()->NoContextConstant();
2600 2601 2602
  Node* effect =
      graph()->NewNode(common->BeginRegion(RegionObservability::kNotObservable),
                       graph()->start());
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
  if (!allocate_heap_number_operator_.is_set()) {
    CallDescriptor* descriptor = Linkage::GetStubCallDescriptor(
        jsgraph()->isolate(), jsgraph()->zone(), callable.descriptor(), 0,
        CallDescriptor::kNoFlags, Operator::kNoThrow);
    allocate_heap_number_operator_.set(common->Call(descriptor));
  }
  Node* heap_number = graph()->NewNode(allocate_heap_number_operator_.get(),
                                       target, context, effect, control);
  Node* store =
      graph()->NewNode(machine->Store(StoreRepresentation(
                           MachineRepresentation::kFloat64, kNoWriteBarrier)),
                       heap_number, BuildHeapNumberValueIndexConstant(), value,
                       heap_number, control);
  return graph()->NewNode(common->FinishRegion(), heap_number, store);
}

Node* WasmGraphBuilder::BuildLoadHeapNumberValue(Node* value, Node* control) {
  return graph()->NewNode(jsgraph()->machine()->Load(MachineType::Float64()),
                          value, BuildHeapNumberValueIndexConstant(),
                          graph()->start(), control);
}

Node* WasmGraphBuilder::BuildHeapNumberValueIndexConstant() {
  return jsgraph()->IntPtrConstant(HeapNumber::kValueOffset - kHeapObjectTag);
}
2628

2629 2630
void WasmGraphBuilder::BuildJSToWasmWrapper(Handle<Code> wasm_code) {
  int wasm_count = static_cast<int>(sig_->parameter_count());
2631
  int count = wasm_count + 3;
2632 2633 2634
  Node** args = Buffer(count);

  // Build the start and the JS parameter nodes.
2635
  Node* start = Start(wasm_count + 5);
2636 2637
  *control_ = start;
  *effect_ = start;
2638

2639 2640 2641 2642 2643 2644
  // Create the context parameter
  Node* context = graph()->NewNode(
      jsgraph()->common()->Parameter(
          Linkage::GetJSCallContextParamIndex(wasm_count + 1), "%context"),
      graph()->start());

2645
  // Set the ThreadInWasm flag before we do the actual call.
2646
  BuildModifyThreadInWasmFlag(true);
2647

2648
  if (!wasm::IsJSCompatibleSignature(sig_)) {
2649 2650 2651
    // Throw a TypeError. Use the context of the calling javascript function
    // (passed as a parameter), such that the generated code is context
    // independent.
2652 2653
    BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, context,
                                  nullptr, 0);
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664

    // Add a dummy call to the wasm function so that the generated wrapper
    // contains a reference to the wrapped wasm function. Without this reference
    // the wasm function could not be re-imported into another wasm module.
    int pos = 0;
    args[pos++] = HeapConstant(wasm_code);
    args[pos++] = *effect_;
    args[pos++] = *control_;

    // We only need a dummy call descriptor.
    wasm::FunctionSig::Builder dummy_sig_builder(jsgraph()->zone(), 0, 0);
2665 2666
    CallDescriptor* desc =
        GetWasmCallDescriptor(jsgraph()->zone(), dummy_sig_builder.Build());
2667 2668 2669 2670 2671
    *effect_ = graph()->NewNode(jsgraph()->common()->Call(desc), pos, args);
    Return(jsgraph()->UndefinedConstant());
    return;
  }

2672
  int pos = 0;
2673
  args[pos++] = HeapConstant(wasm_code);
2674

2675
  // Convert JS parameters to wasm numbers.
ritesht's avatar
ritesht committed
2676
  for (int i = 0; i < wasm_count; ++i) {
2677
    Node* param = Param(i + 1);
2678
    Node* wasm_param = FromJS(param, context, sig_->GetParam(i));
2679
    args[pos++] = wasm_param;
2680 2681 2682 2683 2684
  }

  args[pos++] = *effect_;
  args[pos++] = *control_;

2685
  // Call the wasm code.
2686
  CallDescriptor* desc = GetWasmCallDescriptor(jsgraph()->zone(), sig_);
2687

2688
  Node* call = graph()->NewNode(jsgraph()->common()->Call(desc), count, args);
2689
  *effect_ = call;
eholk's avatar
eholk committed
2690 2691

  // Clear the ThreadInWasmFlag
2692
  BuildModifyThreadInWasmFlag(false);
eholk's avatar
eholk committed
2693

2694
  Node* retval = call;
2695
  Node* jsval = ToJS(
2696
      retval, sig_->return_count() == 0 ? wasm::kWasmStmt : sig_->GetReturn());
2697
  Return(jsval);
2698 2699
}

2700 2701
int WasmGraphBuilder::AddParameterNodes(Node** args, int pos, int param_count,
                                        wasm::FunctionSig* sig) {
2702
  // Convert wasm numbers to JS values.
2703
  for (int i = 0; i < param_count; ++i) {
2704
    Node* param = Param(i);
2705 2706 2707 2708 2709
    args[pos++] = ToJS(param, sig->GetParam(i));
  }
  return pos;
}

2710 2711 2712
bool WasmGraphBuilder::BuildWasmToJSWrapper(
    Handle<JSReceiver> target, Handle<FixedArray> global_js_imports_table,
    int index) {
2713 2714
  DCHECK(target->IsCallable());

2715
  int wasm_count = static_cast<int>(sig_->parameter_count());
2716 2717 2718 2719

  // Build the start and the parameter nodes.
  Isolate* isolate = jsgraph()->isolate();
  CallDescriptor* desc;
2720
  Node* start = Start(wasm_count + 3);
2721 2722
  *effect_ = start;
  *control_ = start;
2723

2724
  if (!wasm::IsJSCompatibleSignature(sig_)) {
2725 2726 2727 2728
    // Throw a TypeError. Embedding the context is ok here, since this code is
    // regenerated at instantiation time.
    Node* context =
        jsgraph()->HeapConstant(jsgraph()->isolate()->native_context());
2729 2730
    BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, context,
                                  nullptr, 0);
2731 2732 2733
    // We don't need to return a value here, as the runtime call will not return
    // anyway (the c entry stub will trigger stack unwinding).
    ReturnVoid();
2734
    return false;
2735 2736
  }

2737 2738
  Node** args = Buffer(wasm_count + 7);

2739
  Node* call = nullptr;
2740

2741
  BuildModifyThreadInWasmFlag(false);
eholk's avatar
eholk committed
2742

2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
  // We add the target function to a table and look it up during runtime. This
  // ensures that if the GC kicks in, it doesn't need to patch the code for the
  // JS function.
  // js_imports_table is fixed array with global handle scope whose lifetime is
  // tied to the instance.
  // TODO(aseemgarg): explore using per-import global handle instead of a table
  Node* js_table = jsgraph()->IntPtrConstant(
      reinterpret_cast<intptr_t>(global_js_imports_table.location()));
  Node* load_table = graph()->NewNode(
      jsgraph()->machine()->Load(LoadRepresentation::TaggedPointer()), js_table,
      jsgraph()->IntPtrConstant(0), *effect_, *control_);
  *effect_ = load_table;
  int offset =
      global_js_imports_table->OffsetOfElementAt(index) - kHeapObjectTag;
  Node* offset_node = jsgraph()->Int32Constant(offset);
  Node* target_address = graph()->NewNode(
      jsgraph()->machine()->Load(LoadRepresentation::TaggedPointer()),
      load_table, offset_node, *effect_, *control_);
  *effect_ = target_address;

2763 2764 2765
  if (target->IsJSFunction()) {
    Handle<JSFunction> function = Handle<JSFunction>::cast(target);
    if (function->shared()->internal_formal_parameter_count() == wasm_count) {
2766
      int pos = 0;
2767
      args[pos++] = target_address;  // target callable.
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
      // Receiver.
      if (is_sloppy(function->shared()->language_mode()) &&
          !function->shared()->native()) {
        args[pos++] =
            HeapConstant(handle(function->context()->global_proxy(), isolate));
      } else {
        args[pos++] = jsgraph()->Constant(
            handle(isolate->heap()->undefined_value(), isolate));
      }

      desc = Linkage::GetJSCallDescriptor(
          graph()->zone(), false, wasm_count + 1, CallDescriptor::kNoFlags);

2781
      // Convert wasm numbers to JS values.
2782
      pos = AddParameterNodes(args, pos, wasm_count, sig_);
2783 2784 2785 2786 2787 2788 2789 2790

      args[pos++] = jsgraph()->UndefinedConstant();        // new target
      args[pos++] = jsgraph()->Int32Constant(wasm_count);  // argument count
      args[pos++] = HeapConstant(handle(function->context()));
      args[pos++] = *effect_;
      args[pos++] = *control_;

      call = graph()->NewNode(jsgraph()->common()->Call(desc), pos, args);
2791 2792 2793 2794
    }
  }

  // We cannot call the target directly, we have to use the Call builtin.
2795
  if (!call) {
2796
    int pos = 0;
2797 2798
    Callable callable = CodeFactory::Call(isolate);
    args[pos++] = jsgraph()->HeapConstant(callable.code());
2799
    args[pos++] = target_address;                        // target callable
2800 2801 2802 2803
    args[pos++] = jsgraph()->Int32Constant(wasm_count);  // argument count
    args[pos++] = jsgraph()->Constant(
        handle(isolate->heap()->undefined_value(), isolate));  // receiver

2804 2805 2806 2807
    desc = Linkage::GetStubCallDescriptor(isolate, graph()->zone(),
                                          callable.descriptor(), wasm_count + 1,
                                          CallDescriptor::kNoFlags);

2808
    // Convert wasm numbers to JS values.
2809
    pos = AddParameterNodes(args, pos, wasm_count, sig_);
2810

2811 2812 2813 2814 2815 2816 2817 2818
    // The native_context is sufficient here, because all kind of callables
    // which depend on the context provide their own context. The context here
    // is only needed if the target is a constructor to throw a TypeError, if
    // the target is a native function, or if the target is a callable JSObject,
    // which can only be constructed by the runtime.
    args[pos++] = HeapConstant(isolate->native_context());
    args[pos++] = *effect_;
    args[pos++] = *control_;
2819

2820 2821
    call = graph()->NewNode(jsgraph()->common()->Call(desc), pos, args);
  }
2822

2823
  *effect_ = call;
2824
  SetSourcePosition(call, 0);
2825

2826
  BuildModifyThreadInWasmFlag(true);
eholk's avatar
eholk committed
2827

2828
  // Convert the return value back.
2829
  Node* val = sig_->return_count() == 0
2830
                  ? jsgraph()->Int32Constant(0)
2831
                  : FromJS(call, HeapConstant(isolate->native_context()),
2832
                           sig_->GetReturn());
2833
  Return(val);
2834
  return true;
2835 2836
}

2837 2838 2839 2840 2841 2842 2843 2844 2845
namespace {
bool HasInt64ParamOrReturn(wasm::FunctionSig* sig) {
  for (auto type : sig->all()) {
    if (type == wasm::kWasmI64) return true;
  }
  return false;
}
}  // namespace

2846
void WasmGraphBuilder::BuildWasmInterpreterEntry(
2847
    uint32_t function_index, Handle<WasmInstanceObject> instance) {
2848
  int param_count = static_cast<int>(sig_->parameter_count());
2849 2850 2851 2852 2853 2854 2855 2856

  // Build the start and the parameter nodes.
  Node* start = Start(param_count + 3);
  *effect_ = start;
  *control_ = start;

  // Compute size for the argument buffer.
  int args_size_bytes = 0;
2857 2858
  for (wasm::ValueType type : sig_->parameters()) {
    args_size_bytes += 1 << ElementSizeLog2Of(type);
2859 2860 2861
  }

  // The return value is also passed via this buffer:
2862
  DCHECK_GE(wasm::kV8MaxWasmFunctionReturns, sig_->return_count());
2863 2864
  // TODO(wasm): Handle multi-value returns.
  DCHECK_EQ(1, wasm::kV8MaxWasmFunctionReturns);
2865
  int return_size_bytes =
2866
      sig_->return_count() == 0 ? 0 : 1 << ElementSizeLog2Of(sig_->GetReturn());
2867 2868

  // Get a stack slot for the arguments.
2869 2870 2871 2872 2873
  Node* arg_buffer =
      args_size_bytes == 0 && return_size_bytes == 0
          ? jsgraph()->IntPtrConstant(0)
          : graph()->NewNode(jsgraph()->machine()->StackSlot(
                std::max(args_size_bytes, return_size_bytes), 8));
2874 2875 2876

  // Now store all our arguments to the buffer.
  int offset = 0;
2877

2878 2879 2880 2881 2882 2883
  for (int i = 0; i < param_count; ++i) {
    wasm::ValueType type = sig_->GetParam(i);
    *effect_ =
        graph()->NewNode(GetSafeStoreOperator(offset, type), arg_buffer,
                         Int32Constant(offset), Param(i), *effect_, *control_);
    offset += 1 << ElementSizeLog2Of(type);
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
  }
  DCHECK_EQ(args_size_bytes, offset);

  // We are passing the raw arg_buffer here. To the GC and other parts, it looks
  // like a Smi (lowest bit not set). In the runtime function however, don't
  // call Smi::value on it, but just cast it to a byte pointer.
  Node* parameters[] = {
      jsgraph()->HeapConstant(instance),       // wasm instance
      jsgraph()->SmiConstant(function_index),  // function index
      arg_buffer,                              // argument buffer
  };
2895 2896
  BuildCallToRuntime(Runtime::kWasmRunInterpreter, parameters,
                     arraysize(parameters));
2897 2898

  // Read back the return value.
2899
  if (sig_->return_count() == 0) {
2900
    Return(Int32Constant(0));
2901
  } else {
2902 2903
    // TODO(wasm): Implement multi-return.
    DCHECK_EQ(1, sig_->return_count());
2904
    MachineType load_rep = wasm::WasmOpcodes::MachineTypeFor(sig_->GetReturn());
2905 2906 2907
    Node* val =
        graph()->NewNode(jsgraph()->machine()->Load(load_rep), arg_buffer,
                         Int32Constant(0), *effect_, *control_);
2908 2909
    Return(val);
  }
2910 2911

  if (HasInt64ParamOrReturn(sig_)) LowerInt64();
2912 2913
}

2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
void WasmGraphBuilder::BuildCWasmEntry() {
  // Build the start and the JS parameter nodes.
  Node* start = Start(CWasmEntryParameters::kNumParameters + 5);
  *control_ = start;
  *effect_ = start;

  // Create parameter nodes (offset by 1 for the receiver parameter).
  Node* code_obj = Param(CWasmEntryParameters::kCodeObject + 1);
  Node* arg_buffer = Param(CWasmEntryParameters::kArgumentsBuffer + 1);

  // Set the ThreadInWasm flag before we do the actual call.
  BuildModifyThreadInWasmFlag(true);

  int wasm_arg_count = static_cast<int>(sig_->parameter_count());
  int arg_count = wasm_arg_count + 3;  // args + code, control, effect
  Node** args = Buffer(arg_count);

  int pos = 0;
  args[pos++] = code_obj;

  int offset = 0;
  for (wasm::ValueType type : sig_->parameters()) {
    Node* arg_load =
        graph()->NewNode(GetSafeLoadOperator(offset, type), arg_buffer,
                         Int32Constant(offset), *effect_, *control_);
    *effect_ = arg_load;
    args[pos++] = arg_load;
    offset += 1 << ElementSizeLog2Of(type);
  }

  args[pos++] = *effect_;
  args[pos++] = *control_;
  DCHECK_EQ(arg_count, pos);

  // Call the wasm code.
  CallDescriptor* desc = GetWasmCallDescriptor(jsgraph()->zone(), sig_);

  Node* call =
      graph()->NewNode(jsgraph()->common()->Call(desc), arg_count, args);
  *effect_ = call;

  // Clear the ThreadInWasmFlag
  BuildModifyThreadInWasmFlag(false);

  // Store the return value.
  DCHECK_GE(1, sig_->return_count());
  if (sig_->return_count() == 1) {
    StoreRepresentation store_rep(sig_->GetReturn(), kNoWriteBarrier);
    Node* store =
        graph()->NewNode(jsgraph()->machine()->Store(store_rep), arg_buffer,
                         Int32Constant(0), call, *effect_, *control_);
    *effect_ = store;
  }
  Return(jsgraph()->SmiConstant(0));

  if (jsgraph()->machine()->Is32() && HasInt64ParamOrReturn(sig_)) {
    MachineRepresentation sig_reps[] = {
        MachineRepresentation::kWord32,  // return value
        MachineRepresentation::kTagged,  // receiver
        MachineRepresentation::kTagged,  // arg0 (code)
        MachineRepresentation::kTagged   // arg1 (buffer)
    };
    wasm::FunctionSig c_entry_sig(1, 2, sig_reps);
    Int64Lowering r(jsgraph()->graph(), jsgraph()->machine(),
                    jsgraph()->common(), jsgraph()->zone(), &c_entry_sig);
    r.LowerGraph();
  }
}

2983
Node* WasmGraphBuilder::MemBuffer(uint32_t offset) {
2984 2985
  DCHECK_NOT_NULL(env_);
  const uintptr_t mem_start = static_cast<const uintptr_t>(env_->mem_start);
2986
  if (offset == 0) {
2987
    if (!mem_buffer_) {
2988
      mem_buffer_ = jsgraph()->RelocatableIntPtrConstant(
2989
          mem_start, RelocInfo::WASM_MEMORY_REFERENCE);
2990
    }
2991 2992
    return mem_buffer_;
  } else {
2993
    return jsgraph()->RelocatableIntPtrConstant(
2994 2995
        static_cast<uintptr_t>(mem_start + offset),
        RelocInfo::WASM_MEMORY_REFERENCE);
2996 2997 2998
  }
}

2999
Node* WasmGraphBuilder::CurrentMemoryPages() {
3000
  // CurrentMemoryPages can not be called from asm.js.
3001
  DCHECK_EQ(wasm::kWasmOrigin, env_->module->origin());
3002
  SetNeedsStackCheck();
3003
  Node* call = BuildCallToRuntime(Runtime::kWasmMemorySize, nullptr, 0);
3004 3005
  Node* result = BuildChangeSmiToInt32(call);
  return result;
3006 3007
}

3008
Node* WasmGraphBuilder::MemSize() {
3009
  DCHECK_NOT_NULL(env_);
3010
  if (mem_size_) return mem_size_;
3011
  uint32_t size = env_->mem_size;
3012 3013 3014
  mem_size_ = jsgraph()->RelocatableInt32Constant(
      size, RelocInfo::WASM_MEMORY_SIZE_REFERENCE);
  return mem_size_;
3015 3016
}

3017 3018
void WasmGraphBuilder::EnsureFunctionTableNodes() {
  if (function_tables_.size() > 0) return;
3019
  size_t tables_size = env_->function_tables.size();
3020
  for (size_t i = 0; i < tables_size; ++i) {
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
    wasm::GlobalHandleAddress function_handle_address =
        env_->function_tables[i];
    wasm::GlobalHandleAddress signature_handle_address =
        env_->signature_tables[i];
    function_tables_.push_back(jsgraph()->RelocatableIntPtrConstant(
        reinterpret_cast<intptr_t>(function_handle_address),
        RelocInfo::WASM_GLOBAL_HANDLE));
    signature_tables_.push_back(jsgraph()->RelocatableIntPtrConstant(
        reinterpret_cast<intptr_t>(signature_handle_address),
        RelocInfo::WASM_GLOBAL_HANDLE));
3031
    uint32_t table_size = env_->module->function_tables[i].initial_size;
3032 3033 3034
    function_table_sizes_.push_back(jsgraph()->RelocatableInt32Constant(
        static_cast<uint32_t>(table_size),
        RelocInfo::WASM_FUNCTION_TABLE_SIZE_REFERENCE));
3035 3036 3037
  }
}

3038 3039 3040
Node* WasmGraphBuilder::BuildModifyThreadInWasmFlag(bool new_value) {
  // TODO(eholk): generate code to modify the thread-local storage directly,
  // rather than calling the runtime.
3041 3042 3043 3044
  //
  // Note that the runtime functions also toggle the wasm_execution_time
  // counters. Make sure this behavior is preserved if we avoid the runtime
  // call.
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
  if (!trap_handler::UseTrapHandler()) {
    return *control_;
  }

  const Runtime::FunctionId f =
      new_value ? Runtime::kSetThreadInWasm : Runtime::kClearThreadInWasm;
  const Runtime::Function* fun = Runtime::FunctionForId(f);
  DCHECK_EQ(0, fun->nargs);
  const CallDescriptor* desc = Linkage::GetRuntimeCallDescriptor(
      jsgraph()->zone(), f, fun->nargs, Operator::kNoProperties,
      CallDescriptor::kNoFlags);
  // CEntryStubConstant nodes have to be created and cached in the main
  // thread. At the moment this is only done for CEntryStubConstant(1).
  DCHECK_EQ(1, fun->result_size);
  Node* inputs[] = {centry_stub_node_,
                    jsgraph()->ExternalConstant(
                        ExternalReference(f, jsgraph()->isolate())),  // ref
                    jsgraph()->Int32Constant(fun->nargs),             // arity
                    jsgraph()->NoContextConstant(),
                    *effect_,
                    *control_};

  Node* node = jsgraph()->graph()->NewNode(jsgraph()->common()->Call(desc),
                                           arraysize(inputs), inputs);
  *effect_ = node;
  return node;
}

// Only call this function for code which is not reused across instantiations,
// as we do not patch the embedded context.
Node* WasmGraphBuilder::BuildCallToRuntimeWithContext(Runtime::FunctionId f,
                                                      Node* context,
                                                      Node** parameters,
                                                      int parameter_count) {
  // Setting and clearing the thread-in-wasm flag should not be done as a normal
  // runtime call.
  DCHECK_NE(f, Runtime::kSetThreadInWasm);
  DCHECK_NE(f, Runtime::kClearThreadInWasm);
  // We're leaving Wasm code, so clear the flag.
  *control_ = BuildModifyThreadInWasmFlag(false);

  const Runtime::Function* fun = Runtime::FunctionForId(f);
  CallDescriptor* desc = Linkage::GetRuntimeCallDescriptor(
      jsgraph()->zone(), f, fun->nargs, Operator::kNoProperties,
      CallDescriptor::kNoFlags);
  // CEntryStubConstant nodes have to be created and cached in the main
  // thread. At the moment this is only done for CEntryStubConstant(1).
  DCHECK_EQ(1, fun->result_size);
  // At the moment we only allow 3 parameters. If more parameters are needed,
  // increase this constant accordingly.
  static const int kMaxParams = 3;
  DCHECK_GE(kMaxParams, parameter_count);
  Node* inputs[kMaxParams + 6];
  int count = 0;
  inputs[count++] = centry_stub_node_;
  for (int i = 0; i < parameter_count; i++) {
    inputs[count++] = parameters[i];
  }
  inputs[count++] = jsgraph()->ExternalConstant(
      ExternalReference(f, jsgraph()->isolate()));         // ref
  inputs[count++] = jsgraph()->Int32Constant(fun->nargs);  // arity
3106
  inputs[count++] = context;                               // context
3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
  inputs[count++] = *effect_;
  inputs[count++] = *control_;

  Node* node = jsgraph()->graph()->NewNode(jsgraph()->common()->Call(desc),
                                           count, inputs);
  *effect_ = node;

  // Restore the thread-in-wasm flag, since we have returned to Wasm.
  *control_ = BuildModifyThreadInWasmFlag(true);

  return node;
}

Node* WasmGraphBuilder::BuildCallToRuntime(Runtime::FunctionId f,
                                           Node** parameters,
                                           int parameter_count) {
  return BuildCallToRuntimeWithContext(f, jsgraph()->NoContextConstant(),
                                       parameters, parameter_count);
}

3127
Node* WasmGraphBuilder::GetGlobal(uint32_t index) {
3128
  MachineType mem_type =
3129 3130 3131
      wasm::WasmOpcodes::MachineTypeFor(env_->module->globals[index].type);
  uintptr_t global_addr =
      env_->globals_start + env_->module->globals[index].offset;
mtrofin's avatar
mtrofin committed
3132
  Node* addr = jsgraph()->RelocatableIntPtrConstant(
3133
      global_addr, RelocInfo::WASM_GLOBAL_REFERENCE);
3134 3135 3136 3137 3138 3139 3140
  const Operator* op = jsgraph()->machine()->Load(mem_type);
  Node* node = graph()->NewNode(op, addr, jsgraph()->Int32Constant(0), *effect_,
                                *control_);
  *effect_ = node;
  return node;
}

3141
Node* WasmGraphBuilder::SetGlobal(uint32_t index, Node* val) {
3142
  MachineType mem_type =
3143 3144 3145
      wasm::WasmOpcodes::MachineTypeFor(env_->module->globals[index].type);
  uintptr_t global_addr =
      env_->globals_start + env_->module->globals[index].offset;
mtrofin's avatar
mtrofin committed
3146
  Node* addr = jsgraph()->RelocatableIntPtrConstant(
3147
      global_addr, RelocInfo::WASM_GLOBAL_REFERENCE);
3148
  const Operator* op = jsgraph()->machine()->Store(
3149
      StoreRepresentation(mem_type.representation(), kNoWriteBarrier));
3150 3151 3152 3153 3154 3155 3156
  Node* node = graph()->NewNode(op, addr, jsgraph()->Int32Constant(0), val,
                                *effect_, *control_);
  *effect_ = node;
  return node;
}

void WasmGraphBuilder::BoundsCheckMem(MachineType memtype, Node* index,
3157 3158
                                      uint32_t offset,
                                      wasm::WasmCodePosition position) {
3159
  if (FLAG_wasm_no_bounds_checks) return;
3160

3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
  uint64_t min_size = static_cast<uint64_t>(env_->module->initial_pages) *
                      wasm::WasmModule::kPageSize;
  uint64_t max_size = static_cast<uint64_t>(env_->module->has_maximum_pages
                                                ? env_->module->maximum_pages
                                                : wasm::kV8MaxWasmMemoryPages) *
                      wasm::WasmModule::kPageSize;

  byte access_size = wasm::WasmOpcodes::MemSize(memtype);

  uint64_t end_offset = static_cast<uint64_t>(offset) + access_size;
  if (end_offset > max_size) {
    // The access will be out of bounds, even for the largest memory.
    TrapIfEq32(wasm::kTrapMemOutOfBounds, jsgraph()->Int32Constant(0), 0,
               position);
    return;
  }

  if (end_offset > min_size) {
    // The end offset is larger than the smallest memory.
    // Dynamically check the end offset against the actual memory size, which
    // is not known at compile time.
    Node* cond = graph()->NewNode(
        jsgraph()->machine()->Uint32LessThanOrEqual(),
        jsgraph()->IntPtrConstant(static_cast<uintptr_t>(end_offset)),
        jsgraph()->RelocatableInt32Constant(
            static_cast<uint32_t>(env_->mem_size),
            RelocInfo::WASM_MEMORY_SIZE_REFERENCE));
3188
    TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position);
3189
  } else {
3190 3191
    // The end offset is within the bounds of the smallest memory, so only
    // one check is required. Check to see if the index is also a constant.
3192 3193
    Uint32Matcher m(index);
    if (m.HasValue()) {
3194 3195 3196 3197
      uint64_t index_val = m.Value();
      if ((index_val + offset + access_size) <= min_size) {
        // The input index is a constant and everything is statically within
        // bounds of the smallest possible memory.
3198 3199
        return;
      }
3200
    }
3201 3202
  }

3203
  uint64_t effective_size = env_->mem_size - (end_offset - 1);
3204 3205 3206 3207
  Node* cond = graph()->NewNode(jsgraph()->machine()->Uint32LessThan(), index,
                                jsgraph()->RelocatableInt32Constant(
                                    static_cast<uint32_t>(effective_size),
                                    RelocInfo::WASM_MEMORY_SIZE_REFERENCE));
3208
  TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position);
3209 3210
}

3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
const Operator* WasmGraphBuilder::GetSafeLoadOperator(int offset,
                                                      wasm::ValueType type) {
  int alignment = offset % (1 << ElementSizeLog2Of(type));
  MachineType mach_type = wasm::WasmOpcodes::MachineTypeFor(type);
  if (alignment == 0 || jsgraph()->machine()->UnalignedLoadSupported(type)) {
    return jsgraph()->machine()->Load(mach_type);
  }
  return jsgraph()->machine()->UnalignedLoad(mach_type);
}

3221 3222 3223
const Operator* WasmGraphBuilder::GetSafeStoreOperator(int offset,
                                                       wasm::ValueType type) {
  int alignment = offset % (1 << ElementSizeLog2Of(type));
3224
  if (alignment == 0 || jsgraph()->machine()->UnalignedStoreSupported(type)) {
3225 3226 3227 3228 3229 3230 3231
    StoreRepresentation rep(type, WriteBarrierKind::kNoWriteBarrier);
    return jsgraph()->machine()->Store(rep);
  }
  UnalignedStoreRepresentation rep(type);
  return jsgraph()->machine()->UnalignedStore(rep);
}

3232
Node* WasmGraphBuilder::LoadMem(wasm::ValueType type, MachineType memtype,
3233
                                Node* index, uint32_t offset,
3234
                                uint32_t alignment,
3235
                                wasm::WasmCodePosition position) {
3236
  Node* load;
3237

3238
  // Wasm semantics throw on OOB. Introduce explicit bounds check.
eholk's avatar
eholk committed
3239
  if (!FLAG_wasm_trap_handler || !V8_TRAP_HANDLER_SUPPORTED) {
3240 3241
    BoundsCheckMem(memtype, index, offset, position);
  }
3242

3243
  if (memtype.representation() == MachineRepresentation::kWord8 ||
3244
      jsgraph()->machine()->UnalignedLoadSupported(memtype.representation())) {
eholk's avatar
eholk committed
3245
    if (FLAG_wasm_trap_handler && V8_TRAP_HANDLER_SUPPORTED) {
3246
      DCHECK(FLAG_wasm_guard_pages);
3247 3248
      Node* position_node = jsgraph()->Int32Constant(position);
      load = graph()->NewNode(jsgraph()->machine()->ProtectedLoad(memtype),
3249 3250
                              MemBuffer(offset), index, position_node, *effect_,
                              *control_);
3251 3252 3253 3254
    } else {
      load = graph()->NewNode(jsgraph()->machine()->Load(memtype),
                              MemBuffer(offset), index, *effect_, *control_);
    }
3255
  } else {
3256
    // TODO(eholk): Support unaligned loads with trap handlers.
eholk's avatar
eholk committed
3257
    DCHECK(!FLAG_wasm_trap_handler || !V8_TRAP_HANDLER_SUPPORTED);
3258 3259
    load = graph()->NewNode(jsgraph()->machine()->UnalignedLoad(memtype),
                            MemBuffer(offset), index, *effect_, *control_);
3260
  }
3261 3262 3263

  *effect_ = load;

3264
#if defined(V8_TARGET_BIG_ENDIAN)
3265
  load = BuildChangeEndiannessLoad(load, memtype, type);
3266
#endif
3267

3268
  if (type == wasm::kWasmI64 &&
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
      ElementSizeLog2Of(memtype.representation()) < 3) {
    // TODO(titzer): TF zeroes the upper bits of 64-bit loads for subword sizes.
    if (memtype.IsSigned()) {
      // sign extend
      load = graph()->NewNode(jsgraph()->machine()->ChangeInt32ToInt64(), load);
    } else {
      // zero extend
      load =
          graph()->NewNode(jsgraph()->machine()->ChangeUint32ToUint64(), load);
    }
  }

  return load;
}

Node* WasmGraphBuilder::StoreMem(MachineType memtype, Node* index,
3285
                                 uint32_t offset, uint32_t alignment, Node* val,
3286 3287
                                 wasm::WasmCodePosition position,
                                 wasm::ValueType type) {
3288
  Node* store;
3289

3290
  // Wasm semantics throw on OOB. Introduce explicit bounds check.
eholk's avatar
eholk committed
3291
  if (!FLAG_wasm_trap_handler || !V8_TRAP_HANDLER_SUPPORTED) {
3292 3293
    BoundsCheckMem(memtype, index, offset, position);
  }
3294

3295
#if defined(V8_TARGET_BIG_ENDIAN)
3296
  val = BuildChangeEndiannessStore(val, memtype, type);
3297 3298
#endif

3299
  if (memtype.representation() == MachineRepresentation::kWord8 ||
3300
      jsgraph()->machine()->UnalignedStoreSupported(memtype.representation())) {
eholk's avatar
eholk committed
3301
    if (FLAG_wasm_trap_handler && V8_TRAP_HANDLER_SUPPORTED) {
3302 3303 3304
      Node* position_node = jsgraph()->Int32Constant(position);
      store = graph()->NewNode(
          jsgraph()->machine()->ProtectedStore(memtype.representation()),
3305
          MemBuffer(offset), index, val, position_node, *effect_, *control_);
3306 3307 3308 3309 3310 3311
    } else {
      StoreRepresentation rep(memtype.representation(), kNoWriteBarrier);
      store =
          graph()->NewNode(jsgraph()->machine()->Store(rep), MemBuffer(offset),
                           index, val, *effect_, *control_);
    }
3312
  } else {
3313
    // TODO(eholk): Support unaligned stores with trap handlers.
eholk's avatar
eholk committed
3314
    DCHECK(!FLAG_wasm_trap_handler || !V8_TRAP_HANDLER_SUPPORTED);
3315 3316 3317 3318
    UnalignedStoreRepresentation rep(memtype.representation());
    store =
        graph()->NewNode(jsgraph()->machine()->UnalignedStore(rep),
                         MemBuffer(offset), index, val, *effect_, *control_);
3319 3320
  }

3321 3322
  *effect_ = store;

3323 3324 3325
  return store;
}

3326 3327 3328 3329
Node* WasmGraphBuilder::BuildAsmjsLoadMem(MachineType type, Node* index) {
  // TODO(turbofan): fold bounds checks for constant asm.js loads.
  // asm.js semantics use CheckedLoad (i.e. OOB reads return 0ish).
  const Operator* op = jsgraph()->machine()->CheckedLoad(type);
3330 3331
  Node* load =
      graph()->NewNode(op, MemBuffer(0), index, MemSize(), *effect_, *control_);
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
  *effect_ = load;
  return load;
}

Node* WasmGraphBuilder::BuildAsmjsStoreMem(MachineType type, Node* index,
                                           Node* val) {
  // TODO(turbofan): fold bounds checks for constant asm.js stores.
  // asm.js semantics use CheckedStore (i.e. ignore OOB writes).
  const Operator* op =
      jsgraph()->machine()->CheckedStore(type.representation());
3342
  Node* store = graph()->NewNode(op, MemBuffer(0), index, MemSize(), val,
3343 3344 3345 3346
                                 *effect_, *control_);
  *effect_ = store;
  return val;
}
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358

void WasmGraphBuilder::PrintDebugName(Node* node) {
  PrintF("#%d:%s", node->id(), node->op()->mnemonic());
}

Node* WasmGraphBuilder::String(const char* string) {
  return jsgraph()->Constant(
      jsgraph()->isolate()->factory()->NewStringFromAsciiChecked(string));
}

Graph* WasmGraphBuilder::graph() { return jsgraph()->graph(); }

3359 3360 3361 3362 3363
void WasmGraphBuilder::LowerInt64() {
  if (!jsgraph()->machine()->Is32()) return;
  Int64Lowering r(jsgraph()->graph(), jsgraph()->machine(), jsgraph()->common(),
                  jsgraph()->zone(), sig_);
  r.LowerGraph();
3364
}
3365

3366
void WasmGraphBuilder::SimdScalarLoweringForTesting() {
3367
  SimdScalarLowering(jsgraph(), sig_).LowerGraph();
3368 3369
}

3370 3371 3372
void WasmGraphBuilder::SetSourcePosition(Node* node,
                                         wasm::WasmCodePosition position) {
  DCHECK_NE(position, wasm::kNoCodePosition);
3373
  if (source_position_table_)
3374
    source_position_table_->SetSourcePosition(node, SourcePosition(position));
3375 3376
}

3377
Node* WasmGraphBuilder::S128Zero() {
3378
  has_simd_ = true;
3379
  return graph()->NewNode(jsgraph()->machine()->S128Zero());
3380 3381
}

3382
Node* WasmGraphBuilder::SimdOp(wasm::WasmOpcode opcode, Node* const* inputs) {
3383
  has_simd_ = true;
3384
  switch (opcode) {
3385
    case wasm::kExprF32x4Splat:
3386
      return graph()->NewNode(jsgraph()->machine()->F32x4Splat(), inputs[0]);
3387
    case wasm::kExprF32x4SConvertI32x4:
3388
      return graph()->NewNode(jsgraph()->machine()->F32x4SConvertI32x4(),
3389
                              inputs[0]);
3390
    case wasm::kExprF32x4UConvertI32x4:
3391
      return graph()->NewNode(jsgraph()->machine()->F32x4UConvertI32x4(),
3392
                              inputs[0]);
3393
    case wasm::kExprF32x4Abs:
3394
      return graph()->NewNode(jsgraph()->machine()->F32x4Abs(), inputs[0]);
3395
    case wasm::kExprF32x4Neg:
3396
      return graph()->NewNode(jsgraph()->machine()->F32x4Neg(), inputs[0]);
3397
    case wasm::kExprF32x4RecipApprox:
3398
      return graph()->NewNode(jsgraph()->machine()->F32x4RecipApprox(),
3399 3400
                              inputs[0]);
    case wasm::kExprF32x4RecipSqrtApprox:
3401
      return graph()->NewNode(jsgraph()->machine()->F32x4RecipSqrtApprox(),
3402
                              inputs[0]);
3403
    case wasm::kExprF32x4Add:
3404
      return graph()->NewNode(jsgraph()->machine()->F32x4Add(), inputs[0],
3405
                              inputs[1]);
3406 3407 3408
    case wasm::kExprF32x4AddHoriz:
      return graph()->NewNode(jsgraph()->machine()->F32x4AddHoriz(), inputs[0],
                              inputs[1]);
3409
    case wasm::kExprF32x4Sub:
3410
      return graph()->NewNode(jsgraph()->machine()->F32x4Sub(), inputs[0],
3411
                              inputs[1]);
3412
    case wasm::kExprF32x4Mul:
3413
      return graph()->NewNode(jsgraph()->machine()->F32x4Mul(), inputs[0],
3414 3415
                              inputs[1]);
    case wasm::kExprF32x4Min:
3416
      return graph()->NewNode(jsgraph()->machine()->F32x4Min(), inputs[0],
3417 3418
                              inputs[1]);
    case wasm::kExprF32x4Max:
3419
      return graph()->NewNode(jsgraph()->machine()->F32x4Max(), inputs[0],
3420
                              inputs[1]);
3421
    case wasm::kExprF32x4Eq:
3422
      return graph()->NewNode(jsgraph()->machine()->F32x4Eq(), inputs[0],
3423 3424
                              inputs[1]);
    case wasm::kExprF32x4Ne:
3425 3426
      return graph()->NewNode(jsgraph()->machine()->F32x4Ne(), inputs[0],
                              inputs[1]);
3427
    case wasm::kExprF32x4Lt:
3428 3429
      return graph()->NewNode(jsgraph()->machine()->F32x4Lt(), inputs[0],
                              inputs[1]);
3430
    case wasm::kExprF32x4Le:
3431 3432
      return graph()->NewNode(jsgraph()->machine()->F32x4Le(), inputs[0],
                              inputs[1]);
3433
    case wasm::kExprF32x4Gt:
3434 3435
      return graph()->NewNode(jsgraph()->machine()->F32x4Lt(), inputs[1],
                              inputs[0]);
3436
    case wasm::kExprF32x4Ge:
3437 3438
      return graph()->NewNode(jsgraph()->machine()->F32x4Le(), inputs[1],
                              inputs[0]);
3439
    case wasm::kExprI32x4Splat:
3440
      return graph()->NewNode(jsgraph()->machine()->I32x4Splat(), inputs[0]);
3441
    case wasm::kExprI32x4SConvertF32x4:
3442
      return graph()->NewNode(jsgraph()->machine()->I32x4SConvertF32x4(),
3443
                              inputs[0]);
3444
    case wasm::kExprI32x4UConvertF32x4:
3445
      return graph()->NewNode(jsgraph()->machine()->I32x4UConvertF32x4(),
3446
                              inputs[0]);
3447 3448 3449 3450 3451 3452
    case wasm::kExprI32x4SConvertI16x8Low:
      return graph()->NewNode(jsgraph()->machine()->I32x4SConvertI16x8Low(),
                              inputs[0]);
    case wasm::kExprI32x4SConvertI16x8High:
      return graph()->NewNode(jsgraph()->machine()->I32x4SConvertI16x8High(),
                              inputs[0]);
3453
    case wasm::kExprI32x4Neg:
3454
      return graph()->NewNode(jsgraph()->machine()->I32x4Neg(), inputs[0]);
3455
    case wasm::kExprI32x4Add:
3456
      return graph()->NewNode(jsgraph()->machine()->I32x4Add(), inputs[0],
3457
                              inputs[1]);
3458 3459 3460
    case wasm::kExprI32x4AddHoriz:
      return graph()->NewNode(jsgraph()->machine()->I32x4AddHoriz(), inputs[0],
                              inputs[1]);
3461
    case wasm::kExprI32x4Sub:
3462
      return graph()->NewNode(jsgraph()->machine()->I32x4Sub(), inputs[0],
3463
                              inputs[1]);
3464
    case wasm::kExprI32x4Mul:
3465
      return graph()->NewNode(jsgraph()->machine()->I32x4Mul(), inputs[0],
3466 3467
                              inputs[1]);
    case wasm::kExprI32x4MinS:
3468
      return graph()->NewNode(jsgraph()->machine()->I32x4MinS(), inputs[0],
3469 3470
                              inputs[1]);
    case wasm::kExprI32x4MaxS:
3471
      return graph()->NewNode(jsgraph()->machine()->I32x4MaxS(), inputs[0],
3472
                              inputs[1]);
3473
    case wasm::kExprI32x4Eq:
3474
      return graph()->NewNode(jsgraph()->machine()->I32x4Eq(), inputs[0],
3475
                              inputs[1]);
3476
    case wasm::kExprI32x4Ne:
3477 3478
      return graph()->NewNode(jsgraph()->machine()->I32x4Ne(), inputs[0],
                              inputs[1]);
3479
    case wasm::kExprI32x4LtS:
3480 3481
      return graph()->NewNode(jsgraph()->machine()->I32x4GtS(), inputs[1],
                              inputs[0]);
3482
    case wasm::kExprI32x4LeS:
3483
      return graph()->NewNode(jsgraph()->machine()->I32x4GeS(), inputs[1],
3484
                              inputs[0]);
3485 3486 3487
    case wasm::kExprI32x4GtS:
      return graph()->NewNode(jsgraph()->machine()->I32x4GtS(), inputs[0],
                              inputs[1]);
3488
    case wasm::kExprI32x4GeS:
3489 3490
      return graph()->NewNode(jsgraph()->machine()->I32x4GeS(), inputs[0],
                              inputs[1]);
3491 3492 3493 3494 3495 3496
    case wasm::kExprI32x4UConvertI16x8Low:
      return graph()->NewNode(jsgraph()->machine()->I32x4UConvertI16x8Low(),
                              inputs[0]);
    case wasm::kExprI32x4UConvertI16x8High:
      return graph()->NewNode(jsgraph()->machine()->I32x4UConvertI16x8High(),
                              inputs[0]);
3497
    case wasm::kExprI32x4MinU:
3498
      return graph()->NewNode(jsgraph()->machine()->I32x4MinU(), inputs[0],
3499 3500
                              inputs[1]);
    case wasm::kExprI32x4MaxU:
3501
      return graph()->NewNode(jsgraph()->machine()->I32x4MaxU(), inputs[0],
3502
                              inputs[1]);
3503
    case wasm::kExprI32x4LtU:
3504 3505
      return graph()->NewNode(jsgraph()->machine()->I32x4GtU(), inputs[1],
                              inputs[0]);
3506
    case wasm::kExprI32x4LeU:
3507
      return graph()->NewNode(jsgraph()->machine()->I32x4GeU(), inputs[1],
3508
                              inputs[0]);
3509 3510 3511
    case wasm::kExprI32x4GtU:
      return graph()->NewNode(jsgraph()->machine()->I32x4GtU(), inputs[0],
                              inputs[1]);
3512
    case wasm::kExprI32x4GeU:
3513 3514
      return graph()->NewNode(jsgraph()->machine()->I32x4GeU(), inputs[0],
                              inputs[1]);
3515
    case wasm::kExprI16x8Splat:
3516
      return graph()->NewNode(jsgraph()->machine()->I16x8Splat(), inputs[0]);
3517 3518 3519 3520 3521 3522
    case wasm::kExprI16x8SConvertI8x16Low:
      return graph()->NewNode(jsgraph()->machine()->I16x8SConvertI8x16Low(),
                              inputs[0]);
    case wasm::kExprI16x8SConvertI8x16High:
      return graph()->NewNode(jsgraph()->machine()->I16x8SConvertI8x16High(),
                              inputs[0]);
3523
    case wasm::kExprI16x8Neg:
3524
      return graph()->NewNode(jsgraph()->machine()->I16x8Neg(), inputs[0]);
3525 3526 3527
    case wasm::kExprI16x8SConvertI32x4:
      return graph()->NewNode(jsgraph()->machine()->I16x8SConvertI32x4(),
                              inputs[0], inputs[1]);
3528
    case wasm::kExprI16x8Add:
3529
      return graph()->NewNode(jsgraph()->machine()->I16x8Add(), inputs[0],
3530
                              inputs[1]);
3531
    case wasm::kExprI16x8AddSaturateS:
3532
      return graph()->NewNode(jsgraph()->machine()->I16x8AddSaturateS(),
3533
                              inputs[0], inputs[1]);
3534 3535 3536
    case wasm::kExprI16x8AddHoriz:
      return graph()->NewNode(jsgraph()->machine()->I16x8AddHoriz(), inputs[0],
                              inputs[1]);
3537
    case wasm::kExprI16x8Sub:
3538
      return graph()->NewNode(jsgraph()->machine()->I16x8Sub(), inputs[0],
3539
                              inputs[1]);
3540
    case wasm::kExprI16x8SubSaturateS:
3541
      return graph()->NewNode(jsgraph()->machine()->I16x8SubSaturateS(),
3542
                              inputs[0], inputs[1]);
3543
    case wasm::kExprI16x8Mul:
3544
      return graph()->NewNode(jsgraph()->machine()->I16x8Mul(), inputs[0],
3545 3546
                              inputs[1]);
    case wasm::kExprI16x8MinS:
3547
      return graph()->NewNode(jsgraph()->machine()->I16x8MinS(), inputs[0],
3548 3549
                              inputs[1]);
    case wasm::kExprI16x8MaxS:
3550
      return graph()->NewNode(jsgraph()->machine()->I16x8MaxS(), inputs[0],
3551 3552
                              inputs[1]);
    case wasm::kExprI16x8Eq:
3553
      return graph()->NewNode(jsgraph()->machine()->I16x8Eq(), inputs[0],
3554 3555
                              inputs[1]);
    case wasm::kExprI16x8Ne:
3556 3557
      return graph()->NewNode(jsgraph()->machine()->I16x8Ne(), inputs[0],
                              inputs[1]);
3558
    case wasm::kExprI16x8LtS:
3559 3560
      return graph()->NewNode(jsgraph()->machine()->I16x8GtS(), inputs[1],
                              inputs[0]);
3561
    case wasm::kExprI16x8LeS:
3562
      return graph()->NewNode(jsgraph()->machine()->I16x8GeS(), inputs[1],
3563
                              inputs[0]);
3564 3565 3566
    case wasm::kExprI16x8GtS:
      return graph()->NewNode(jsgraph()->machine()->I16x8GtS(), inputs[0],
                              inputs[1]);
3567
    case wasm::kExprI16x8GeS:
3568 3569
      return graph()->NewNode(jsgraph()->machine()->I16x8GeS(), inputs[0],
                              inputs[1]);
3570 3571 3572 3573 3574 3575 3576 3577 3578
    case wasm::kExprI16x8UConvertI8x16Low:
      return graph()->NewNode(jsgraph()->machine()->I16x8UConvertI8x16Low(),
                              inputs[0]);
    case wasm::kExprI16x8UConvertI8x16High:
      return graph()->NewNode(jsgraph()->machine()->I16x8UConvertI8x16High(),
                              inputs[0]);
    case wasm::kExprI16x8UConvertI32x4:
      return graph()->NewNode(jsgraph()->machine()->I16x8UConvertI32x4(),
                              inputs[0], inputs[1]);
3579
    case wasm::kExprI16x8AddSaturateU:
3580
      return graph()->NewNode(jsgraph()->machine()->I16x8AddSaturateU(),
3581 3582
                              inputs[0], inputs[1]);
    case wasm::kExprI16x8SubSaturateU:
3583
      return graph()->NewNode(jsgraph()->machine()->I16x8SubSaturateU(),
3584 3585
                              inputs[0], inputs[1]);
    case wasm::kExprI16x8MinU:
3586
      return graph()->NewNode(jsgraph()->machine()->I16x8MinU(), inputs[0],
3587 3588
                              inputs[1]);
    case wasm::kExprI16x8MaxU:
3589
      return graph()->NewNode(jsgraph()->machine()->I16x8MaxU(), inputs[0],
3590
                              inputs[1]);
3591
    case wasm::kExprI16x8LtU:
3592 3593
      return graph()->NewNode(jsgraph()->machine()->I16x8GtU(), inputs[1],
                              inputs[0]);
3594
    case wasm::kExprI16x8LeU:
3595
      return graph()->NewNode(jsgraph()->machine()->I16x8GeU(), inputs[1],
3596
                              inputs[0]);
3597 3598 3599
    case wasm::kExprI16x8GtU:
      return graph()->NewNode(jsgraph()->machine()->I16x8GtU(), inputs[0],
                              inputs[1]);
3600
    case wasm::kExprI16x8GeU:
3601 3602
      return graph()->NewNode(jsgraph()->machine()->I16x8GeU(), inputs[0],
                              inputs[1]);
3603
    case wasm::kExprI8x16Splat:
3604
      return graph()->NewNode(jsgraph()->machine()->I8x16Splat(), inputs[0]);
3605
    case wasm::kExprI8x16Neg:
3606
      return graph()->NewNode(jsgraph()->machine()->I8x16Neg(), inputs[0]);
3607 3608 3609
    case wasm::kExprI8x16SConvertI16x8:
      return graph()->NewNode(jsgraph()->machine()->I8x16SConvertI16x8(),
                              inputs[0], inputs[1]);
3610
    case wasm::kExprI8x16Add:
3611
      return graph()->NewNode(jsgraph()->machine()->I8x16Add(), inputs[0],
3612
                              inputs[1]);
3613
    case wasm::kExprI8x16AddSaturateS:
3614
      return graph()->NewNode(jsgraph()->machine()->I8x16AddSaturateS(),
3615
                              inputs[0], inputs[1]);
3616
    case wasm::kExprI8x16Sub:
3617
      return graph()->NewNode(jsgraph()->machine()->I8x16Sub(), inputs[0],
3618
                              inputs[1]);
3619
    case wasm::kExprI8x16SubSaturateS:
3620
      return graph()->NewNode(jsgraph()->machine()->I8x16SubSaturateS(),
3621
                              inputs[0], inputs[1]);
3622
    case wasm::kExprI8x16Mul:
3623
      return graph()->NewNode(jsgraph()->machine()->I8x16Mul(), inputs[0],
3624 3625
                              inputs[1]);
    case wasm::kExprI8x16MinS:
3626
      return graph()->NewNode(jsgraph()->machine()->I8x16MinS(), inputs[0],
3627 3628
                              inputs[1]);
    case wasm::kExprI8x16MaxS:
3629
      return graph()->NewNode(jsgraph()->machine()->I8x16MaxS(), inputs[0],
3630 3631
                              inputs[1]);
    case wasm::kExprI8x16Eq:
3632
      return graph()->NewNode(jsgraph()->machine()->I8x16Eq(), inputs[0],
3633 3634
                              inputs[1]);
    case wasm::kExprI8x16Ne:
3635 3636
      return graph()->NewNode(jsgraph()->machine()->I8x16Ne(), inputs[0],
                              inputs[1]);
3637
    case wasm::kExprI8x16LtS:
3638 3639
      return graph()->NewNode(jsgraph()->machine()->I8x16GtS(), inputs[1],
                              inputs[0]);
3640
    case wasm::kExprI8x16LeS:
3641
      return graph()->NewNode(jsgraph()->machine()->I8x16GeS(), inputs[1],
3642
                              inputs[0]);
3643 3644 3645
    case wasm::kExprI8x16GtS:
      return graph()->NewNode(jsgraph()->machine()->I8x16GtS(), inputs[0],
                              inputs[1]);
3646
    case wasm::kExprI8x16GeS:
3647 3648
      return graph()->NewNode(jsgraph()->machine()->I8x16GeS(), inputs[0],
                              inputs[1]);
3649 3650 3651
    case wasm::kExprI8x16UConvertI16x8:
      return graph()->NewNode(jsgraph()->machine()->I8x16UConvertI16x8(),
                              inputs[0], inputs[1]);
3652
    case wasm::kExprI8x16AddSaturateU:
3653
      return graph()->NewNode(jsgraph()->machine()->I8x16AddSaturateU(),
3654 3655
                              inputs[0], inputs[1]);
    case wasm::kExprI8x16SubSaturateU:
3656
      return graph()->NewNode(jsgraph()->machine()->I8x16SubSaturateU(),
3657 3658
                              inputs[0], inputs[1]);
    case wasm::kExprI8x16MinU:
3659
      return graph()->NewNode(jsgraph()->machine()->I8x16MinU(), inputs[0],
3660 3661
                              inputs[1]);
    case wasm::kExprI8x16MaxU:
3662
      return graph()->NewNode(jsgraph()->machine()->I8x16MaxU(), inputs[0],
3663
                              inputs[1]);
3664
    case wasm::kExprI8x16LtU:
3665 3666
      return graph()->NewNode(jsgraph()->machine()->I8x16GtU(), inputs[1],
                              inputs[0]);
3667
    case wasm::kExprI8x16LeU:
3668
      return graph()->NewNode(jsgraph()->machine()->I8x16GeU(), inputs[1],
3669
                              inputs[0]);
3670 3671 3672
    case wasm::kExprI8x16GtU:
      return graph()->NewNode(jsgraph()->machine()->I8x16GtU(), inputs[0],
                              inputs[1]);
3673
    case wasm::kExprI8x16GeU:
3674 3675
      return graph()->NewNode(jsgraph()->machine()->I8x16GeU(), inputs[0],
                              inputs[1]);
3676
    case wasm::kExprS128And:
3677
      return graph()->NewNode(jsgraph()->machine()->S128And(), inputs[0],
3678 3679
                              inputs[1]);
    case wasm::kExprS128Or:
3680
      return graph()->NewNode(jsgraph()->machine()->S128Or(), inputs[0],
3681 3682
                              inputs[1]);
    case wasm::kExprS128Xor:
3683
      return graph()->NewNode(jsgraph()->machine()->S128Xor(), inputs[0],
3684 3685
                              inputs[1]);
    case wasm::kExprS128Not:
3686
      return graph()->NewNode(jsgraph()->machine()->S128Not(), inputs[0]);
3687 3688
    case wasm::kExprS128Select:
      return graph()->NewNode(jsgraph()->machine()->S128Select(), inputs[0],
3689
                              inputs[1], inputs[2]);
3690
    case wasm::kExprS1x4AnyTrue:
3691
      return graph()->NewNode(jsgraph()->machine()->S1x4AnyTrue(), inputs[0]);
3692
    case wasm::kExprS1x4AllTrue:
3693
      return graph()->NewNode(jsgraph()->machine()->S1x4AllTrue(), inputs[0]);
3694
    case wasm::kExprS1x8AnyTrue:
3695
      return graph()->NewNode(jsgraph()->machine()->S1x8AnyTrue(), inputs[0]);
3696
    case wasm::kExprS1x8AllTrue:
3697
      return graph()->NewNode(jsgraph()->machine()->S1x8AllTrue(), inputs[0]);
3698
    case wasm::kExprS1x16AnyTrue:
3699
      return graph()->NewNode(jsgraph()->machine()->S1x16AnyTrue(), inputs[0]);
3700
    case wasm::kExprS1x16AllTrue:
3701
      return graph()->NewNode(jsgraph()->machine()->S1x16AllTrue(), inputs[0]);
3702
    default:
3703
      FATAL_UNSUPPORTED_OPCODE(opcode);
3704 3705 3706
  }
}

3707
Node* WasmGraphBuilder::SimdLaneOp(wasm::WasmOpcode opcode, uint8_t lane,
3708
                                   Node* const* inputs) {
3709
  has_simd_ = true;
3710
  switch (opcode) {
3711
    case wasm::kExprF32x4ExtractLane:
3712
      return graph()->NewNode(jsgraph()->machine()->F32x4ExtractLane(lane),
3713 3714
                              inputs[0]);
    case wasm::kExprF32x4ReplaceLane:
3715
      return graph()->NewNode(jsgraph()->machine()->F32x4ReplaceLane(lane),
3716
                              inputs[0], inputs[1]);
3717
    case wasm::kExprI32x4ExtractLane:
3718
      return graph()->NewNode(jsgraph()->machine()->I32x4ExtractLane(lane),
3719
                              inputs[0]);
3720
    case wasm::kExprI32x4ReplaceLane:
3721
      return graph()->NewNode(jsgraph()->machine()->I32x4ReplaceLane(lane),
3722
                              inputs[0], inputs[1]);
3723
    case wasm::kExprI16x8ExtractLane:
3724
      return graph()->NewNode(jsgraph()->machine()->I16x8ExtractLane(lane),
3725
                              inputs[0]);
3726
    case wasm::kExprI16x8ReplaceLane:
3727
      return graph()->NewNode(jsgraph()->machine()->I16x8ReplaceLane(lane),
3728 3729
                              inputs[0], inputs[1]);
    case wasm::kExprI8x16ExtractLane:
3730
      return graph()->NewNode(jsgraph()->machine()->I8x16ExtractLane(lane),
3731 3732
                              inputs[0]);
    case wasm::kExprI8x16ReplaceLane:
3733
      return graph()->NewNode(jsgraph()->machine()->I8x16ReplaceLane(lane),
3734
                              inputs[0], inputs[1]);
3735
    default:
3736
      FATAL_UNSUPPORTED_OPCODE(opcode);
3737 3738 3739
  }
}

3740
Node* WasmGraphBuilder::SimdShiftOp(wasm::WasmOpcode opcode, uint8_t shift,
3741
                                    Node* const* inputs) {
3742 3743 3744
  has_simd_ = true;
  switch (opcode) {
    case wasm::kExprI32x4Shl:
3745
      return graph()->NewNode(jsgraph()->machine()->I32x4Shl(shift), inputs[0]);
3746
    case wasm::kExprI32x4ShrS:
3747 3748
      return graph()->NewNode(jsgraph()->machine()->I32x4ShrS(shift),
                              inputs[0]);
3749
    case wasm::kExprI32x4ShrU:
3750 3751
      return graph()->NewNode(jsgraph()->machine()->I32x4ShrU(shift),
                              inputs[0]);
3752
    case wasm::kExprI16x8Shl:
3753
      return graph()->NewNode(jsgraph()->machine()->I16x8Shl(shift), inputs[0]);
3754
    case wasm::kExprI16x8ShrS:
3755 3756
      return graph()->NewNode(jsgraph()->machine()->I16x8ShrS(shift),
                              inputs[0]);
3757
    case wasm::kExprI16x8ShrU:
3758 3759
      return graph()->NewNode(jsgraph()->machine()->I16x8ShrU(shift),
                              inputs[0]);
3760
    case wasm::kExprI8x16Shl:
3761
      return graph()->NewNode(jsgraph()->machine()->I8x16Shl(shift), inputs[0]);
3762
    case wasm::kExprI8x16ShrS:
3763 3764
      return graph()->NewNode(jsgraph()->machine()->I8x16ShrS(shift),
                              inputs[0]);
3765
    case wasm::kExprI8x16ShrU:
3766 3767
      return graph()->NewNode(jsgraph()->machine()->I8x16ShrU(shift),
                              inputs[0]);
3768
    default:
3769
      FATAL_UNSUPPORTED_OPCODE(opcode);
3770 3771 3772
  }
}

3773 3774
Node* WasmGraphBuilder::Simd8x16ShuffleOp(const uint8_t shuffle[16],
                                          Node* const* inputs) {
3775
  has_simd_ = true;
3776 3777
  return graph()->NewNode(jsgraph()->machine()->S8x16Shuffle(shuffle),
                          inputs[0], inputs[1]);
3778 3779
}

3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
#define ATOMIC_BINOP_LIST(V)              \
  V(I32AtomicAdd, Add, Uint32)            \
  V(I32AtomicSub, Sub, Uint32)            \
  V(I32AtomicAnd, And, Uint32)            \
  V(I32AtomicOr, Or, Uint32)              \
  V(I32AtomicXor, Xor, Uint32)            \
  V(I32AtomicExchange, Exchange, Uint32)  \
  V(I32AtomicAdd8U, Add, Uint8)           \
  V(I32AtomicSub8U, Sub, Uint8)           \
  V(I32AtomicAnd8U, And, Uint8)           \
  V(I32AtomicOr8U, Or, Uint8)             \
  V(I32AtomicXor8U, Xor, Uint8)           \
  V(I32AtomicExchange8U, Exchange, Uint8) \
  V(I32AtomicAdd16U, Add, Uint16)         \
  V(I32AtomicSub16U, Sub, Uint16)         \
  V(I32AtomicAnd16U, And, Uint16)         \
  V(I32AtomicOr16U, Or, Uint16)           \
  V(I32AtomicXor16U, Xor, Uint16)         \
  V(I32AtomicExchange16U, Exchange, Uint16)

#define ATOMIC_TERNARY_LIST(V)                          \
  V(I32AtomicCompareExchange, CompareExchange, Uint32)  \
  V(I32AtomicCompareExchange8U, CompareExchange, Uint8) \
  V(I32AtomicCompareExchange16U, CompareExchange, Uint16)
3804

3805
Node* WasmGraphBuilder::AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs,
3806 3807 3808
                                 wasm::WasmCodePosition position) {
  Node* node;
  switch (opcode) {
3809 3810 3811 3812 3813 3814 3815 3816 3817 3818
#define BUILD_ATOMIC_BINOP(Name, Operation, Type)                     \
  case wasm::kExpr##Name: {                                           \
    BoundsCheckMem(MachineType::Type(), inputs[0], 0, position);      \
    node = graph()->NewNode(                                          \
        jsgraph()->machine()->Atomic##Operation(MachineType::Type()), \
        MemBuffer(0), inputs[0], inputs[1], *effect_, *control_);     \
    break;                                                            \
  }
    ATOMIC_BINOP_LIST(BUILD_ATOMIC_BINOP)
#undef BUILD_ATOMIC_BINOP
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829

#define BUILD_ATOMIC_TERNARY_OP(Name, Operation, Type)                       \
  case wasm::kExpr##Name: {                                                  \
    BoundsCheckMem(MachineType::Type(), inputs[0], 0, position);             \
    node = graph()->NewNode(                                                 \
        jsgraph()->machine()->Atomic##Operation(MachineType::Type()),        \
        MemBuffer(0), inputs[0], inputs[1], inputs[2], *effect_, *control_); \
    break;                                                                   \
  }
    ATOMIC_TERNARY_LIST(BUILD_ATOMIC_TERNARY_OP)
#undef BUILD_ATOMIC_TERNARY_OP
3830 3831 3832 3833 3834 3835 3836
    default:
      FATAL_UNSUPPORTED_OPCODE(opcode);
  }
  *effect_ = node;
  return node;
}

3837
static void RecordFunctionCompilation(CodeEventListener::LogEventsAndTags tag,
3838
                                      Isolate* isolate, Handle<Code> code,
3839
                                      const char* message, uint32_t index,
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
                                      const wasm::WasmName& module_name,
                                      const wasm::WasmName& func_name) {
  DCHECK(isolate->logger()->is_logging_code_events() ||
         isolate->is_profiling());

  ScopedVector<char> buffer(128);
  SNPrintF(buffer, "%s#%d:%.*s:%.*s", message, index, module_name.length(),
           module_name.start(), func_name.length(), func_name.start());
  Handle<String> name_str =
      isolate->factory()->NewStringFromAsciiChecked(buffer.start());
  Handle<String> script_str =
3851
      isolate->factory()->NewStringFromAsciiChecked("(wasm)");
3852 3853 3854 3855 3856 3857
  Handle<SharedFunctionInfo> shared =
      isolate->factory()->NewSharedFunctionInfo(name_str, code, false);
  PROFILE(isolate, CodeCreateEvent(tag, AbstractCode::cast(*code), *shared,
                                   *script_str, 0, 0));
}

3858
Handle<Code> CompileJSToWasmWrapper(Isolate* isolate, wasm::WasmModule* module,
3859
                                    Handle<Code> wasm_code, uint32_t index) {
3860
  const wasm::WasmFunction* func = &module->functions[index];
3861 3862 3863 3864

  //----------------------------------------------------------------------------
  // Create the Graph
  //----------------------------------------------------------------------------
3865
  Zone zone(isolate->allocator(), ZONE_NAME);
3866 3867 3868
  Graph graph(&zone);
  CommonOperatorBuilder common(&zone);
  MachineOperatorBuilder machine(&zone);
3869
  JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine);
3870 3871 3872 3873

  Node* control = nullptr;
  Node* effect = nullptr;

3874 3875
  // TODO(titzer): compile JS to WASM wrappers without a {ModuleEnv}.
  ModuleEnv env = {module,
3876 3877
                   std::vector<Address>(),              // function_tables
                   std::vector<Address>(),              // signature_tables
3878 3879 3880 3881 3882 3883 3884 3885
                   std::vector<wasm::SignatureMap*>(),  // signature_maps
                   std::vector<Handle<Code>>(),         // function_code
                   BUILTIN_CODE(isolate, Illegal),      // default_function_code
                   0,
                   0,
                   0};

  WasmGraphBuilder builder(&env, &zone, &jsgraph,
3886
                           CEntryStub(isolate, 1).GetCode(), func->sig);
3887 3888
  builder.set_control_ptr(&control);
  builder.set_effect_ptr(&effect);
3889
  builder.BuildJSToWasmWrapper(wasm_code);
3890 3891 3892 3893

  //----------------------------------------------------------------------------
  // Run the compilation pipeline.
  //----------------------------------------------------------------------------
3894 3895 3896 3897 3898 3899 3900
  if (FLAG_trace_turbo_graph) {  // Simple textual RPO.
    OFStream os(stdout);
    os << "-- Graph after change lowering -- " << std::endl;
    os << AsRPO(graph);
  }

  // Schedule and compile to machine code.
3901 3902
  int params =
      static_cast<int>(module->functions[index].sig->parameter_count());
3903 3904 3905 3906
  CallDescriptor* incoming = Linkage::GetJSCallDescriptor(
      &zone, false, params + 1, CallDescriptor::kNoFlags);
  Code::Flags flags = Code::ComputeFlags(Code::JS_TO_WASM_FUNCTION);
  bool debugging =
mtrofin's avatar
mtrofin committed
3907
#if DEBUG
3908
      true;
mtrofin's avatar
mtrofin committed
3909
#else
3910
      FLAG_print_opt_code || FLAG_trace_turbo || FLAG_trace_turbo_graph;
mtrofin's avatar
mtrofin committed
3911
#endif
3912
  Vector<const char> func_name = ArrayVector("js-to-wasm");
mtrofin's avatar
mtrofin committed
3913

3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
  static unsigned id = 0;
  Vector<char> buffer;
  if (debugging) {
    buffer = Vector<char>::New(128);
    int chars = SNPrintF(buffer, "js-to-wasm#%d", id);
    func_name = Vector<const char>::cast(buffer.SubVector(0, chars));
  }

  CompilationInfo info(func_name, isolate, &zone, flags);
  Handle<Code> code = Pipeline::GenerateCodeForTesting(&info, incoming, &graph);
3924
#ifdef ENABLE_DISASSEMBLER
3925 3926 3927 3928
  if (FLAG_print_opt_code && !code.is_null()) {
    OFStream os(stdout);
    code->Disassemble(buffer.start(), os);
  }
3929
#endif
3930 3931 3932
  if (debugging) {
    buffer.Dispose();
  }
mtrofin's avatar
mtrofin committed
3933

3934
  if (isolate->logger()->is_logging_code_events() || isolate->is_profiling()) {
3935 3936 3937 3938 3939
    char func_name[32];
    SNPrintF(ArrayVector(func_name), "js-to-wasm#%d", func->func_index);
    RecordFunctionCompilation(CodeEventListener::FUNCTION_TAG, isolate, code,
                              "js-to-wasm", index, wasm::WasmName("export"),
                              CStrVector(func_name));
3940
  }
3941
  return code;
3942 3943
}

3944 3945 3946 3947
Handle<Code> CompileWasmToJSWrapper(
    Isolate* isolate, Handle<JSReceiver> target, wasm::FunctionSig* sig,
    uint32_t index, Handle<String> module_name, MaybeHandle<String> import_name,
    wasm::ModuleOrigin origin, Handle<FixedArray> global_js_imports_table) {
3948 3949 3950
  //----------------------------------------------------------------------------
  // Create the Graph
  //----------------------------------------------------------------------------
3951
  Zone zone(isolate->allocator(), ZONE_NAME);
3952 3953 3954
  Graph graph(&zone);
  CommonOperatorBuilder common(&zone);
  MachineOperatorBuilder machine(&zone);
3955
  JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine);
3956 3957 3958 3959

  Node* control = nullptr;
  Node* effect = nullptr;

3960 3961 3962 3963
  SourcePositionTable* source_position_table =
      origin == wasm::kAsmJsOrigin ? new (&zone) SourcePositionTable(&graph)
                                   : nullptr;

3964 3965
  WasmGraphBuilder builder(nullptr, &zone, &jsgraph,
                           CEntryStub(isolate, 1).GetCode(), sig,
3966
                           source_position_table);
3967 3968
  builder.set_control_ptr(&control);
  builder.set_effect_ptr(&effect);
3969 3970 3971
  if (builder.BuildWasmToJSWrapper(target, global_js_imports_table, index)) {
    global_js_imports_table->set(index, *target);
  }
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981

  Handle<Code> code = Handle<Code>::null();
  {
    if (FLAG_trace_turbo_graph) {  // Simple textual RPO.
      OFStream os(stdout);
      os << "-- Graph after change lowering -- " << std::endl;
      os << AsRPO(graph);
    }

    // Schedule and compile to machine code.
3982
    CallDescriptor* incoming = GetWasmCallDescriptor(&zone, sig);
3983
    if (machine.Is32()) {
3984
      incoming = GetI32WasmCallDescriptor(&zone, incoming);
3985
    }
3986
    Code::Flags flags = Code::ComputeFlags(Code::WASM_TO_JS_FUNCTION);
mtrofin's avatar
mtrofin committed
3987 3988 3989 3990 3991 3992
    bool debugging =
#if DEBUG
        true;
#else
        FLAG_print_opt_code || FLAG_trace_turbo || FLAG_trace_turbo_graph;
#endif
3993
    Vector<const char> func_name = ArrayVector("wasm-to-js");
mtrofin's avatar
mtrofin committed
3994 3995 3996 3997
    static unsigned id = 0;
    Vector<char> buffer;
    if (debugging) {
      buffer = Vector<char>::New(128);
3998 3999
      int chars = SNPrintF(buffer, "wasm-to-js#%d", id);
      func_name = Vector<const char>::cast(buffer.SubVector(0, chars));
mtrofin's avatar
mtrofin committed
4000 4001 4002
    }

    CompilationInfo info(func_name, isolate, &zone, flags);
4003 4004
    code = Pipeline::GenerateCodeForTesting(&info, incoming, &graph, nullptr,
                                            source_position_table);
4005 4006 4007 4008 4009 4010 4011 4012 4013
    Handle<FixedArray> deopt_data =
        isolate->factory()->NewFixedArray(2, TENURED);
    intptr_t loc =
        reinterpret_cast<intptr_t>(global_js_imports_table.location());
    Handle<Object> loc_handle = isolate->factory()->NewHeapNumberFromBits(loc);
    deopt_data->set(0, *loc_handle);
    Handle<Object> index_handle = isolate->factory()->NewNumberFromInt(index);
    deopt_data->set(1, *index_handle);
    code->set_deoptimization_data(*deopt_data);
4014 4015 4016 4017 4018 4019
#ifdef ENABLE_DISASSEMBLER
    if (FLAG_print_opt_code && !code.is_null()) {
      OFStream os(stdout);
      code->Disassemble(buffer.start(), os);
    }
#endif
mtrofin's avatar
mtrofin committed
4020 4021 4022
    if (debugging) {
      buffer.Dispose();
    }
4023
  }
4024 4025
  if (isolate->logger()->is_logging_code_events() || isolate->is_profiling()) {
    const char* function_name = nullptr;
4026
    size_t function_name_size = 0;
4027 4028
    if (!import_name.is_null()) {
      Handle<String> handle = import_name.ToHandleChecked();
4029
      function_name = handle->ToCString().get();
4030
      function_name_size = static_cast<size_t>(handle->length());
4031
    }
4032 4033 4034 4035 4036
    RecordFunctionCompilation(CodeEventListener::FUNCTION_TAG, isolate, code,
                              "wasm-to-js", index,
                              {module_name->ToCString().get(),
                               static_cast<size_t>(module_name->length())},
                              {function_name, function_name_size});
4037 4038
  }

4039 4040 4041
  return code;
}

4042 4043 4044 4045 4046 4047 4048 4049 4050
Handle<Code> CompileWasmInterpreterEntry(Isolate* isolate, uint32_t func_index,
                                         wasm::FunctionSig* sig,
                                         Handle<WasmInstanceObject> instance) {
  //----------------------------------------------------------------------------
  // Create the Graph
  //----------------------------------------------------------------------------
  Zone zone(isolate->allocator(), ZONE_NAME);
  Graph graph(&zone);
  CommonOperatorBuilder common(&zone);
4051 4052 4053 4054
  MachineOperatorBuilder machine(
      &zone, MachineType::PointerRepresentation(),
      InstructionSelector::SupportedMachineOperatorFlags(),
      InstructionSelector::AlignmentRequirements());
4055 4056 4057 4058 4059
  JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine);

  Node* control = nullptr;
  Node* effect = nullptr;

4060 4061
  WasmGraphBuilder builder(nullptr, &zone, &jsgraph,
                           CEntryStub(isolate, 1).GetCode(), sig);
4062 4063
  builder.set_control_ptr(&control);
  builder.set_effect_ptr(&effect);
4064
  builder.BuildWasmInterpreterEntry(func_index, instance);
4065 4066 4067 4068 4069 4070 4071 4072 4073 4074

  Handle<Code> code = Handle<Code>::null();
  {
    if (FLAG_trace_turbo_graph) {  // Simple textual RPO.
      OFStream os(stdout);
      os << "-- Wasm to interpreter graph -- " << std::endl;
      os << AsRPO(graph);
    }

    // Schedule and compile to machine code.
4075
    CallDescriptor* incoming = GetWasmCallDescriptor(&zone, sig);
4076
    if (machine.Is32()) {
4077
      incoming = GetI32WasmCallDescriptor(&zone, incoming);
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110
    }
    Code::Flags flags = Code::ComputeFlags(Code::WASM_INTERPRETER_ENTRY);
    EmbeddedVector<char, 32> debug_name;
    int name_len = SNPrintF(debug_name, "wasm-to-interpreter#%d", func_index);
    DCHECK(name_len > 0 && name_len < debug_name.length());
    debug_name.Truncate(name_len);
    DCHECK_EQ('\0', debug_name.start()[debug_name.length()]);

    CompilationInfo info(debug_name, isolate, &zone, flags);
    code = Pipeline::GenerateCodeForTesting(&info, incoming, &graph, nullptr);
#ifdef ENABLE_DISASSEMBLER
    if (FLAG_print_opt_code && !code.is_null()) {
      OFStream os(stdout);
      code->Disassemble(debug_name.start(), os);
    }
#endif

    if (isolate->logger()->is_logging_code_events() ||
        isolate->is_profiling()) {
      RecordFunctionCompilation(CodeEventListener::FUNCTION_TAG, isolate, code,
                                "wasm-to-interpreter", func_index,
                                wasm::WasmName("module"), debug_name);
    }
  }

  Handle<FixedArray> deopt_data = isolate->factory()->NewFixedArray(1, TENURED);
  Handle<WeakCell> weak_instance = isolate->factory()->NewWeakCell(instance);
  deopt_data->set(0, *weak_instance);
  code->set_deoptimization_data(*deopt_data);

  return code;
}

4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
Handle<Code> CompileCWasmEntry(Isolate* isolate, wasm::FunctionSig* sig) {
  Zone zone(isolate->allocator(), ZONE_NAME);
  Graph graph(&zone);
  CommonOperatorBuilder common(&zone);
  MachineOperatorBuilder machine(&zone);
  JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine);

  Node* control = nullptr;
  Node* effect = nullptr;

  WasmGraphBuilder builder(nullptr, &zone, &jsgraph,
                           CEntryStub(isolate, 1).GetCode(), sig);
  builder.set_control_ptr(&control);
  builder.set_effect_ptr(&effect);
  builder.BuildCWasmEntry();

  if (FLAG_trace_turbo_graph) {  // Simple textual RPO.
    OFStream os(stdout);
    os << "-- C Wasm entry graph -- " << std::endl;
    os << AsRPO(graph);
  }

  // Schedule and compile to machine code.
  CallDescriptor* incoming = Linkage::GetJSCallDescriptor(
      &zone, false, CWasmEntryParameters::kNumParameters + 1,
      CallDescriptor::kNoFlags);
  Code::Flags flags = Code::ComputeFlags(Code::C_WASM_ENTRY);

  // Build a name in the form "c-wasm-entry:<params>:<returns>".
  static constexpr size_t kMaxNameLen = 128;
  char debug_name[kMaxNameLen] = "c-wasm-entry:";
  size_t name_len = strlen(debug_name);
  auto append_name_char = [&](char c) {
    if (name_len + 1 < kMaxNameLen) debug_name[name_len++] = c;
  };
  for (wasm::ValueType t : sig->parameters()) {
    append_name_char(wasm::WasmOpcodes::ShortNameOf(t));
  }
  append_name_char(':');
  for (wasm::ValueType t : sig->returns()) {
    append_name_char(wasm::WasmOpcodes::ShortNameOf(t));
  }
  debug_name[name_len] = '\0';
  Vector<const char> debug_name_vec(debug_name, name_len);

  CompilationInfo info(debug_name_vec, isolate, &zone, flags);
  Handle<Code> code = Pipeline::GenerateCodeForTesting(&info, incoming, &graph);
#ifdef ENABLE_DISASSEMBLER
  if (FLAG_print_opt_code && !code.is_null()) {
    OFStream os(stdout);
    code->Disassemble(debug_name, os);
  }
#endif

  return code;
}

4168
SourcePositionTable* WasmCompilationUnit::BuildGraphForWasmFunction(
4169
    double* decode_ms) {
4170 4171 4172 4173 4174 4175 4176 4177 4178
#if DEBUG
  if (env_) {
    size_t tables_size = env_->module->function_tables.size();
    DCHECK_EQ(tables_size, env_->function_tables.size());
    DCHECK_EQ(tables_size, env_->signature_tables.size());
    DCHECK_EQ(tables_size, env_->signature_maps.size());
  }
#endif

4179 4180 4181 4182
  base::ElapsedTimer decode_timer;
  if (FLAG_trace_wasm_decode_time) {
    decode_timer.Start();
  }
4183
  // Create a TF graph during decoding.
4184

4185
  SourcePositionTable* source_position_table =
4186
      new (jsgraph_->zone()) SourcePositionTable(jsgraph_->graph());
4187
  WasmGraphBuilder builder(env_, jsgraph_->zone(), jsgraph_, centry_stub_,
4188 4189
                           func_body_.sig, source_position_table,
                           runtime_exception_support_);
4190
  graph_construction_result_ =
4191
      wasm::BuildTFGraph(isolate_->allocator(), &builder, func_body_);
4192 4193 4194 4195

  if (graph_construction_result_.failed()) {
    if (FLAG_trace_wasm_compiler) {
      OFStream os(stdout);
4196
      os << "Compilation failed: " << graph_construction_result_.error_msg()
4197
         << std::endl;
4198 4199 4200
    }
    return nullptr;
  }
4201

4202
  builder.LowerInt64();
4203

4204
  if (builder.has_simd() && !CpuFeatures::SupportsWasmSimd128()) {
4205
    SimdScalarLowering(jsgraph_, func_body_.sig).LowerGraph();
4206
  }
4207

4208 4209
  if (func_index_ >= FLAG_trace_wasm_ast_start &&
      func_index_ < FLAG_trace_wasm_ast_end) {
4210
    PrintRawWasmCode(isolate_->allocator(), func_body_, env_->module);
4211
  }
4212
  if (FLAG_trace_wasm_decode_time) {
4213 4214
    *decode_ms = decode_timer.Elapsed().InMillisecondsF();
  }
4215
  return source_position_table;
4216 4217
}

4218 4219 4220 4221 4222
namespace {
Vector<const char> GetDebugName(Zone* zone, wasm::WasmName name, int index) {
  if (!name.is_empty()) {
    return name;
  }
4223 4224 4225
#ifndef DEBUG
  return {};
#endif
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
  constexpr int kBufferLength = 15;

  EmbeddedVector<char, kBufferLength> name_vector;
  int name_len = SNPrintF(name_vector, "wasm#%d", index);
  DCHECK(name_len > 0 && name_len < name_vector.length());

  char* index_name = zone->NewArray<char>(name_len);
  memcpy(index_name, name_vector.start(), name_len);
  return Vector<const char>(index_name, name_len);
}
}  // namespace

4238 4239 4240 4241
WasmCompilationUnit::WasmCompilationUnit(
    Isolate* isolate, ModuleEnv* env, wasm::FunctionBody body,
    wasm::WasmName name, int index, Handle<Code> centry_stub,
    Counters* counters, RuntimeExceptionSupport exception_support)
4242
    : isolate_(isolate),
4243
      env_(env),
4244 4245
      func_body_(body),
      func_name_(name),
4246
      counters_(counters ? counters : isolate->counters()),
4247
      centry_stub_(centry_stub),
4248 4249
      func_index_(index),
      runtime_exception_support_(exception_support) {}
4250 4251

void WasmCompilationUnit::ExecuteCompilation() {
4252
  auto timed_histogram = env_->module->is_wasm()
4253 4254 4255
                             ? counters()->wasm_compile_wasm_function_time()
                             : counters()->wasm_compile_asm_function_time();
  TimedHistogramScope wasm_compile_function_time_scope(timed_histogram);
4256

4257
  if (FLAG_trace_wasm_compiler) {
4258
    if (func_name_.start() != nullptr) {
4259
      PrintF("Compiling wasm function %d:'%.*s'\n\n", func_index(),
4260 4261
             func_name_.length(), func_name_.start());
    } else {
4262
      PrintF("Compiling wasm function %d:<unnamed>\n\n", func_index());
4263
    }
4264 4265 4266 4267 4268
  }

  double decode_ms = 0;
  size_t node_count = 0;

4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
  // Scope for the {graph_zone}.
  {
    Zone graph_zone(isolate_->allocator(), ZONE_NAME);
    jsgraph_ = new (&graph_zone) JSGraph(
        isolate_, new (&graph_zone) Graph(&graph_zone),
        new (&graph_zone) CommonOperatorBuilder(&graph_zone), nullptr, nullptr,
        new (&graph_zone) MachineOperatorBuilder(
            &graph_zone, MachineType::PointerRepresentation(),
            InstructionSelector::SupportedMachineOperatorFlags(),
            InstructionSelector::AlignmentRequirements()));
    SourcePositionTable* source_positions =
        BuildGraphForWasmFunction(&decode_ms);
4281

4282 4283 4284 4285
    if (graph_construction_result_.failed()) {
      ok_ = false;
      return;
    }
4286

4287 4288 4289 4290 4291
    base::ElapsedTimer pipeline_timer;
    if (FLAG_trace_wasm_decode_time) {
      node_count = jsgraph_->graph()->NodeCount();
      pipeline_timer.Start();
    }
4292

4293 4294 4295
    compilation_zone_.reset(new Zone(isolate_->allocator(), ZONE_NAME));

    // Run the compiler pipeline to generate machine code.
4296 4297
    CallDescriptor* descriptor =
        GetWasmCallDescriptor(compilation_zone_.get(), func_body_.sig);
4298
    if (jsgraph_->machine()->Is32()) {
4299 4300
      descriptor =
          GetI32WasmCallDescriptor(compilation_zone_.get(), descriptor);
4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
    }
    info_.reset(new CompilationInfo(
        GetDebugName(compilation_zone_.get(), func_name_, func_index_),
        isolate_, compilation_zone_.get(),
        Code::ComputeFlags(Code::WASM_FUNCTION)));
    ZoneVector<trap_handler::ProtectedInstructionData> protected_instructions(
        compilation_zone_.get());

    job_.reset(Pipeline::NewWasmCompilationJob(
        info_.get(), jsgraph_, descriptor, source_positions,
4311
        &protected_instructions, env_->module->origin()));
4312 4313
    ok_ = job_->ExecuteJob() == CompilationJob::SUCCEEDED;
    // TODO(bradnelson): Improve histogram handling of size_t.
4314 4315
    counters()->wasm_compile_function_peak_memory_bytes()->AddSample(
        static_cast<int>(jsgraph_->graph()->zone()->allocation_size()));
4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332

    if (FLAG_trace_wasm_decode_time) {
      double pipeline_ms = pipeline_timer.Elapsed().InMillisecondsF();
      PrintF(
          "wasm-compilation phase 1 ok: %u bytes, %0.3f ms decode, %zu nodes, "
          "%0.3f ms pipeline\n",
          static_cast<unsigned>(func_body_.end - func_body_.start), decode_ms,
          node_count, pipeline_ms);
    }
    // The graph zone is about to get out of scope. Avoid invalid references.
    jsgraph_ = nullptr;
  }

  // Record the memory cost this unit places on the system until
  // it is finalized.
  size_t cost = job_->AllocatedMemory();
  set_memory_cost(cost);
4333 4334
}

4335
MaybeHandle<Code> WasmCompilationUnit::FinishCompilation(
4336
    wasm::ErrorThrower* thrower) {
4337
  if (!ok_) {
4338 4339 4340
    if (graph_construction_result_.failed()) {
      // Add the function as another context for the exception
      ScopedVector<char> buffer(128);
4341
      if (func_name_.start() == nullptr) {
4342
        SNPrintF(buffer, "Compiling wasm function #%d failed", func_index_);
4343
      } else {
4344 4345
        SNPrintF(buffer, "Compiling wasm function #%d:%.*s failed", func_index_,
                 func_name_.length(), func_name_.start());
4346 4347
      }
      thrower->CompileFailed(buffer.start(), graph_construction_result_);
4348 4349
    }

4350
    return {};
4351
  }
4352 4353 4354 4355
  base::ElapsedTimer codegen_timer;
  if (FLAG_trace_wasm_decode_time) {
    codegen_timer.Start();
  }
4356
  if (job_->FinalizeJob() != CompilationJob::SUCCEEDED) {
4357 4358
    return Handle<Code>::null();
  }
4359
  Handle<Code> code = info_->code();
4360 4361
  DCHECK(!code.is_null());

4362 4363
  if (isolate_->logger()->is_logging_code_events() ||
      isolate_->is_profiling()) {
4364
    RecordFunctionCompilation(CodeEventListener::FUNCTION_TAG, isolate_, code,
4365 4366
                              "WASM_function", func_index_,
                              wasm::WasmName("module"), func_name_);
4367
  }
4368

4369
  if (FLAG_trace_wasm_decode_time) {
4370 4371
    double codegen_ms = codegen_timer.Elapsed().InMillisecondsF();
    PrintF("wasm-code-generation ok: %u bytes, %0.3f ms code generation\n",
4372
           static_cast<unsigned>(func_body_.end - func_body_.start),
4373
           codegen_ms);
4374
  }
4375

4376
  return code;
4377 4378
}

4379
// static
4380
MaybeHandle<Code> WasmCompilationUnit::CompileWasmFunction(
4381
    wasm::ErrorThrower* thrower, Isolate* isolate,
4382
    const wasm::ModuleWireBytes& wire_bytes, ModuleEnv* env,
4383
    const wasm::WasmFunction* function) {
4384 4385 4386 4387 4388 4389 4390
  wasm::FunctionBody function_body{
      function->sig, function->code.offset(),
      wire_bytes.start() + function->code.offset(),
      wire_bytes.start() + function->code.end_offset()};
  WasmCompilationUnit unit(
      isolate, env, function_body, wire_bytes.GetNameOrNull(function),
      function->func_index, CEntryStub(isolate, 1).GetCode());
4391 4392 4393 4394
  unit.ExecuteCompilation();
  return unit.FinishCompilation(thrower);
}

4395 4396 4397 4398 4399
#undef WASM_64
#undef FATAL_UNSUPPORTED_OPCODE
#undef ATOMIC_BINOP_LIST
#undef ATOMIC_TERNARY_LIST

4400 4401 4402
}  // namespace compiler
}  // namespace internal
}  // namespace v8