js-typed-lowering.cc 105 KB
Newer Older
1 2 3 4
// Copyright 2014 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
#include "src/code-factory.h"
6
#include "src/compilation-dependencies.h"
7
#include "src/compiler/access-builder.h"
8
#include "src/compiler/js-graph.h"
9
#include "src/compiler/js-typed-lowering.h"
10
#include "src/compiler/linkage.h"
11
#include "src/compiler/node-matchers.h"
12 13
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
14
#include "src/compiler/state-values-utils.h"
15
#include "src/type-cache.h"
16 17 18 19 20 21
#include "src/types.h"

namespace v8 {
namespace internal {
namespace compiler {

22
namespace {
23

24 25 26 27 28
// A helper class to construct inline allocations on the simplified operator
// level. This keeps track of the effect chain for initial stores on a newly
// allocated object and also provides helpers for commonly allocated objects.
class AllocationBuilder final {
 public:
29
  AllocationBuilder(JSGraph* jsgraph, Node* effect, Node* control)
30 31 32 33 34 35
      : jsgraph_(jsgraph),
        allocation_(nullptr),
        effect_(effect),
        control_(control) {}

  // Primitive allocation of static size.
36
  void Allocate(int size, PretenureFlag pretenure = NOT_TENURED) {
37
    effect_ = graph()->NewNode(common()->BeginRegion(), effect_);
38 39 40
    allocation_ =
        graph()->NewNode(simplified()->Allocate(pretenure),
                         jsgraph()->Constant(size), effect_, control_);
41 42 43 44 45 46 47 48 49
    effect_ = allocation_;
  }

  // Primitive store into a field.
  void Store(const FieldAccess& access, Node* value) {
    effect_ = graph()->NewNode(simplified()->StoreField(access), allocation_,
                               value, effect_, control_);
  }

50 51 52 53 54 55
  // Primitive store into an element.
  void Store(ElementAccess const& access, Node* index, Node* value) {
    effect_ = graph()->NewNode(simplified()->StoreElement(access), allocation_,
                               index, value, effect_, control_);
  }

56
  // Compound allocation of a FixedArray.
57 58 59 60 61 62 63 64
  void AllocateArray(int length, Handle<Map> map,
                     PretenureFlag pretenure = NOT_TENURED) {
    DCHECK(map->instance_type() == FIXED_ARRAY_TYPE ||
           map->instance_type() == FIXED_DOUBLE_ARRAY_TYPE);
    int size = (map->instance_type() == FIXED_ARRAY_TYPE)
                   ? FixedArray::SizeFor(length)
                   : FixedDoubleArray::SizeFor(length);
    Allocate(size, pretenure);
65
    Store(AccessBuilder::ForMap(), map);
66
    Store(AccessBuilder::ForFixedArrayLength(), jsgraph()->Constant(length));
67 68 69 70 71 72 73
  }

  // Compound store of a constant into a field.
  void Store(const FieldAccess& access, Handle<Object> value) {
    Store(access, jsgraph()->Constant(value));
  }

74
  void FinishAndChange(Node* node) {
75 76 77 78
    NodeProperties::SetType(allocation_, NodeProperties::GetType(node));
    node->ReplaceInput(0, allocation_);
    node->ReplaceInput(1, effect_);
    node->TrimInputCount(2);
79 80 81 82 83
    NodeProperties::ChangeOp(node, common()->FinishRegion());
  }

  Node* Finish() {
    return graph()->NewNode(common()->FinishRegion(), allocation_, effect_);
84
  }
85 86 87 88

 protected:
  JSGraph* jsgraph() { return jsgraph_; }
  Graph* graph() { return jsgraph_->graph(); }
89 90
  CommonOperatorBuilder* common() { return jsgraph_->common(); }
  SimplifiedOperatorBuilder* simplified() { return jsgraph_->simplified(); }
91 92 93 94 95 96 97 98

 private:
  JSGraph* const jsgraph_;
  Node* allocation_;
  Node* effect_;
  Node* control_;
};

99 100
}  // namespace

101

102 103 104 105
// A helper class to simplify the process of reducing a single binop node with a
// JSOperator. This class manages the rewriting of context, control, and effect
// dependencies during lowering of a binop and contains numerous helper
// functions for matching the types of inputs to an operation.
106
class JSBinopReduction final {
107 108
 public:
  JSBinopReduction(JSTypedLowering* lowering, Node* node)
109
      : lowering_(lowering), node_(node) {}
110

111 112 113 114 115 116 117 118 119
  void ConvertInputsToNumber(Node* frame_state) {
    // To convert the inputs to numbers, we have to provide frame states
    // for lazy bailouts in the ToNumber conversions.
    // We use a little hack here: we take the frame state before the binary
    // operation and use it to construct the frame states for the conversion
    // so that after the deoptimization, the binary operation IC gets
    // already converted values from full code. This way we are sure that we
    // will not re-do any of the side effects.

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    Node* left_input = nullptr;
    Node* right_input = nullptr;
    bool left_is_primitive = left_type()->Is(Type::PlainPrimitive());
    bool right_is_primitive = right_type()->Is(Type::PlainPrimitive());
    bool handles_exception = NodeProperties::IsExceptionalCall(node_);

    if (!left_is_primitive && !right_is_primitive && handles_exception) {
      ConvertBothInputsToNumber(&left_input, &right_input, frame_state);
    } else {
      left_input = left_is_primitive
                       ? ConvertPlainPrimitiveToNumber(left())
                       : ConvertSingleInputToNumber(
                             left(), CreateFrameStateForLeftInput(frame_state));
      right_input = right_is_primitive
                        ? ConvertPlainPrimitiveToNumber(right())
                        : ConvertSingleInputToNumber(
                              right(), CreateFrameStateForRightInput(
137
                                           frame_state, left_input));
138
    }
139 140 141

    node_->ReplaceInput(0, left_input);
    node_->ReplaceInput(1, right_input);
142 143
  }

144 145 146 147
  void ConvertInputsToUI32(Signedness left_signedness,
                           Signedness right_signedness) {
    node_->ReplaceInput(0, ConvertToUI32(left(), left_signedness));
    node_->ReplaceInput(1, ConvertToUI32(right(), right_signedness));
148 149 150 151 152 153 154 155 156 157 158
  }

  void SwapInputs() {
    Node* l = left();
    Node* r = right();
    node_->ReplaceInput(0, r);
    node_->ReplaceInput(1, l);
  }

  // Remove all effect and control inputs and outputs to this node and change
  // to the pure operator {op}, possibly inserting a boolean inversion.
159 160
  Reduction ChangeToPureOperator(const Operator* op, bool invert = false,
                                 Type* type = Type::Any()) {
161
    DCHECK_EQ(0, op->EffectInputCount());
162
    DCHECK_EQ(false, OperatorProperties::HasContextInput(op));
163
    DCHECK_EQ(0, op->ControlInputCount());
164
    DCHECK_EQ(2, op->ValueInputCount());
165

166
    // Remove the effects from the node, and update its effect/control usages.
167
    if (node_->op()->EffectInputCount() > 0) {
168
      lowering_->RelaxEffectsAndControls(node_);
169
    }
170 171
    // Remove the inputs corresponding to context, effect, and control.
    NodeProperties::RemoveNonValueInputs(node_);
172
    // Finally, update the operator to the new one.
173
    NodeProperties::ChangeOp(node_, op);
174

175 176
    // TODO(jarin): Replace the explicit typing hack with a call to some method
    // that encapsulates changing the operator and re-typing.
177 178
    Type* node_type = NodeProperties::GetType(node_);
    NodeProperties::SetType(node_, Type::Intersect(node_type, type, zone()));
179

180 181 182 183 184 185
    if (invert) {
      // Insert an boolean not to invert the value.
      Node* value = graph()->NewNode(simplified()->BooleanNot(), node_);
      node_->ReplaceUses(value);
      // Note: ReplaceUses() smashes all uses, so smash it back here.
      value->ReplaceInput(0, node_);
186
      return lowering_->Replace(value);
187 188 189 190
    }
    return lowering_->Changed(node_);
  }

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  Reduction ChangeToStringComparisonOperator(const Operator* op,
                                             bool invert = false) {
    if (node_->op()->ControlInputCount() > 0) {
      lowering_->RelaxControls(node_);
    }
    // String comparison operators need effect and control inputs, so copy them
    // over.
    Node* effect = NodeProperties::GetEffectInput(node_);
    Node* control = NodeProperties::GetControlInput(node_);
    node_->ReplaceInput(2, effect);
    node_->ReplaceInput(3, control);

    node_->TrimInputCount(4);
    NodeProperties::ChangeOp(node_, op);

    if (invert) {
      // Insert a boolean-not to invert the value.
      Node* value = graph()->NewNode(simplified()->BooleanNot(), node_);
      node_->ReplaceUses(value);
      // Note: ReplaceUses() smashes all uses, so smash it back here.
      value->ReplaceInput(0, node_);
      return lowering_->Replace(value);
    }
    return lowering_->Changed(node_);
  }

217 218 219 220
  Reduction ChangeToPureOperator(const Operator* op, Type* type) {
    return ChangeToPureOperator(op, false, type);
  }

221 222 223 224 225 226 227 228 229 230
  // TODO(turbofan): Strong mode should be killed soonish!
  bool IsStrong() const {
    if (node_->opcode() == IrOpcode::kJSLessThan ||
        node_->opcode() == IrOpcode::kJSLessThanOrEqual ||
        node_->opcode() == IrOpcode::kJSGreaterThan ||
        node_->opcode() == IrOpcode::kJSGreaterThanOrEqual) {
      return is_strong(OpParameter<LanguageMode>(node_));
    }
    return is_strong(BinaryOperationParametersOf(node_->op()).language_mode());
  }
231

232
  bool LeftInputIs(Type* t) { return left_type()->Is(t); }
233

234 235 236 237 238
  bool RightInputIs(Type* t) { return right_type()->Is(t); }

  bool OneInputIs(Type* t) { return LeftInputIs(t) || RightInputIs(t); }

  bool BothInputsAre(Type* t) { return LeftInputIs(t) && RightInputIs(t); }
239

240
  bool OneInputCannotBe(Type* t) {
241
    return !left_type()->Maybe(t) || !right_type()->Maybe(t);
242 243 244
  }

  bool NeitherInputCanBe(Type* t) {
245
    return !left_type()->Maybe(t) && !right_type()->Maybe(t);
246 247 248 249 250 251 252
  }

  Node* effect() { return NodeProperties::GetEffectInput(node_); }
  Node* control() { return NodeProperties::GetControlInput(node_); }
  Node* context() { return NodeProperties::GetContextInput(node_); }
  Node* left() { return NodeProperties::GetValueInput(node_, 0); }
  Node* right() { return NodeProperties::GetValueInput(node_, 1); }
253 254
  Type* left_type() { return NodeProperties::GetType(node_->InputAt(0)); }
  Type* right_type() { return NodeProperties::GetType(node_->InputAt(1)); }
255 256

  SimplifiedOperatorBuilder* simplified() { return lowering_->simplified(); }
257
  Graph* graph() const { return lowering_->graph(); }
258 259 260
  JSGraph* jsgraph() { return lowering_->jsgraph(); }
  JSOperatorBuilder* javascript() { return lowering_->javascript(); }
  MachineOperatorBuilder* machine() { return lowering_->machine(); }
261
  CommonOperatorBuilder* common() { return jsgraph()->common(); }
262
  Zone* zone() const { return graph()->zone(); }
263 264 265 266 267

 private:
  JSTypedLowering* lowering_;  // The containing lowering instance.
  Node* node_;                 // The original node.

268
  Node* CreateFrameStateForLeftInput(Node* frame_state) {
269
    FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);
270 271 272 273 274 275

    if (state_info.bailout_id() == BailoutId::None()) {
      // Dummy frame state => just leave it as is.
      return frame_state;
    }

276 277 278 279 280 281 282 283 284 285
    // If the frame state is already the right one, just return it.
    if (state_info.state_combine().kind() == OutputFrameStateCombine::kPokeAt &&
        state_info.state_combine().GetOffsetToPokeAt() == 1) {
      return frame_state;
    }

    // Here, we smash the result of the conversion into the slot just below
    // the stack top. This is the slot that full code uses to store the
    // left operand.
    const Operator* op = jsgraph()->common()->FrameState(
286 287
        state_info.bailout_id(), OutputFrameStateCombine::PokeAt(1),
        state_info.function_info());
288

289 290 291 292 293 294 295
    return graph()->NewNode(op,
                            frame_state->InputAt(kFrameStateParametersInput),
                            frame_state->InputAt(kFrameStateLocalsInput),
                            frame_state->InputAt(kFrameStateStackInput),
                            frame_state->InputAt(kFrameStateContextInput),
                            frame_state->InputAt(kFrameStateFunctionInput),
                            frame_state->InputAt(kFrameStateOuterStateInput));
296 297 298
  }

  Node* CreateFrameStateForRightInput(Node* frame_state, Node* converted_left) {
299
    FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);
300 301 302 303 304 305 306 307 308

    if (state_info.bailout_id() == BailoutId::None()) {
      // Dummy frame state => just leave it as is.
      return frame_state;
    }

    // Create a frame state that stores the result of the operation to the
    // top of the stack (i.e., the slot used for the right operand).
    const Operator* op = jsgraph()->common()->FrameState(
309 310
        state_info.bailout_id(), OutputFrameStateCombine::PokeAt(0),
        state_info.function_info());
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

    // Change the left operand {converted_left} on the expression stack.
    Node* stack = frame_state->InputAt(2);
    DCHECK_EQ(stack->opcode(), IrOpcode::kStateValues);
    DCHECK_GE(stack->InputCount(), 2);

    // TODO(jarin) Allocate in a local zone or a reusable buffer.
    NodeVector new_values(stack->InputCount(), zone());
    for (int i = 0; i < stack->InputCount(); i++) {
      if (i == stack->InputCount() - 2) {
        new_values[i] = converted_left;
      } else {
        new_values[i] = stack->InputAt(i);
      }
    }
    Node* new_stack =
        graph()->NewNode(stack->op(), stack->InputCount(), &new_values.front());

329 330 331 332 333 334
    return graph()->NewNode(
        op, frame_state->InputAt(kFrameStateParametersInput),
        frame_state->InputAt(kFrameStateLocalsInput), new_stack,
        frame_state->InputAt(kFrameStateContextInput),
        frame_state->InputAt(kFrameStateFunctionInput),
        frame_state->InputAt(kFrameStateOuterStateInput));
335 336
  }

337
  Node* ConvertPlainPrimitiveToNumber(Node* node) {
338
    DCHECK(NodeProperties::GetType(node)->Is(Type::PlainPrimitive()));
339 340 341 342 343 344 345
    // Avoid inserting too many eager ToNumber() operations.
    Reduction const reduction = lowering_->ReduceJSToNumberInput(node);
    if (reduction.Changed()) return reduction.replacement();
    // TODO(jarin) Use PlainPrimitiveToNumber once we have it.
    return graph()->NewNode(
        javascript()->ToNumber(), node, jsgraph()->NoContextConstant(),
        jsgraph()->EmptyFrameState(), graph()->start(), graph()->start());
346 347
  }

348
  Node* ConvertSingleInputToNumber(Node* node, Node* frame_state) {
349
    DCHECK(!NodeProperties::GetType(node)->Is(Type::PlainPrimitive()));
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    Node* const n = graph()->NewNode(javascript()->ToNumber(), node, context(),
                                     frame_state, effect(), control());
    NodeProperties::ReplaceUses(node_, node_, node_, n, n);
    update_effect(n);
    return n;
  }

  void ConvertBothInputsToNumber(Node** left_result, Node** right_result,
                                 Node* frame_state) {
    Node* projections[2];

    // Find {IfSuccess} and {IfException} continuations of the operation.
    NodeProperties::CollectControlProjections(node_, projections, 2);
    IfExceptionHint hint = OpParameter<IfExceptionHint>(projections[1]);
    Node* if_exception = projections[1];
    Node* if_success = projections[0];

    // Insert two ToNumber() operations that both potentially throw.
    Node* left_state = CreateFrameStateForLeftInput(frame_state);
    Node* left_conv =
        graph()->NewNode(javascript()->ToNumber(), left(), context(),
                         left_state, effect(), control());
    Node* left_success = graph()->NewNode(common()->IfSuccess(), left_conv);
    Node* right_state = CreateFrameStateForRightInput(frame_state, left_conv);
    Node* right_conv =
        graph()->NewNode(javascript()->ToNumber(), right(), context(),
                         right_state, left_conv, left_success);
    Node* left_exception =
        graph()->NewNode(common()->IfException(hint), left_conv, left_conv);
    Node* right_exception =
        graph()->NewNode(common()->IfException(hint), right_conv, right_conv);
    NodeProperties::ReplaceControlInput(if_success, right_conv);
    update_effect(right_conv);

    // Wire conversions to existing {IfException} continuation.
    Node* exception_merge = if_exception;
    Node* exception_value =
387 388
        graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                         left_exception, right_exception, exception_merge);
389 390 391 392 393 394
    Node* exception_effect =
        graph()->NewNode(common()->EffectPhi(2), left_exception,
                         right_exception, exception_merge);
    for (Edge edge : exception_merge->use_edges()) {
      if (NodeProperties::IsEffectEdge(edge)) edge.UpdateTo(exception_effect);
      if (NodeProperties::IsValueEdge(edge)) edge.UpdateTo(exception_value);
395
    }
396
    NodeProperties::RemoveType(exception_merge);
397 398
    exception_merge->ReplaceInput(0, left_exception);
    exception_merge->ReplaceInput(1, right_exception);
399
    NodeProperties::ChangeOp(exception_merge, common()->Merge(2));
400 401 402

    *left_result = left_conv;
    *right_result = right_conv;
403 404
  }

405
  Node* ConvertToUI32(Node* node, Signedness signedness) {
406
    // Avoid introducing too many eager NumberToXXnt32() operations.
407
    Type* type = NodeProperties::GetType(node);
408 409 410 411 412 413 414 415 416 417 418
    if (signedness == kSigned) {
      if (!type->Is(Type::Signed32())) {
        node = graph()->NewNode(simplified()->NumberToInt32(), node);
      }
    } else {
      DCHECK_EQ(kUnsigned, signedness);
      if (!type->Is(Type::Unsigned32())) {
        node = graph()->NewNode(simplified()->NumberToUint32(), node);
      }
    }
    return node;
419 420 421 422 423 424 425 426
  }

  void update_effect(Node* effect) {
    NodeProperties::ReplaceEffectInput(node_, effect);
  }
};


427 428 429 430 431 432 433 434 435 436 437 438
// TODO(turbofan): js-typed-lowering improvements possible
// - immediately put in type bounds for all new nodes
// - relax effects from generic but not-side-effecting operations


JSTypedLowering::JSTypedLowering(Editor* editor,
                                 CompilationDependencies* dependencies,
                                 Flags flags, JSGraph* jsgraph, Zone* zone)
    : AdvancedReducer(editor),
      dependencies_(dependencies),
      flags_(flags),
      jsgraph_(jsgraph),
439 440
      true_type_(Type::Constant(factory()->true_value(), graph()->zone())),
      false_type_(Type::Constant(factory()->false_value(), graph()->zone())),
441 442
      the_hole_type_(
          Type::Constant(factory()->the_hole_value(), graph()->zone())),
443 444 445 446 447 448 449 450 451
      type_cache_(TypeCache::Get()) {
  for (size_t k = 0; k < arraysize(shifted_int32_ranges_); ++k) {
    double min = kMinInt / (1 << k);
    double max = kMaxInt / (1 << k);
    shifted_int32_ranges_[k] = Type::Range(min, max, graph()->zone());
  }
}


452
Reduction JSTypedLowering::ReduceJSAdd(Node* node) {
453 454
  if (flags() & kDisableBinaryOpReduction) return NoChange();

455
  JSBinopReduction r(this, node);
456 457
  if (r.BothInputsAre(Type::Number())) {
    // JSAdd(x:number, y:number) => NumberAdd(x, y)
458
    return r.ChangeToPureOperator(simplified()->NumberAdd(), Type::Number());
459
  }
460
  if (r.NeitherInputCanBe(Type::StringOrReceiver()) && !r.IsStrong()) {
461
    // JSAdd(x:-string, y:-string) => NumberAdd(ToNumber(x), ToNumber(y))
462
    Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
463
    r.ConvertInputsToNumber(frame_state);
464
    return r.ChangeToPureOperator(simplified()->NumberAdd(), Type::Number());
465
  }
466 467 468 469 470 471 472 473 474 475 476
  if (r.BothInputsAre(Type::String())) {
    // JSAdd(x:string, y:string) => CallStub[StringAdd](x, y)
    Callable const callable =
        CodeFactory::StringAdd(isolate(), STRING_ADD_CHECK_NONE, NOT_TENURED);
    CallDescriptor const* const desc = Linkage::GetStubCallDescriptor(
        isolate(), graph()->zone(), callable.descriptor(), 0,
        CallDescriptor::kNeedsFrameState, node->op()->properties());
    DCHECK_EQ(2, OperatorProperties::GetFrameStateInputCount(node->op()));
    node->RemoveInput(NodeProperties::FirstFrameStateIndex(node) + 1);
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
477
    NodeProperties::ChangeOp(node, common()->Call(desc));
478 479
    return Changed(node);
  }
480 481 482 483
  return NoChange();
}


484
Reduction JSTypedLowering::ReduceJSModulus(Node* node) {
485 486
  if (flags() & kDisableBinaryOpReduction) return NoChange();

487 488 489 490 491 492 493 494 495 496
  JSBinopReduction r(this, node);
  if (r.BothInputsAre(Type::Number())) {
    // JSModulus(x:number, x:number) => NumberModulus(x, y)
    return r.ChangeToPureOperator(simplified()->NumberModulus(),
                                  Type::Number());
  }
  return NoChange();
}


497 498
Reduction JSTypedLowering::ReduceNumberBinop(Node* node,
                                             const Operator* numberOp) {
499 500
  if (flags() & kDisableBinaryOpReduction) return NoChange();

501
  JSBinopReduction r(this, node);
502
  if (r.IsStrong() || numberOp == simplified()->NumberModulus()) {
503
    if (r.BothInputsAre(Type::Number())) {
504 505 506 507
      return r.ChangeToPureOperator(numberOp, Type::Number());
    }
    return NoChange();
  }
508
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
509 510
  r.ConvertInputsToNumber(frame_state);
  return r.ChangeToPureOperator(numberOp, Type::Number());
511 512 513
}


514
Reduction JSTypedLowering::ReduceInt32Binop(Node* node, const Operator* intOp) {
515 516
  if (flags() & kDisableBinaryOpReduction) return NoChange();

517
  JSBinopReduction r(this, node);
518
  if (r.IsStrong()) {
519 520 521 522 523 524
    if (r.BothInputsAre(Type::Number())) {
      r.ConvertInputsToUI32(kSigned, kSigned);
      return r.ChangeToPureOperator(intOp, Type::Integral32());
    }
    return NoChange();
  }
525
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
526 527 528
  r.ConvertInputsToNumber(frame_state);
  r.ConvertInputsToUI32(kSigned, kSigned);
  return r.ChangeToPureOperator(intOp, Type::Integral32());
529 530 531
}


532 533 534
Reduction JSTypedLowering::ReduceUI32Shift(Node* node,
                                           Signedness left_signedness,
                                           const Operator* shift_op) {
535 536
  if (flags() & kDisableBinaryOpReduction) return NoChange();

537
  JSBinopReduction r(this, node);
538 539
  if (r.IsStrong()) {
    if (r.BothInputsAre(Type::Number())) {
540
      r.ConvertInputsToUI32(left_signedness, kUnsigned);
541 542 543
      return r.ChangeToPureOperator(shift_op);
    }
    return NoChange();
544
  }
545 546
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
  r.ConvertInputsToNumber(frame_state);
547
  r.ConvertInputsToUI32(left_signedness, kUnsigned);
548
  return r.ChangeToPureOperator(shift_op);
549 550 551 552
}


Reduction JSTypedLowering::ReduceJSComparison(Node* node) {
553 554
  if (flags() & kDisableBinaryOpReduction) return NoChange();

555 556 557
  JSBinopReduction r(this, node);
  if (r.BothInputsAre(Type::String())) {
    // If both inputs are definitely strings, perform a string comparison.
558
    const Operator* stringOp;
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    switch (node->opcode()) {
      case IrOpcode::kJSLessThan:
        stringOp = simplified()->StringLessThan();
        break;
      case IrOpcode::kJSGreaterThan:
        stringOp = simplified()->StringLessThan();
        r.SwapInputs();  // a > b => b < a
        break;
      case IrOpcode::kJSLessThanOrEqual:
        stringOp = simplified()->StringLessThanOrEqual();
        break;
      case IrOpcode::kJSGreaterThanOrEqual:
        stringOp = simplified()->StringLessThanOrEqual();
        r.SwapInputs();  // a >= b => b <= a
        break;
      default:
        return NoChange();
    }
577 578
    r.ChangeToStringComparisonOperator(stringOp);
    return Changed(node);
579
  }
580
  if (r.OneInputCannotBe(Type::StringOrReceiver())) {
581 582
    const Operator* less_than;
    const Operator* less_than_or_equal;
583 584 585 586 587 588 589 590
    if (r.BothInputsAre(Type::Unsigned32())) {
      less_than = machine()->Uint32LessThan();
      less_than_or_equal = machine()->Uint32LessThanOrEqual();
    } else if (r.BothInputsAre(Type::Signed32())) {
      less_than = machine()->Int32LessThan();
      less_than_or_equal = machine()->Int32LessThanOrEqual();
    } else {
      // TODO(turbofan): mixed signed/unsigned int32 comparisons.
591 592 593 594 595
      if (r.IsStrong() && !r.BothInputsAre(Type::Number())) {
        return NoChange();
      }
      Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
      r.ConvertInputsToNumber(frame_state);
596 597 598
      less_than = simplified()->NumberLessThan();
      less_than_or_equal = simplified()->NumberLessThanOrEqual();
    }
599
    const Operator* comparison;
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    switch (node->opcode()) {
      case IrOpcode::kJSLessThan:
        comparison = less_than;
        break;
      case IrOpcode::kJSGreaterThan:
        comparison = less_than;
        r.SwapInputs();  // a > b => b < a
        break;
      case IrOpcode::kJSLessThanOrEqual:
        comparison = less_than_or_equal;
        break;
      case IrOpcode::kJSGreaterThanOrEqual:
        comparison = less_than_or_equal;
        r.SwapInputs();  // a >= b => b <= a
        break;
      default:
        return NoChange();
    }
    return r.ChangeToPureOperator(comparison);
  }
  // TODO(turbofan): relax/remove effects of this operator in other cases.
  return NoChange();  // Keep a generic comparison.
}


Reduction JSTypedLowering::ReduceJSEqual(Node* node, bool invert) {
626 627
  if (flags() & kDisableBinaryOpReduction) return NoChange();

628 629 630 631 632 633
  JSBinopReduction r(this, node);

  if (r.BothInputsAre(Type::Number())) {
    return r.ChangeToPureOperator(simplified()->NumberEqual(), invert);
  }
  if (r.BothInputsAre(Type::String())) {
634 635
    return r.ChangeToStringComparisonOperator(simplified()->StringEqual(),
                                              invert);
636
  }
637 638 639 640
  if (r.BothInputsAre(Type::Boolean())) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(Type::Boolean()),
                                  invert);
  }
641 642 643 644
  if (r.BothInputsAre(Type::Receiver())) {
    return r.ChangeToPureOperator(
        simplified()->ReferenceEqual(Type::Receiver()), invert);
  }
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  if (r.OneInputIs(Type::NullOrUndefined())) {
    Callable const callable = CodeFactory::CompareNilIC(isolate(), kNullValue);
    CallDescriptor const* const desc = Linkage::GetStubCallDescriptor(
        isolate(), graph()->zone(), callable.descriptor(), 0,
        CallDescriptor::kNeedsFrameState, node->op()->properties());
    node->RemoveInput(r.LeftInputIs(Type::NullOrUndefined()) ? 0 : 1);
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
    NodeProperties::ChangeOp(node, common()->Call(desc));
    if (invert) {
      // Insert an boolean not to invert the value.
      Node* value = graph()->NewNode(simplified()->BooleanNot(), node);
      node->ReplaceUses(value);
      // Note: ReplaceUses() smashes all uses, so smash it back here.
      value->ReplaceInput(0, node);
      return Replace(value);
    }
    return Changed(node);
  }
664 665 666 667 668
  return NoChange();
}


Reduction JSTypedLowering::ReduceJSStrictEqual(Node* node, bool invert) {
669 670
  if (flags() & kDisableBinaryOpReduction) return NoChange();

671 672 673 674
  JSBinopReduction r(this, node);
  if (r.left() == r.right()) {
    // x === x is always true if x != NaN
    if (!r.left_type()->Maybe(Type::NaN())) {
675
      Node* replacement = jsgraph()->BooleanConstant(!invert);
676
      ReplaceWithValue(node, replacement);
677
      return Replace(replacement);
678 679
    }
  }
680
  if (r.OneInputCannotBe(Type::NumberOrString())) {
681 682 683
    // For values with canonical representation (i.e. not string nor number) an
    // empty type intersection means the values cannot be strictly equal.
    if (!r.left_type()->Maybe(r.right_type())) {
684
      Node* replacement = jsgraph()->BooleanConstant(invert);
685
      ReplaceWithValue(node, replacement);
686
      return Replace(replacement);
687 688
    }
  }
689 690 691 692
  if (r.OneInputIs(the_hole_type_)) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(the_hole_type_),
                                  invert);
  }
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
  if (r.OneInputIs(Type::Undefined())) {
    return r.ChangeToPureOperator(
        simplified()->ReferenceEqual(Type::Undefined()), invert);
  }
  if (r.OneInputIs(Type::Null())) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(Type::Null()),
                                  invert);
  }
  if (r.OneInputIs(Type::Boolean())) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(Type::Boolean()),
                                  invert);
  }
  if (r.OneInputIs(Type::Object())) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(Type::Object()),
                                  invert);
  }
  if (r.OneInputIs(Type::Receiver())) {
    return r.ChangeToPureOperator(
        simplified()->ReferenceEqual(Type::Receiver()), invert);
  }
713 714 715 716
  if (r.BothInputsAre(Type::Unique())) {
    return r.ChangeToPureOperator(simplified()->ReferenceEqual(Type::Unique()),
                                  invert);
  }
717
  if (r.BothInputsAre(Type::String())) {
718 719
    return r.ChangeToStringComparisonOperator(simplified()->StringEqual(),
                                              invert);
720 721 722 723 724 725 726 727 728
  }
  if (r.BothInputsAre(Type::Number())) {
    return r.ChangeToPureOperator(simplified()->NumberEqual(), invert);
  }
  // TODO(turbofan): js-typed-lowering of StrictEqual(mixed types)
  return NoChange();
}


729
Reduction JSTypedLowering::ReduceJSToBoolean(Node* node) {
730
  Node* const input = node->InputAt(0);
731
  Type* const input_type = NodeProperties::GetType(input);
732
  Node* const effect = NodeProperties::GetEffectInput(node);
733
  if (input_type->Is(Type::Boolean())) {
734
    // JSToBoolean(x:boolean) => x
735
    ReplaceWithValue(node, input, effect);
736
    return Replace(input);
737 738
  } else if (input_type->Is(Type::OrderedNumber())) {
    // JSToBoolean(x:ordered-number) => BooleanNot(NumberEqual(x,#0))
739
    RelaxEffectsAndControls(node);
740 741 742
    node->ReplaceInput(0, graph()->NewNode(simplified()->NumberEqual(), input,
                                           jsgraph()->ZeroConstant()));
    node->TrimInputCount(1);
743
    NodeProperties::ChangeOp(node, simplified()->BooleanNot());
744 745 746
    return Changed(node);
  } else if (input_type->Is(Type::String())) {
    // JSToBoolean(x:string) => NumberLessThan(#0,x.length)
747
    FieldAccess const access = AccessBuilder::ForStringLength();
748
    Node* length = graph()->NewNode(simplified()->LoadField(access), input,
749
                                    effect, graph()->start());
750
    ReplaceWithValue(node, node, length);
751 752
    node->ReplaceInput(0, jsgraph()->ZeroConstant());
    node->ReplaceInput(1, length);
753
    node->TrimInputCount(2);
754
    NodeProperties::ChangeOp(node, simplified()->NumberLessThan());
755
    return Changed(node);
756
  }
757
  return NoChange();
758 759 760
}


761 762 763 764 765 766 767
Reduction JSTypedLowering::ReduceJSToNumberInput(Node* input) {
  if (input->opcode() == IrOpcode::kJSToNumber) {
    // Recursively try to reduce the input first.
    Reduction result = ReduceJSToNumber(input);
    if (result.Changed()) return result;
    return Changed(input);  // JSToNumber(JSToNumber(x)) => JSToNumber(x)
  }
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
  // Check for ToNumber truncation of signaling NaN to undefined mapping.
  if (input->opcode() == IrOpcode::kSelect) {
    Node* check = NodeProperties::GetValueInput(input, 0);
    Node* vtrue = NodeProperties::GetValueInput(input, 1);
    Type* vtrue_type = NodeProperties::GetType(vtrue);
    Node* vfalse = NodeProperties::GetValueInput(input, 2);
    Type* vfalse_type = NodeProperties::GetType(vfalse);
    if (vtrue_type->Is(Type::Undefined()) && vfalse_type->Is(Type::Number())) {
      if (check->opcode() == IrOpcode::kNumberIsHoleNaN &&
          check->InputAt(0) == vfalse) {
        // JSToNumber(Select(NumberIsHoleNaN(x), y:undefined, x:number)) => x
        return Replace(vfalse);
      }
    }
  }
783
  // Try constant-folding of JSToNumber with constant inputs.
784
  Type* input_type = NodeProperties::GetType(input);
785 786 787 788 789 790 791 792 793 794
  if (input_type->IsConstant()) {
    Handle<Object> input_value = input_type->AsConstant()->Value();
    if (input_value->IsString()) {
      return Replace(jsgraph()->Constant(
          String::ToNumber(Handle<String>::cast(input_value))));
    } else if (input_value->IsOddball()) {
      return Replace(jsgraph()->Constant(
          Oddball::ToNumber(Handle<Oddball>::cast(input_value))));
    }
  }
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
  if (input_type->Is(Type::Number())) {
    // JSToNumber(x:number) => x
    return Changed(input);
  }
  if (input_type->Is(Type::Undefined())) {
    // JSToNumber(undefined) => #NaN
    return Replace(jsgraph()->NaNConstant());
  }
  if (input_type->Is(Type::Null())) {
    // JSToNumber(null) => #0
    return Replace(jsgraph()->ZeroConstant());
  }
  if (input_type->Is(Type::Boolean())) {
    // JSToNumber(x:boolean) => BooleanToNumber(x)
    return Replace(graph()->NewNode(simplified()->BooleanToNumber(), input));
  }
  // TODO(turbofan): js-typed-lowering of ToNumber(x:string)
  return NoChange();
}


Reduction JSTypedLowering::ReduceJSToNumber(Node* node) {
  // Try to reduce the input first.
  Node* const input = node->InputAt(0);
  Reduction reduction = ReduceJSToNumberInput(input);
  if (reduction.Changed()) {
821
    ReplaceWithValue(node, reduction.replacement());
822 823
    return reduction;
  }
824
  Type* const input_type = NodeProperties::GetType(input);
825
  if (input_type->Is(Type::PlainPrimitive())) {
826 827 828 829 830 831
    if (NodeProperties::GetContextInput(node) !=
            jsgraph()->NoContextConstant() ||
        NodeProperties::GetEffectInput(node) != graph()->start() ||
        NodeProperties::GetControlInput(node) != graph()->start()) {
      // JSToNumber(x:plain-primitive,context,effect,control)
      //   => JSToNumber(x,no-context,start,start)
832
      RelaxEffectsAndControls(node);
833 834 835
      NodeProperties::ReplaceContextInput(node, jsgraph()->NoContextConstant());
      NodeProperties::ReplaceControlInput(node, graph()->start());
      NodeProperties::ReplaceEffectInput(node, graph()->start());
836 837 838
      DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
      NodeProperties::ReplaceFrameStateInput(node, 0,
                                             jsgraph()->EmptyFrameState());
839 840
      return Changed(node);
    }
841 842 843 844 845 846 847 848 849 850 851 852
  }
  return NoChange();
}


Reduction JSTypedLowering::ReduceJSToStringInput(Node* input) {
  if (input->opcode() == IrOpcode::kJSToString) {
    // Recursively try to reduce the input first.
    Reduction result = ReduceJSToString(input);
    if (result.Changed()) return result;
    return Changed(input);  // JSToString(JSToString(x)) => JSToString(x)
  }
853
  Type* input_type = NodeProperties::GetType(input);
854 855 856
  if (input_type->Is(Type::String())) {
    return Changed(input);  // JSToString(x:string) => x
  }
857
  if (input_type->Is(Type::Boolean())) {
858 859 860 861
    return Replace(graph()->NewNode(
        common()->Select(MachineRepresentation::kTagged), input,
        jsgraph()->HeapConstant(factory()->true_string()),
        jsgraph()->HeapConstant(factory()->false_string())));
862
  }
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
  if (input_type->Is(Type::Undefined())) {
    return Replace(jsgraph()->HeapConstant(factory()->undefined_string()));
  }
  if (input_type->Is(Type::Null())) {
    return Replace(jsgraph()->HeapConstant(factory()->null_string()));
  }
  // TODO(turbofan): js-typed-lowering of ToString(x:number)
  return NoChange();
}


Reduction JSTypedLowering::ReduceJSToString(Node* node) {
  // Try to reduce the input first.
  Node* const input = node->InputAt(0);
  Reduction reduction = ReduceJSToStringInput(input);
  if (reduction.Changed()) {
879
    ReplaceWithValue(node, reduction.replacement());
880 881 882 883 884 885
    return reduction;
  }
  return NoChange();
}


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 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
Reduction JSTypedLowering::ReduceJSToObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSToObject, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Type* receiver_type = NodeProperties::GetType(receiver);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  if (!receiver_type->Is(Type::Receiver())) {
    // TODO(bmeurer/mstarzinger): Add support for lowering inside try blocks.
    if (receiver_type->Maybe(Type::NullOrUndefined()) &&
        NodeProperties::IsExceptionalCall(node)) {
      // ToObject throws for null or undefined inputs.
      return NoChange();
    }

    // Check whether {receiver} is a Smi.
    Node* check0 = graph()->NewNode(simplified()->ObjectIsSmi(), receiver);
    Node* branch0 =
        graph()->NewNode(common()->Branch(BranchHint::kFalse), check0, control);
    Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0);
    Node* etrue0 = effect;

    Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0);
    Node* efalse0 = effect;

    // Determine the instance type of {receiver}.
    Node* receiver_map = efalse0 =
        graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMap()),
                         receiver, efalse0, if_false0);
    Node* receiver_instance_type = efalse0 = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForMapInstanceType()),
        receiver_map, efalse0, if_false0);

    // Check whether {receiver} is a spec object.
    STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
    Node* check1 =
        graph()->NewNode(machine()->Uint32LessThanOrEqual(),
                         jsgraph()->Uint32Constant(FIRST_JS_RECEIVER_TYPE),
                         receiver_instance_type);
    Node* branch1 = graph()->NewNode(common()->Branch(BranchHint::kTrue),
                                     check1, if_false0);
    Node* if_true1 = graph()->NewNode(common()->IfTrue(), branch1);
    Node* etrue1 = efalse0;

    Node* if_false1 = graph()->NewNode(common()->IfFalse(), branch1);
    Node* efalse1 = efalse0;

    // Convert {receiver} using the ToObjectStub.
    Node* if_convert =
        graph()->NewNode(common()->Merge(2), if_true0, if_false1);
    Node* econvert =
        graph()->NewNode(common()->EffectPhi(2), etrue0, efalse1, if_convert);
    Node* rconvert;
    {
      Callable callable = CodeFactory::ToObject(isolate());
      CallDescriptor const* const desc = Linkage::GetStubCallDescriptor(
          isolate(), graph()->zone(), callable.descriptor(), 0,
          CallDescriptor::kNeedsFrameState, node->op()->properties());
      rconvert = econvert = graph()->NewNode(
          common()->Call(desc), jsgraph()->HeapConstant(callable.code()),
          receiver, context, frame_state, econvert, if_convert);
    }

    // The {receiver} is already a spec object.
    Node* if_done = if_true1;
    Node* edone = etrue1;
    Node* rdone = receiver;

    control = graph()->NewNode(common()->Merge(2), if_convert, if_done);
    effect = graph()->NewNode(common()->EffectPhi(2), econvert, edone, control);
957 958 959
    receiver =
        graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                         rconvert, rdone, control);
960 961 962 963 964 965
  }
  ReplaceWithValue(node, receiver, effect, control);
  return Changed(receiver);
}


966 967 968
Reduction JSTypedLowering::ReduceJSLoadNamed(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadNamed, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
969
  Type* receiver_type = NodeProperties::GetType(receiver);
970 971
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
972
  Handle<Name> name = NamedAccessOf(node->op()).name();
973 974 975
  // Optimize "length" property of strings.
  if (name.is_identical_to(factory()->length_string()) &&
      receiver_type->Is(Type::String())) {
976 977 978
    Node* value = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForStringLength()), receiver,
        effect, control);
979 980 981
    ReplaceWithValue(node, value, effect);
    return Replace(value);
  }
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
  // Optimize "prototype" property of functions.
  if (name.is_identical_to(factory()->prototype_string()) &&
      receiver_type->IsConstant() &&
      receiver_type->AsConstant()->Value()->IsJSFunction()) {
    // TODO(turbofan): This lowering might not kick in if we ever lower
    // the C++ accessor for "prototype" in an earlier optimization pass.
    Handle<JSFunction> function =
        Handle<JSFunction>::cast(receiver_type->AsConstant()->Value());
    if (function->has_initial_map()) {
      // We need to add a code dependency on the initial map of the {function}
      // in order to be notified about changes to the "prototype" of {function},
      // so it doesn't make sense to continue unless deoptimization is enabled.
      if (!(flags() & kDeoptimizationEnabled)) return NoChange();
      Handle<Map> initial_map(function->initial_map(), isolate());
      dependencies()->AssumeInitialMapCantChange(initial_map);
      Node* value =
          jsgraph()->Constant(handle(initial_map->prototype(), isolate()));
      ReplaceWithValue(node, value);
      return Replace(value);
    }
  }
1003 1004 1005 1006
  return NoChange();
}


1007
Reduction JSTypedLowering::ReduceJSLoadProperty(Node* node) {
1008 1009
  Node* key = NodeProperties::GetValueInput(node, 1);
  Node* base = NodeProperties::GetValueInput(node, 0);
1010
  Type* key_type = NodeProperties::GetType(key);
1011
  HeapObjectMatcher mbase(base);
1012
  if (mbase.HasValue() && mbase.Value()->IsJSTypedArray()) {
1013
    Handle<JSTypedArray> const array =
1014
        Handle<JSTypedArray>::cast(mbase.Value());
1015 1016 1017
    if (!array->GetBuffer()->was_neutered()) {
      array->GetBuffer()->set_is_neuterable(false);
      BufferAccess const access(array->type());
1018 1019
      size_t const k =
          ElementSizeLog2Of(access.machine_type().representation());
1020 1021
      double const byte_length = array->byte_length()->Number();
      CHECK_LT(k, arraysize(shifted_int32_ranges_));
1022
      if (key_type->Is(shifted_int32_ranges_[k]) && byte_length <= kMaxInt) {
1023
        // JSLoadProperty(typed-array, int32)
1024 1025
        Handle<FixedTypedArrayBase> elements =
            Handle<FixedTypedArrayBase>::cast(handle(array->elements()));
1026 1027 1028 1029 1030
        Node* buffer = jsgraph()->PointerConstant(elements->external_pointer());
        Node* length = jsgraph()->Constant(byte_length);
        Node* effect = NodeProperties::GetEffectInput(node);
        Node* control = NodeProperties::GetControlInput(node);
        // Check if we can avoid the bounds check.
1031
        if (key_type->Min() >= 0 && key_type->Max() < array->length_value()) {
1032 1033 1034 1035
          Node* load = graph()->NewNode(
              simplified()->LoadElement(
                  AccessBuilder::ForTypedArrayElement(array->type(), true)),
              buffer, key, effect, control);
1036 1037
          ReplaceWithValue(node, load, load);
          return Replace(load);
1038 1039 1040 1041 1042
        }
        // Compute byte offset.
        Node* offset = Word32Shl(key, static_cast<int>(k));
        Node* load = graph()->NewNode(simplified()->LoadBuffer(access), buffer,
                                      offset, length, effect, control);
1043 1044
        ReplaceWithValue(node, load, load);
        return Replace(load);
1045
      }
1046 1047 1048 1049 1050 1051
    }
  }
  return NoChange();
}


1052 1053 1054 1055
Reduction JSTypedLowering::ReduceJSStoreProperty(Node* node) {
  Node* key = NodeProperties::GetValueInput(node, 1);
  Node* base = NodeProperties::GetValueInput(node, 0);
  Node* value = NodeProperties::GetValueInput(node, 2);
1056 1057
  Type* key_type = NodeProperties::GetType(key);
  Type* value_type = NodeProperties::GetType(value);
1058
  HeapObjectMatcher mbase(base);
1059
  if (mbase.HasValue() && mbase.Value()->IsJSTypedArray()) {
1060
    Handle<JSTypedArray> const array =
1061
        Handle<JSTypedArray>::cast(mbase.Value());
1062 1063 1064
    if (!array->GetBuffer()->was_neutered()) {
      array->GetBuffer()->set_is_neuterable(false);
      BufferAccess const access(array->type());
1065 1066
      size_t const k =
          ElementSizeLog2Of(access.machine_type().representation());
1067 1068
      double const byte_length = array->byte_length()->Number();
      CHECK_LT(k, arraysize(shifted_int32_ranges_));
1069
      if (access.external_array_type() != kExternalUint8ClampedArray &&
1070 1071
          key_type->Is(shifted_int32_ranges_[k]) && byte_length <= kMaxInt) {
        // JSLoadProperty(typed-array, int32)
1072 1073
        Handle<FixedTypedArrayBase> elements =
            Handle<FixedTypedArrayBase>::cast(handle(array->elements()));
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        Node* buffer = jsgraph()->PointerConstant(elements->external_pointer());
        Node* length = jsgraph()->Constant(byte_length);
        Node* context = NodeProperties::GetContextInput(node);
        Node* effect = NodeProperties::GetEffectInput(node);
        Node* control = NodeProperties::GetControlInput(node);
        // Convert to a number first.
        if (!value_type->Is(Type::Number())) {
          Reduction number_reduction = ReduceJSToNumberInput(value);
          if (number_reduction.Changed()) {
            value = number_reduction.replacement();
          } else {
            Node* frame_state_for_to_number =
                NodeProperties::GetFrameStateInput(node, 1);
            value = effect =
                graph()->NewNode(javascript()->ToNumber(), value, context,
                                 frame_state_for_to_number, effect, control);
          }
1091
        }
1092
        // Check if we can avoid the bounds check.
1093
        if (key_type->Min() >= 0 && key_type->Max() < array->length_value()) {
1094
          RelaxControls(node);
1095 1096 1097 1098 1099 1100
          node->ReplaceInput(0, buffer);
          DCHECK_EQ(key, node->InputAt(1));
          node->ReplaceInput(2, value);
          node->ReplaceInput(3, effect);
          node->ReplaceInput(4, control);
          node->TrimInputCount(5);
1101 1102 1103 1104
          NodeProperties::ChangeOp(
              node,
              simplified()->StoreElement(
                  AccessBuilder::ForTypedArrayElement(array->type(), true)));
1105 1106 1107 1108 1109
          return Changed(node);
        }
        // Compute byte offset.
        Node* offset = Word32Shl(key, static_cast<int>(k));
        // Turn into a StoreBuffer operation.
1110
        RelaxControls(node);
1111
        node->ReplaceInput(0, buffer);
1112 1113 1114 1115 1116 1117
        node->ReplaceInput(1, offset);
        node->ReplaceInput(2, length);
        node->ReplaceInput(3, value);
        node->ReplaceInput(4, effect);
        node->ReplaceInput(5, control);
        node->TrimInputCount(6);
1118
        NodeProperties::ChangeOp(node, simplified()->StoreBuffer(access));
1119 1120
        return Changed(node);
      }
1121 1122 1123 1124 1125 1126
    }
  }
  return NoChange();
}


1127 1128
Reduction JSTypedLowering::ReduceJSInstanceOf(Node* node) {
  DCHECK_EQ(IrOpcode::kJSInstanceOf, node->opcode());
1129 1130
  Node* const context = NodeProperties::GetContextInput(node);
  Node* const frame_state = NodeProperties::GetFrameStateInput(node, 0);
1131 1132

  // If deoptimization is disabled, we cannot optimize.
1133 1134 1135 1136
  if (!(flags() & kDeoptimizationEnabled) ||
      (flags() & kDisableBinaryOpReduction)) {
    return NoChange();
  }
1137

1138 1139 1140 1141
  // If we are in a try block, don't optimize since the runtime call
  // in the proxy case can throw.
  if (NodeProperties::IsExceptionalCall(node)) return NoChange();

1142 1143 1144 1145
  JSBinopReduction r(this, node);
  Node* effect = r.effect();
  Node* control = r.control();

1146 1147 1148 1149
  if (!r.right_type()->IsConstant() ||
      !r.right_type()->AsConstant()->Value()->IsJSFunction()) {
    return NoChange();
  }
1150

1151 1152 1153
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(r.right_type()->AsConstant()->Value());
  Handle<SharedFunctionInfo> shared(function->shared(), isolate());
1154

1155 1156 1157
  if (!function->IsConstructor() ||
      function->map()->has_non_instance_prototype()) {
    return NoChange();
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 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
  JSFunction::EnsureHasInitialMap(function);
  DCHECK(function->has_initial_map());
  Handle<Map> initial_map(function->initial_map(), isolate());
  this->dependencies()->AssumeInitialMapCantChange(initial_map);
  Node* prototype =
      jsgraph()->Constant(handle(initial_map->prototype(), isolate()));

  Node* if_is_smi = nullptr;
  Node* e_is_smi = nullptr;
  // If the left hand side is an object, no smi check is needed.
  if (r.left_type()->Maybe(Type::TaggedSigned())) {
    Node* is_smi = graph()->NewNode(simplified()->ObjectIsSmi(), r.left());
    Node* branch_is_smi =
        graph()->NewNode(common()->Branch(BranchHint::kFalse), is_smi, control);
    if_is_smi = graph()->NewNode(common()->IfTrue(), branch_is_smi);
    e_is_smi = effect;
    control = graph()->NewNode(common()->IfFalse(), branch_is_smi);
  }

  Node* object_map = effect =
      graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMap()),
                       r.left(), effect, control);

  // Loop through the {object}s prototype chain looking for the {prototype}.
  Node* loop = control = graph()->NewNode(common()->Loop(2), control, control);

  Node* loop_effect = effect =
      graph()->NewNode(common()->EffectPhi(2), effect, effect, loop);

  Node* loop_object_map =
      graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                       object_map, r.left(), loop);

  // Check if the lhs needs access checks.
  Node* map_bit_field = effect =
      graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMapBitField()),
                       loop_object_map, loop_effect, control);
  int is_access_check_needed_bit = 1 << Map::kIsAccessCheckNeeded;
  Node* is_access_check_needed_num =
      graph()->NewNode(simplified()->NumberBitwiseAnd(), map_bit_field,
                       jsgraph()->Uint32Constant(is_access_check_needed_bit));
  Node* is_access_check_needed =
      graph()->NewNode(machine()->Word32Equal(), is_access_check_needed_num,
                       jsgraph()->Uint32Constant(is_access_check_needed_bit));

  Node* branch_is_access_check_needed = graph()->NewNode(
      common()->Branch(BranchHint::kFalse), is_access_check_needed, control);
  Node* if_is_access_check_needed =
      graph()->NewNode(common()->IfTrue(), branch_is_access_check_needed);
  Node* e_is_access_check_needed = effect;

  control =
      graph()->NewNode(common()->IfFalse(), branch_is_access_check_needed);

  // Check if the lhs is a proxy.
  Node* map_instance_type = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapInstanceType()),
      loop_object_map, loop_effect, control);
  Node* is_proxy = graph()->NewNode(machine()->Word32Equal(), map_instance_type,
                                    jsgraph()->Uint32Constant(JS_PROXY_TYPE));
  Node* branch_is_proxy =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), is_proxy, control);
  Node* if_is_proxy = graph()->NewNode(common()->IfTrue(), branch_is_proxy);
  Node* e_is_proxy = effect;


  Node* runtime_has_in_proto_chain = control = graph()->NewNode(
      common()->Merge(2), if_is_access_check_needed, if_is_proxy);
  effect = graph()->NewNode(common()->EffectPhi(2), e_is_access_check_needed,
                            e_is_proxy, control);

  // If we need an access check or the object is a Proxy, make a runtime call
  // to finish the lowering.
  Node* bool_result_runtime_has_in_proto_chain_case = graph()->NewNode(
1234
      javascript()->CallRuntime(Runtime::kHasInPrototypeChain), r.left(),
1235 1236 1237 1238 1239 1240 1241 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 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
      prototype, context, frame_state, effect, control);

  control = graph()->NewNode(common()->IfFalse(), branch_is_proxy);

  Node* object_prototype = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapPrototype()),
      loop_object_map, loop_effect, control);

  // Check if object prototype is equal to function prototype.
  Node* eq_proto =
      graph()->NewNode(simplified()->ReferenceEqual(r.right_type()),
                       object_prototype, prototype);
  Node* branch_eq_proto =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), eq_proto, control);
  Node* if_eq_proto = graph()->NewNode(common()->IfTrue(), branch_eq_proto);
  Node* e_eq_proto = effect;

  control = graph()->NewNode(common()->IfFalse(), branch_eq_proto);

  // If not, check if object prototype is the null prototype.
  Node* null_proto =
      graph()->NewNode(simplified()->ReferenceEqual(r.right_type()),
                       object_prototype, jsgraph()->NullConstant());
  Node* branch_null_proto = graph()->NewNode(
      common()->Branch(BranchHint::kFalse), null_proto, control);
  Node* if_null_proto = graph()->NewNode(common()->IfTrue(), branch_null_proto);
  Node* e_null_proto = effect;

  control = graph()->NewNode(common()->IfFalse(), branch_null_proto);
  Node* load_object_map = effect =
      graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMap()),
                       object_prototype, effect, control);
  // Close the loop.
  loop_effect->ReplaceInput(1, effect);
  loop_object_map->ReplaceInput(1, load_object_map);
  loop->ReplaceInput(1, control);

  control = graph()->NewNode(common()->Merge(3), runtime_has_in_proto_chain,
                             if_eq_proto, if_null_proto);
  effect = graph()->NewNode(common()->EffectPhi(3),
                            bool_result_runtime_has_in_proto_chain_case,
                            e_eq_proto, e_null_proto, control);

  Node* result = graph()->NewNode(
      common()->Phi(MachineRepresentation::kTagged, 3),
      bool_result_runtime_has_in_proto_chain_case, jsgraph()->TrueConstant(),
      jsgraph()->FalseConstant(), control);

  if (if_is_smi != nullptr) {
1284
    DCHECK_NOT_NULL(e_is_smi);
1285 1286 1287 1288 1289 1290 1291 1292 1293
    control = graph()->NewNode(common()->Merge(2), if_is_smi, control);
    effect =
        graph()->NewNode(common()->EffectPhi(2), e_is_smi, effect, control);
    result = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                              jsgraph()->FalseConstant(), result, control);
  }

  ReplaceWithValue(node, result, effect, control);
  return Changed(result);
1294 1295 1296
}


1297 1298 1299
Reduction JSTypedLowering::ReduceJSLoadContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadContext, node->opcode());
  ContextAccess const& access = ContextAccessOf(node->op());
1300 1301
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = graph()->start();
1302
  for (size_t i = 0; i < access.depth(); ++i) {
1303 1304 1305 1306 1307
    Node* previous = effect = graph()->NewNode(
        simplified()->LoadField(
            AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX)),
        NodeProperties::GetValueInput(node, 0), effect, control);
    node->ReplaceInput(0, previous);
1308 1309 1310
  }
  node->ReplaceInput(1, effect);
  node->ReplaceInput(2, control);
1311 1312 1313
  NodeProperties::ChangeOp(
      node,
      simplified()->LoadField(AccessBuilder::ForContextSlot(access.index())));
1314 1315 1316 1317 1318 1319 1320
  return Changed(node);
}


Reduction JSTypedLowering::ReduceJSStoreContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreContext, node->opcode());
  ContextAccess const& access = ContextAccessOf(node->op());
1321 1322
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = graph()->start();
1323
  for (size_t i = 0; i < access.depth(); ++i) {
1324 1325 1326 1327 1328
    Node* previous = effect = graph()->NewNode(
        simplified()->LoadField(
            AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX)),
        NodeProperties::GetValueInput(node, 0), effect, control);
    node->ReplaceInput(0, previous);
1329 1330
  }
  node->RemoveInput(2);
1331
  node->ReplaceInput(2, effect);
1332 1333 1334
  NodeProperties::ChangeOp(
      node,
      simplified()->StoreField(AccessBuilder::ForContextSlot(access.index())));
1335 1336 1337 1338
  return Changed(node);
}


1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
Reduction JSTypedLowering::ReduceJSConvertReceiver(Node* node) {
  DCHECK_EQ(IrOpcode::kJSConvertReceiver, node->opcode());
  ConvertReceiverMode mode = ConvertReceiverModeOf(node->op());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Type* receiver_type = NodeProperties::GetType(receiver);
  Node* context = NodeProperties::GetContextInput(node);
  Type* context_type = NodeProperties::GetType(context);
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  if (!receiver_type->Is(Type::Receiver())) {
    if (receiver_type->Is(Type::NullOrUndefined()) ||
        mode == ConvertReceiverMode::kNullOrUndefined) {
      if (context_type->IsConstant()) {
        Handle<JSObject> global_proxy(
            Handle<Context>::cast(context_type->AsConstant()->Value())
                ->global_proxy(),
            isolate());
        receiver = jsgraph()->Constant(global_proxy);
      } else {
1359 1360
        Node* native_context = effect = graph()->NewNode(
            javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
1361
            context, context, effect);
1362 1363 1364
        receiver = effect = graph()->NewNode(
            javascript()->LoadContext(0, Context::GLOBAL_PROXY_INDEX, true),
            native_context, native_context, effect);
1365 1366 1367 1368 1369 1370 1371
      }
    } else if (!receiver_type->Maybe(Type::NullOrUndefined()) ||
               mode == ConvertReceiverMode::kNotNullOrUndefined) {
      receiver = effect =
          graph()->NewNode(javascript()->ToObject(), receiver, context,
                           frame_state, effect, control);
    } else {
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
      // Check {receiver} for undefined.
      Node* check0 =
          graph()->NewNode(simplified()->ReferenceEqual(receiver_type),
                           receiver, jsgraph()->UndefinedConstant());
      Node* branch0 = graph()->NewNode(common()->Branch(BranchHint::kFalse),
                                       check0, control);
      Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0);
      Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0);

      // Check {receiver} for null.
      Node* check1 =
          graph()->NewNode(simplified()->ReferenceEqual(receiver_type),
                           receiver, jsgraph()->NullConstant());
      Node* branch1 = graph()->NewNode(common()->Branch(BranchHint::kFalse),
                                       check1, if_false0);
      Node* if_true1 = graph()->NewNode(common()->IfTrue(), branch1);
      Node* if_false1 = graph()->NewNode(common()->IfFalse(), branch1);

      // Convert {receiver} using ToObject.
      Node* if_convert = if_false1;
      Node* econvert = effect;
      Node* rconvert;
      {
        rconvert = econvert =
            graph()->NewNode(javascript()->ToObject(), receiver, context,
                             frame_state, econvert, if_convert);
      }

      // Replace {receiver} with global proxy of {context}.
      Node* if_global =
          graph()->NewNode(common()->Merge(2), if_true0, if_true1);
      Node* eglobal = effect;
      Node* rglobal;
      {
        if (context_type->IsConstant()) {
          Handle<JSObject> global_proxy(
              Handle<Context>::cast(context_type->AsConstant()->Value())
                  ->global_proxy(),
              isolate());
          rglobal = jsgraph()->Constant(global_proxy);
        } else {
1413 1414
          Node* native_context = eglobal = graph()->NewNode(
              javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
1415
              context, context, eglobal);
1416
          rglobal = eglobal = graph()->NewNode(
1417 1418
              javascript()->LoadContext(0, Context::GLOBAL_PROXY_INDEX, true),
              native_context, native_context, eglobal);
1419 1420 1421 1422 1423 1424
        }
      }

      control = graph()->NewNode(common()->Merge(2), if_convert, if_global);
      effect =
          graph()->NewNode(common()->EffectPhi(2), econvert, eglobal, control);
1425 1426 1427
      receiver =
          graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                           rconvert, rglobal, control);
1428 1429 1430 1431 1432 1433 1434
    }
  }
  ReplaceWithValue(node, receiver, effect, control);
  return Changed(receiver);
}


1435 1436 1437 1438 1439 1440 1441 1442
namespace {

// Maximum instance size for which allocations will be inlined.
const int kMaxInlineInstanceSize = 64 * kPointerSize;


// Checks whether allocation using the given constructor can be inlined.
bool IsAllocationInlineable(Handle<JSFunction> constructor) {
1443 1444 1445
  // TODO(bmeurer): Further relax restrictions on inlining, i.e.
  // instance type and maybe instance size (inobject properties
  // are limited anyways by the runtime).
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
  return constructor->has_initial_map() &&
         constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
         constructor->initial_map()->instance_size() < kMaxInlineInstanceSize;
}

}  // namespace


Reduction JSTypedLowering::ReduceJSCreate(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreate, node->opcode());
  Node* const target = NodeProperties::GetValueInput(node, 0);
  Type* const target_type = NodeProperties::GetType(target);
  Node* const new_target = NodeProperties::GetValueInput(node, 1);
  Node* const effect = NodeProperties::GetEffectInput(node);
  // TODO(turbofan): Add support for NewTarget passed to JSCreate.
  if (target != new_target) return NoChange();
  // Extract constructor function.
  if (target_type->IsConstant() &&
      target_type->AsConstant()->Value()->IsJSFunction()) {
    Handle<JSFunction> constructor =
        Handle<JSFunction>::cast(target_type->AsConstant()->Value());
1467
    DCHECK(constructor->IsConstructor());
1468 1469
    // Force completion of inobject slack tracking before
    // generating code to finalize the instance size.
1470
    constructor->CompleteInobjectSlackTrackingIfActive();
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

    // TODO(bmeurer): We fall back to the runtime in case we cannot inline
    // the allocation here, which is sort of expensive. We should think about
    // a soft fallback to some NewObjectCodeStub.
    if (IsAllocationInlineable(constructor)) {
      // Compute instance size from initial map of {constructor}.
      Handle<Map> initial_map(constructor->initial_map(), isolate());
      int const instance_size = initial_map->instance_size();

      // Add a dependency on the {initial_map} to make sure that this code is
      // deoptimized whenever the {initial_map} of the {constructor} changes.
      dependencies()->AssumeInitialMapCantChange(initial_map);

      // Emit code to allocate the JSObject instance for the {constructor}.
      AllocationBuilder a(jsgraph(), effect, graph()->start());
      a.Allocate(instance_size);
      a.Store(AccessBuilder::ForMap(), initial_map);
      a.Store(AccessBuilder::ForJSObjectProperties(),
              jsgraph()->EmptyFixedArrayConstant());
      a.Store(AccessBuilder::ForJSObjectElements(),
              jsgraph()->EmptyFixedArrayConstant());
      for (int i = 0; i < initial_map->GetInObjectProperties(); ++i) {
        a.Store(AccessBuilder::ForJSObjectInObjectProperty(initial_map, i),
                jsgraph()->UndefinedConstant());
      }
      a.FinishAndChange(node);
      return Changed(node);
    }
  }
  return NoChange();
}


1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
namespace {

// Retrieves the frame state holding actual argument values.
Node* GetArgumentsFrameState(Node* frame_state) {
  Node* const outer_state = frame_state->InputAt(kFrameStateOuterStateInput);
  FrameStateInfo outer_state_info = OpParameter<FrameStateInfo>(outer_state);
  return outer_state_info.type() == FrameStateType::kArgumentsAdaptor
             ? outer_state
             : frame_state;
}

}  // namespace


1518 1519 1520 1521 1522 1523 1524 1525 1526
Reduction JSTypedLowering::ReduceJSCreateArguments(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateArguments, node->opcode());
  CreateArgumentsParameters const& p = CreateArgumentsParametersOf(node->op());
  Node* const frame_state = NodeProperties::GetFrameStateInput(node, 0);
  Node* const outer_state = frame_state->InputAt(kFrameStateOuterStateInput);
  FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);

  // Use the ArgumentsAccessStub for materializing both mapped and unmapped
  // arguments object, but only for non-inlined (i.e. outermost) frames.
1527
  if (outer_state->opcode() != IrOpcode::kFrameState) {
1528 1529 1530 1531 1532 1533 1534 1535
    Isolate* isolate = jsgraph()->isolate();
    int parameter_count = state_info.parameter_count() - 1;
    int parameter_offset = parameter_count * kPointerSize;
    int offset = StandardFrameConstants::kCallerSPOffset + parameter_offset;
    Node* parameter_pointer = graph()->NewNode(
        machine()->IntAdd(), graph()->NewNode(machine()->LoadFramePointer()),
        jsgraph()->IntPtrConstant(offset));

1536
    if (p.type() != CreateArgumentsParameters::kRestArray) {
1537 1538
      Handle<SharedFunctionInfo> shared;
      if (!state_info.shared_info().ToHandle(&shared)) return NoChange();
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
      bool unmapped = p.type() == CreateArgumentsParameters::kUnmappedArguments;
      Callable callable = CodeFactory::ArgumentsAccess(
          isolate, unmapped, shared->has_duplicate_parameters());
      CallDescriptor* desc = Linkage::GetStubCallDescriptor(
          isolate, graph()->zone(), callable.descriptor(), 0,
          CallDescriptor::kNeedsFrameState);
      const Operator* new_op = common()->Call(desc);
      Node* stub_code = jsgraph()->HeapConstant(callable.code());
      node->InsertInput(graph()->zone(), 0, stub_code);
      node->InsertInput(graph()->zone(), 2,
                        jsgraph()->Constant(parameter_count));
      node->InsertInput(graph()->zone(), 3, parameter_pointer);
      NodeProperties::ChangeOp(node, new_op);
      return Changed(node);
    } else {
      Callable callable = CodeFactory::RestArgumentsAccess(isolate);
      CallDescriptor* desc = Linkage::GetStubCallDescriptor(
          isolate, graph()->zone(), callable.descriptor(), 0,
          CallDescriptor::kNeedsFrameState);
      const Operator* new_op = common()->Call(desc);
      Node* stub_code = jsgraph()->HeapConstant(callable.code());
      node->InsertInput(graph()->zone(), 0, stub_code);
      node->ReplaceInput(1, jsgraph()->Constant(parameter_count));
      node->InsertInput(graph()->zone(), 2, parameter_pointer);
      node->InsertInput(graph()->zone(), 3,
                        jsgraph()->Constant(p.start_index()));
      NodeProperties::ChangeOp(node, new_op);
      return Changed(node);
    }
  } else if (outer_state->opcode() == IrOpcode::kFrameState) {
    // Use inline allocation for all mapped arguments objects within inlined
    // (i.e. non-outermost) frames, independent of the object size.
    if (p.type() == CreateArgumentsParameters::kMappedArguments) {
      Handle<SharedFunctionInfo> shared;
      if (!state_info.shared_info().ToHandle(&shared)) return NoChange();
      Node* const callee = NodeProperties::GetValueInput(node, 0);
      Node* const control = NodeProperties::GetControlInput(node);
      Node* const context = NodeProperties::GetContextInput(node);
      Node* effect = NodeProperties::GetEffectInput(node);
      // TODO(mstarzinger): Duplicate parameters are not handled yet.
      if (shared->has_duplicate_parameters()) return NoChange();
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
      Node* const args_state = GetArgumentsFrameState(frame_state);
      FrameStateInfo args_state_info = OpParameter<FrameStateInfo>(args_state);
      // Prepare element backing store to be used by arguments object.
      bool has_aliased_arguments = false;
      Node* const elements = AllocateAliasedArguments(
          effect, control, args_state, context, shared, &has_aliased_arguments);
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
      // Load the arguments object map from the current native context.
      Node* const load_native_context = effect = graph()->NewNode(
          javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
          context, context, effect);
      Node* const load_arguments_map = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForContextSlot(
              has_aliased_arguments ? Context::FAST_ALIASED_ARGUMENTS_MAP_INDEX
                                    : Context::SLOPPY_ARGUMENTS_MAP_INDEX)),
          load_native_context, effect, control);
      // Actually allocate and initialize the arguments object.
      AllocationBuilder a(jsgraph(), effect, control);
      Node* properties = jsgraph()->EmptyFixedArrayConstant();
      int length = args_state_info.parameter_count() - 1;  // Minus receiver.
      STATIC_ASSERT(Heap::kSloppyArgumentsObjectSize == 5 * kPointerSize);
      a.Allocate(Heap::kSloppyArgumentsObjectSize);
      a.Store(AccessBuilder::ForMap(), load_arguments_map);
      a.Store(AccessBuilder::ForJSObjectProperties(), properties);
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
      a.Store(AccessBuilder::ForArgumentsLength(), jsgraph()->Constant(length));
      a.Store(AccessBuilder::ForArgumentsCallee(), callee);
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
    } else if (p.type() == CreateArgumentsParameters::kUnmappedArguments) {
      // Use inline allocation for all unmapped arguments objects within inlined
      // (i.e. non-outermost) frames, independent of the object size.
      Node* const control = NodeProperties::GetControlInput(node);
      Node* const context = NodeProperties::GetContextInput(node);
      Node* effect = NodeProperties::GetEffectInput(node);
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
      Node* const args_state = GetArgumentsFrameState(frame_state);
      FrameStateInfo args_state_info = OpParameter<FrameStateInfo>(args_state);
      // Prepare element backing store to be used by arguments object.
      Node* const elements = AllocateArguments(effect, control, args_state);
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
      // Load the arguments object map from the current native context.
      Node* const load_native_context = effect = graph()->NewNode(
          javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
          context, context, effect);
      Node* const load_arguments_map = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForContextSlot(
              Context::STRICT_ARGUMENTS_MAP_INDEX)),
          load_native_context, effect, control);
      // Actually allocate and initialize the arguments object.
      AllocationBuilder a(jsgraph(), effect, control);
      Node* properties = jsgraph()->EmptyFixedArrayConstant();
      int length = args_state_info.parameter_count() - 1;  // Minus receiver.
      STATIC_ASSERT(Heap::kStrictArgumentsObjectSize == 4 * kPointerSize);
      a.Allocate(Heap::kStrictArgumentsObjectSize);
      a.Store(AccessBuilder::ForMap(), load_arguments_map);
      a.Store(AccessBuilder::ForJSObjectProperties(), properties);
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
      a.Store(AccessBuilder::ForArgumentsLength(), jsgraph()->Constant(length));
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
    } else if (p.type() == CreateArgumentsParameters::kRestArray) {
      // Use inline allocation for all unmapped arguments objects within inlined
      // (i.e. non-outermost) frames, independent of the object size.
      Node* const control = NodeProperties::GetControlInput(node);
      Node* const context = NodeProperties::GetContextInput(node);
      Node* effect = NodeProperties::GetEffectInput(node);
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
      Node* const args_state = GetArgumentsFrameState(frame_state);
      FrameStateInfo args_state_info = OpParameter<FrameStateInfo>(args_state);
      // Prepare element backing store to be used by the rest array.
      Node* const elements =
          AllocateRestArguments(effect, control, args_state, p.start_index());
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
      // Load the JSArray object map from the current native context.
      Node* const load_native_context = effect = graph()->NewNode(
          javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
          context, context, effect);
      Node* const load_jsarray_map = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForContextSlot(
              Context::JS_ARRAY_FAST_ELEMENTS_MAP_INDEX)),
          load_native_context, effect, control);
      // Actually allocate and initialize the jsarray.
      AllocationBuilder a(jsgraph(), effect, control);
      Node* properties = jsgraph()->EmptyFixedArrayConstant();

      // -1 to minus receiver
      int argument_count = args_state_info.parameter_count() - 1;
      int length = std::max(0, argument_count - p.start_index());
      STATIC_ASSERT(JSArray::kSize == 4 * kPointerSize);
      a.Allocate(JSArray::kSize);
      a.Store(AccessBuilder::ForMap(), load_jsarray_map);
      a.Store(AccessBuilder::ForJSObjectProperties(), properties);
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
      a.Store(AccessBuilder::ForJSArrayLength(FAST_ELEMENTS),
              jsgraph()->Constant(length));
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
    }
1689 1690
  }

1691 1692 1693 1694
  return NoChange();
}


1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
Reduction JSTypedLowering::ReduceNewArray(Node* node, Node* length,
                                          int capacity,
                                          Handle<AllocationSite> site) {
  DCHECK_EQ(IrOpcode::kJSCreateArray, node->opcode());
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Extract transition and tenuring feedback from the {site} and add
  // appropriate code dependencies on the {site} if deoptimization is
  // enabled.
  PretenureFlag pretenure = site->GetPretenureMode();
  ElementsKind elements_kind = site->GetElementsKind();
1708
  DCHECK(IsFastElementsKind(elements_kind));
1709 1710 1711 1712 1713 1714
  if (flags() & kDeoptimizationEnabled) {
    dependencies()->AssumeTenuringDecision(site);
    dependencies()->AssumeTransitionStable(site);
  }

  // Retrieve the initial map for the array from the appropriate native context.
1715 1716 1717 1718 1719 1720
  Node* native_context = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
      context, context, effect);
  Node* js_array_map = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::ArrayMapIndex(elements_kind), true),
      native_context, native_context, effect);
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

  // Setup elements and properties.
  Node* elements;
  if (capacity == 0) {
    elements = jsgraph()->EmptyFixedArrayConstant();
  } else {
    elements = effect =
        AllocateElements(effect, control, elements_kind, capacity, pretenure);
  }
  Node* properties = jsgraph()->EmptyFixedArrayConstant();

  // Perform the allocation of the actual JSArray object.
  AllocationBuilder a(jsgraph(), effect, control);
  a.Allocate(JSArray::kSize, pretenure);
  a.Store(AccessBuilder::ForMap(), js_array_map);
  a.Store(AccessBuilder::ForJSObjectProperties(), properties);
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
  a.Store(AccessBuilder::ForJSArrayLength(elements_kind), length);
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}


1745 1746 1747
Reduction JSTypedLowering::ReduceJSCreateArray(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateArray, node->opcode());
  CreateArrayParameters const& p = CreateArrayParametersOf(node->op());
1748 1749
  Node* target = NodeProperties::GetValueInput(node, 0);
  Node* new_target = NodeProperties::GetValueInput(node, 1);
1750 1751 1752 1753 1754 1755 1756

  // TODO(bmeurer): Optimize the subclassing case.
  if (target != new_target) return NoChange();

  // Check if we have a feedback {site} on the {node}.
  Handle<AllocationSite> site = p.site();
  if (p.site().is_null()) return NoChange();
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

  // Attempt to inline calls to the Array constructor for the relevant cases
  // where either no arguments are provided, or exactly one unsigned number
  // argument is given.
  if (site->CanInlineCall()) {
    if (p.arity() == 0) {
      Node* length = jsgraph()->ZeroConstant();
      int capacity = JSArray::kPreallocatedArrayElements;
      return ReduceNewArray(node, length, capacity, site);
    } else if (p.arity() == 1) {
      Node* length = NodeProperties::GetValueInput(node, 2);
      Type* length_type = NodeProperties::GetType(length);
      if (length_type->Is(type_cache_.kElementLoopUnrollType)) {
        int capacity = static_cast<int>(length_type->Max());
        return ReduceNewArray(node, length, capacity, site);
      }
    }
  }
1775

1776 1777 1778 1779
  return NoChange();
}


1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
Reduction JSTypedLowering::ReduceJSCreateIterResultObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateIterResultObject, node->opcode());
  Node* value = NodeProperties::GetValueInput(node, 0);
  Node* done = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);

  // Load the JSIteratorResult map for the {context}.
  Node* native_context = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
      context, context, effect);
  Node* iterator_result_map = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::ITERATOR_RESULT_MAP_INDEX, true),
      native_context, native_context, effect);

  // Emit code to allocate the JSIteratorResult instance.
  AllocationBuilder a(jsgraph(), effect, graph()->start());
  a.Allocate(JSIteratorResult::kSize);
  a.Store(AccessBuilder::ForMap(), iterator_result_map);
  a.Store(AccessBuilder::ForJSObjectProperties(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSIteratorResultValue(), value);
  a.Store(AccessBuilder::ForJSIteratorResultDone(), done);
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
  a.FinishAndChange(node);
  return Changed(node);
}


1811 1812 1813
Reduction JSTypedLowering::ReduceJSCreateFunctionContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateFunctionContext, node->opcode());
  int slot_count = OpParameter<int>(node->op());
1814 1815
  Node* const closure = NodeProperties::GetValueInput(node, 0);

1816
  // Use inline allocation for function contexts up to a size limit.
1817
  if (slot_count < kFunctionContextAllocationLimit) {
1818
    // JSCreateFunctionContext[slot_count < limit]](fun)
1819 1820 1821
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
    Node* context = NodeProperties::GetContextInput(node);
1822
    Node* extension = jsgraph()->TheHoleConstant();
1823 1824 1825
    Node* native_context = effect = graph()->NewNode(
        javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
        context, context, effect);
1826
    AllocationBuilder a(jsgraph(), effect, control);
1827 1828 1829 1830 1831 1832
    STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);  // Ensure fully covered.
    int context_length = slot_count + Context::MIN_CONTEXT_SLOTS;
    a.AllocateArray(context_length, factory()->function_context_map());
    a.Store(AccessBuilder::ForContextSlot(Context::CLOSURE_INDEX), closure);
    a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
    a.Store(AccessBuilder::ForContextSlot(Context::EXTENSION_INDEX), extension);
1833 1834
    a.Store(AccessBuilder::ForContextSlot(Context::NATIVE_CONTEXT_INDEX),
            native_context);
1835
    for (int i = Context::MIN_CONTEXT_SLOTS; i < context_length; ++i) {
1836
      a.Store(AccessBuilder::ForContextSlot(i), jsgraph()->UndefinedConstant());
1837
    }
1838
    RelaxControls(node);
1839
    a.FinishAndChange(node);
1840 1841 1842 1843 1844 1845 1846
    return Changed(node);
  }

  return NoChange();
}


1847 1848
Reduction JSTypedLowering::ReduceJSCreateWithContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateWithContext, node->opcode());
1849 1850 1851 1852 1853
  Node* object = NodeProperties::GetValueInput(node, 0);
  Node* closure = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* context = NodeProperties::GetContextInput(node);
1854 1855 1856
  Node* native_context = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
      context, context, effect);
1857 1858 1859 1860 1861 1862
  AllocationBuilder a(jsgraph(), effect, control);
  STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);  // Ensure fully covered.
  a.AllocateArray(Context::MIN_CONTEXT_SLOTS, factory()->with_context_map());
  a.Store(AccessBuilder::ForContextSlot(Context::CLOSURE_INDEX), closure);
  a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
  a.Store(AccessBuilder::ForContextSlot(Context::EXTENSION_INDEX), object);
1863 1864
  a.Store(AccessBuilder::ForContextSlot(Context::NATIVE_CONTEXT_INDEX),
          native_context);
1865 1866 1867
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
1868 1869 1870
}


1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
Reduction JSTypedLowering::ReduceJSCreateCatchContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateCatchContext, node->opcode());
  Handle<String> name = OpParameter<Handle<String>>(node);
  Node* exception = NodeProperties::GetValueInput(node, 0);
  Node* closure = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* context = NodeProperties::GetContextInput(node);
  Node* native_context = effect = graph()->NewNode(
      javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
      context, context, effect);
  AllocationBuilder a(jsgraph(), effect, control);
  STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);  // Ensure fully covered.
  a.AllocateArray(Context::MIN_CONTEXT_SLOTS + 1,
                  factory()->catch_context_map());
  a.Store(AccessBuilder::ForContextSlot(Context::CLOSURE_INDEX), closure);
  a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
  a.Store(AccessBuilder::ForContextSlot(Context::EXTENSION_INDEX), name);
  a.Store(AccessBuilder::ForContextSlot(Context::NATIVE_CONTEXT_INDEX),
          native_context);
  a.Store(AccessBuilder::ForContextSlot(Context::THROWN_OBJECT_INDEX),
          exception);
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}


1899 1900
Reduction JSTypedLowering::ReduceJSCreateBlockContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateBlockContext, node->opcode());
1901 1902
  Handle<ScopeInfo> scope_info = OpParameter<Handle<ScopeInfo>>(node);
  int context_length = scope_info->ContextLength();
1903 1904
  Node* const closure = NodeProperties::GetValueInput(node, 0);

1905
  // Use inline allocation for block contexts up to a size limit.
1906
  if (context_length < kBlockContextAllocationLimit) {
1907
    // JSCreateBlockContext[scope[length < limit]](fun)
1908 1909 1910 1911 1912 1913 1914
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
    Node* context = NodeProperties::GetContextInput(node);
    Node* extension = jsgraph()->Constant(scope_info);
    Node* native_context = effect = graph()->NewNode(
        javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true),
        context, context, effect);
1915
    AllocationBuilder a(jsgraph(), effect, control);
1916 1917 1918 1919
    STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);  // Ensure fully covered.
    a.AllocateArray(context_length, factory()->block_context_map());
    a.Store(AccessBuilder::ForContextSlot(Context::CLOSURE_INDEX), closure);
    a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
1920
    a.Store(AccessBuilder::ForContextSlot(Context::EXTENSION_INDEX), extension);
1921 1922
    a.Store(AccessBuilder::ForContextSlot(Context::NATIVE_CONTEXT_INDEX),
            native_context);
1923
    for (int i = Context::MIN_CONTEXT_SLOTS; i < context_length; ++i) {
1924
      a.Store(AccessBuilder::ForContextSlot(i), jsgraph()->UndefinedConstant());
1925
    }
1926
    RelaxControls(node);
1927
    a.FinishAndChange(node);
1928 1929
    return Changed(node);
  }
1930

1931 1932 1933 1934
  return NoChange();
}


1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 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
Reduction JSTypedLowering::ReduceJSCallConstruct(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCallConstruct, node->opcode());
  CallConstructParameters const& p = CallConstructParametersOf(node->op());
  DCHECK_LE(2u, p.arity());
  int const arity = static_cast<int>(p.arity() - 2);
  Node* target = NodeProperties::GetValueInput(node, 0);
  Type* target_type = NodeProperties::GetType(target);
  Node* new_target = NodeProperties::GetValueInput(node, arity + 1);

  // Check if {target} is a known JSFunction.
  if (target_type->IsConstant() &&
      target_type->AsConstant()->Value()->IsJSFunction()) {
    Handle<JSFunction> function =
        Handle<JSFunction>::cast(target_type->AsConstant()->Value());
    Handle<SharedFunctionInfo> shared(function->shared(), isolate());

    // Remove the eager bailout frame state.
    NodeProperties::RemoveFrameStateInput(node, 1);

    // Patch {node} to an indirect call via the {function}s construct stub.
    Callable callable(handle(shared->construct_stub(), isolate()),
                      ConstructStubDescriptor(isolate()));
    node->RemoveInput(arity + 1);
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
    node->InsertInput(graph()->zone(), 2, new_target);
    node->InsertInput(graph()->zone(), 3, jsgraph()->Int32Constant(arity));
    node->InsertInput(graph()->zone(), 4, jsgraph()->UndefinedConstant());
    node->InsertInput(graph()->zone(), 5, jsgraph()->UndefinedConstant());
    NodeProperties::ChangeOp(
        node, common()->Call(Linkage::GetStubCallDescriptor(
                  isolate(), graph()->zone(), callable.descriptor(), 1 + arity,
                  CallDescriptor::kNeedsFrameState)));
    return Changed(node);
  }

  // Check if {target} is a JSFunction.
  if (target_type->Is(Type::Function())) {
    // Remove the eager bailout frame state.
    NodeProperties::RemoveFrameStateInput(node, 1);

    // Patch {node} to an indirect call via the ConstructFunction builtin.
    Callable callable = CodeFactory::ConstructFunction(isolate());
    node->RemoveInput(arity + 1);
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
    node->InsertInput(graph()->zone(), 2, new_target);
    node->InsertInput(graph()->zone(), 3, jsgraph()->Int32Constant(arity));
    node->InsertInput(graph()->zone(), 4, jsgraph()->UndefinedConstant());
    NodeProperties::ChangeOp(
        node, common()->Call(Linkage::GetStubCallDescriptor(
                  isolate(), graph()->zone(), callable.descriptor(), 1 + arity,
                  CallDescriptor::kNeedsFrameState)));
    return Changed(node);
  }

  return NoChange();
}


1995 1996 1997 1998
Reduction JSTypedLowering::ReduceJSCallFunction(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCallFunction, node->opcode());
  CallFunctionParameters const& p = CallFunctionParametersOf(node->op());
  int const arity = static_cast<int>(p.arity() - 2);
1999
  ConvertReceiverMode convert_mode = p.convert_mode();
2000 2001 2002 2003
  Node* target = NodeProperties::GetValueInput(node, 0);
  Type* target_type = NodeProperties::GetType(target);
  Node* receiver = NodeProperties::GetValueInput(node, 1);
  Type* receiver_type = NodeProperties::GetType(receiver);
2004 2005 2006
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
2007

2008 2009 2010 2011 2012 2013 2014
  // Try to infer receiver {convert_mode} from {receiver} type.
  if (receiver_type->Is(Type::NullOrUndefined())) {
    convert_mode = ConvertReceiverMode::kNullOrUndefined;
  } else if (!receiver_type->Maybe(Type::NullOrUndefined())) {
    convert_mode = ConvertReceiverMode::kNotNullOrUndefined;
  }

2015 2016 2017 2018 2019 2020
  // Check if {target} is a known JSFunction.
  if (target_type->IsConstant() &&
      target_type->AsConstant()->Value()->IsJSFunction()) {
    Handle<JSFunction> function =
        Handle<JSFunction>::cast(target_type->AsConstant()->Value());
    Handle<SharedFunctionInfo> shared(function->shared(), isolate());
2021

2022 2023 2024 2025
    // Class constructors are callable, but [[Call]] will raise an exception.
    // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList ).
    if (IsClassConstructor(shared->kind())) return NoChange();

2026 2027 2028 2029
    // Load the context from the {target}.
    Node* context = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForJSFunctionContext()), target,
        effect, control);
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
    NodeProperties::ReplaceContextInput(node, context);

    // Check if we need to convert the {receiver}.
    if (is_sloppy(shared->language_mode()) && !shared->native() &&
        !receiver_type->Is(Type::Receiver())) {
      receiver = effect =
          graph()->NewNode(javascript()->ConvertReceiver(convert_mode),
                           receiver, context, frame_state, effect, control);
      NodeProperties::ReplaceValueInput(node, receiver, 1);
    }

2041 2042 2043
    // Update the effect dependency for the {node}.
    NodeProperties::ReplaceEffectInput(node, effect);

2044 2045 2046 2047 2048
    // Remove the eager bailout frame state.
    NodeProperties::RemoveFrameStateInput(node, 1);

    // Compute flags for the call.
    CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;
2049 2050 2051
    if (p.tail_call_mode() == TailCallMode::kAllow) {
      flags |= CallDescriptor::kSupportsTailCalls;
    }
2052

2053 2054
    Node* new_target = jsgraph()->UndefinedConstant();
    Node* argument_count = jsgraph()->Int32Constant(arity);
2055 2056 2057
    if (shared->internal_formal_parameter_count() == arity ||
        shared->internal_formal_parameter_count() ==
            SharedFunctionInfo::kDontAdaptArgumentsSentinel) {
2058
      // Patch {node} to a direct call.
2059 2060
      node->InsertInput(graph()->zone(), arity + 2, new_target);
      node->InsertInput(graph()->zone(), arity + 3, argument_count);
2061 2062 2063
      NodeProperties::ChangeOp(node,
                               common()->Call(Linkage::GetJSCallDescriptor(
                                   graph()->zone(), false, 1 + arity, flags)));
2064
    } else {
2065
      // Patch {node} to an indirect call via the ArgumentsAdaptorTrampoline.
2066 2067 2068
      Callable callable = CodeFactory::ArgumentAdaptor(isolate());
      node->InsertInput(graph()->zone(), 0,
                        jsgraph()->HeapConstant(callable.code()));
2069 2070
      node->InsertInput(graph()->zone(), 2, new_target);
      node->InsertInput(graph()->zone(), 3, argument_count);
2071
      node->InsertInput(
2072
          graph()->zone(), 4,
2073 2074 2075 2076 2077
          jsgraph()->Int32Constant(shared->internal_formal_parameter_count()));
      NodeProperties::ChangeOp(
          node, common()->Call(Linkage::GetStubCallDescriptor(
                    isolate(), graph()->zone(), callable.descriptor(),
                    1 + arity, flags)));
2078
    }
2079
    return Changed(node);
2080
  }
2081

2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
  // Check if {target} is a JSFunction.
  if (target_type->Is(Type::Function())) {
    // Remove the eager bailout frame state.
    NodeProperties::RemoveFrameStateInput(node, 1);

    // Compute flags for the call.
    CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;
    if (p.tail_call_mode() == TailCallMode::kAllow) {
      flags |= CallDescriptor::kSupportsTailCalls;
    }

    // Patch {node} to an indirect call via the CallFunction builtin.
2094
    Callable callable = CodeFactory::CallFunction(isolate(), convert_mode);
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
    node->InsertInput(graph()->zone(), 2, jsgraph()->Int32Constant(arity));
    NodeProperties::ChangeOp(
        node, common()->Call(Linkage::GetStubCallDescriptor(
                  isolate(), graph()->zone(), callable.descriptor(), 1 + arity,
                  flags)));
    return Changed(node);
  }

2105 2106 2107 2108 2109 2110 2111 2112 2113
  // Maybe we did at least learn something about the {receiver}.
  if (p.convert_mode() != convert_mode) {
    NodeProperties::ChangeOp(
        node,
        javascript()->CallFunction(p.arity(), p.language_mode(), p.feedback(),
                                   convert_mode, p.tail_call_mode()));
    return Changed(node);
  }

2114 2115 2116 2117
  return NoChange();
}


2118 2119 2120
Reduction JSTypedLowering::ReduceJSForInDone(Node* node) {
  DCHECK_EQ(IrOpcode::kJSForInDone, node->opcode());
  node->TrimInputCount(2);
2121
  NodeProperties::ChangeOp(node, machine()->Word32Equal());
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
  return Changed(node);
}


Reduction JSTypedLowering::ReduceJSForInNext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSForInNext, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* cache_array = NodeProperties::GetValueInput(node, 1);
  Node* cache_type = NodeProperties::GetValueInput(node, 2);
  Node* index = NodeProperties::GetValueInput(node, 3);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Load the next {key} from the {cache_array}.
  Node* key = effect = graph()->NewNode(
      simplified()->LoadElement(AccessBuilder::ForFixedArrayElement()),
      cache_array, index, effect, control);

  // Load the map of the {receiver}.
  Node* receiver_map = effect =
      graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMap()),
                       receiver, effect, control);

  // Check if the expected map still matches that of the {receiver}.
  Node* check0 = graph()->NewNode(simplified()->ReferenceEqual(Type::Any()),
                                  receiver_map, cache_type);
  Node* branch0 =
      graph()->NewNode(common()->Branch(BranchHint::kTrue), check0, control);

  Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0);
  Node* etrue0;
  Node* vtrue0;
  {
    // Don't need filtering since expected map still matches that of the
    // {receiver}.
    etrue0 = effect;
    vtrue0 = key;
  }

  Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0);
  Node* efalse0;
  Node* vfalse0;
  {
2167 2168 2169 2170 2171 2172
    // Filter the {key} to check if it's still a valid property of the
    // {receiver} (does the ToName conversion implicitly).
    vfalse0 = efalse0 = graph()->NewNode(
        javascript()->CallRuntime(Runtime::kForInFilter), receiver, key,
        context, frame_state, effect, if_false0);
    if_false0 = graph()->NewNode(common()->IfSuccess(), vfalse0);
2173 2174 2175 2176 2177 2178 2179 2180 2181
  }

  control = graph()->NewNode(common()->Merge(2), if_true0, if_false0);
  effect = graph()->NewNode(common()->EffectPhi(2), etrue0, efalse0, control);
  ReplaceWithValue(node, node, effect, control);
  node->ReplaceInput(0, vtrue0);
  node->ReplaceInput(1, vfalse0);
  node->ReplaceInput(2, control);
  node->TrimInputCount(3);
2182 2183
  NodeProperties::ChangeOp(node,
                           common()->Phi(MachineRepresentation::kTagged, 2));
2184 2185 2186 2187 2188 2189 2190
  return Changed(node);
}


Reduction JSTypedLowering::ReduceJSForInStep(Node* node) {
  DCHECK_EQ(IrOpcode::kJSForInStep, node->opcode());
  node->ReplaceInput(1, jsgraph()->Int32Constant(1));
2191
  NodeProperties::ChangeOp(node, machine()->Int32Add());
2192 2193 2194 2195
  return Changed(node);
}


2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
Reduction JSTypedLowering::ReduceSelect(Node* node) {
  DCHECK_EQ(IrOpcode::kSelect, node->opcode());
  Node* const condition = NodeProperties::GetValueInput(node, 0);
  Type* const condition_type = NodeProperties::GetType(condition);
  Node* const vtrue = NodeProperties::GetValueInput(node, 1);
  Type* const vtrue_type = NodeProperties::GetType(vtrue);
  Node* const vfalse = NodeProperties::GetValueInput(node, 2);
  Type* const vfalse_type = NodeProperties::GetType(vfalse);
  if (condition_type->Is(true_type_)) {
    // Select(condition:true, vtrue, vfalse) => vtrue
    return Replace(vtrue);
  }
  if (condition_type->Is(false_type_)) {
    // Select(condition:false, vtrue, vfalse) => vfalse
    return Replace(vfalse);
  }
  if (vtrue_type->Is(true_type_) && vfalse_type->Is(false_type_)) {
    // Select(condition, vtrue:true, vfalse:false) => condition
    return Replace(condition);
  }
  if (vtrue_type->Is(false_type_) && vfalse_type->Is(true_type_)) {
    // Select(condition, vtrue:false, vfalse:true) => BooleanNot(condition)
    node->TrimInputCount(1);
    NodeProperties::ChangeOp(node, simplified()->BooleanNot());
    return Changed(node);
  }
  return NoChange();
}


2226
Reduction JSTypedLowering::Reduce(Node* node) {
2227
  // Check if the output type is a singleton.  In that case we already know the
2228
  // result value and can simply replace the node if it's eliminable.
2229
  if (!NodeProperties::IsConstant(node) && NodeProperties::IsTyped(node) &&
2230
      node->op()->HasProperty(Operator::kEliminatable)) {
2231
    Type* upper = NodeProperties::GetType(node);
2232 2233
    if (upper->IsConstant()) {
      Node* replacement = jsgraph()->Constant(upper->AsConstant()->Value());
2234
      ReplaceWithValue(node, replacement);
2235 2236 2237
      return Changed(replacement);
    } else if (upper->Is(Type::MinusZero())) {
      Node* replacement = jsgraph()->Constant(factory()->minus_zero_value());
2238
      ReplaceWithValue(node, replacement);
2239 2240 2241
      return Changed(replacement);
    } else if (upper->Is(Type::NaN())) {
      Node* replacement = jsgraph()->NaNConstant();
2242
      ReplaceWithValue(node, replacement);
2243 2244 2245
      return Changed(replacement);
    } else if (upper->Is(Type::Null())) {
      Node* replacement = jsgraph()->NullConstant();
2246
      ReplaceWithValue(node, replacement);
2247 2248 2249
      return Changed(replacement);
    } else if (upper->Is(Type::PlainNumber()) && upper->Min() == upper->Max()) {
      Node* replacement = jsgraph()->Constant(upper->Min());
2250
      ReplaceWithValue(node, replacement);
2251 2252 2253
      return Changed(replacement);
    } else if (upper->Is(Type::Undefined())) {
      Node* replacement = jsgraph()->UndefinedConstant();
2254
      ReplaceWithValue(node, replacement);
2255 2256
      return Changed(replacement);
    }
2257
  }
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
  switch (node->opcode()) {
    case IrOpcode::kJSEqual:
      return ReduceJSEqual(node, false);
    case IrOpcode::kJSNotEqual:
      return ReduceJSEqual(node, true);
    case IrOpcode::kJSStrictEqual:
      return ReduceJSStrictEqual(node, false);
    case IrOpcode::kJSStrictNotEqual:
      return ReduceJSStrictEqual(node, true);
    case IrOpcode::kJSLessThan:         // fall through
    case IrOpcode::kJSGreaterThan:      // fall through
    case IrOpcode::kJSLessThanOrEqual:  // fall through
    case IrOpcode::kJSGreaterThanOrEqual:
      return ReduceJSComparison(node);
    case IrOpcode::kJSBitwiseOr:
2273
      return ReduceInt32Binop(node, simplified()->NumberBitwiseOr());
2274
    case IrOpcode::kJSBitwiseXor:
2275
      return ReduceInt32Binop(node, simplified()->NumberBitwiseXor());
2276
    case IrOpcode::kJSBitwiseAnd:
2277
      return ReduceInt32Binop(node, simplified()->NumberBitwiseAnd());
2278
    case IrOpcode::kJSShiftLeft:
2279
      return ReduceUI32Shift(node, kSigned, simplified()->NumberShiftLeft());
2280
    case IrOpcode::kJSShiftRight:
2281
      return ReduceUI32Shift(node, kSigned, simplified()->NumberShiftRight());
2282
    case IrOpcode::kJSShiftRightLogical:
2283 2284
      return ReduceUI32Shift(node, kUnsigned,
                             simplified()->NumberShiftRightLogical());
2285 2286 2287 2288 2289
    case IrOpcode::kJSAdd:
      return ReduceJSAdd(node);
    case IrOpcode::kJSSubtract:
      return ReduceNumberBinop(node, simplified()->NumberSubtract());
    case IrOpcode::kJSMultiply:
2290
      return ReduceNumberBinop(node, simplified()->NumberMultiply());
2291 2292 2293
    case IrOpcode::kJSDivide:
      return ReduceNumberBinop(node, simplified()->NumberDivide());
    case IrOpcode::kJSModulus:
2294
      return ReduceJSModulus(node);
2295
    case IrOpcode::kJSToBoolean:
2296
      return ReduceJSToBoolean(node);
2297
    case IrOpcode::kJSToNumber:
2298
      return ReduceJSToNumber(node);
2299
    case IrOpcode::kJSToString:
2300
      return ReduceJSToString(node);
2301 2302
    case IrOpcode::kJSToObject:
      return ReduceJSToObject(node);
2303 2304
    case IrOpcode::kJSLoadNamed:
      return ReduceJSLoadNamed(node);
2305
    case IrOpcode::kJSLoadProperty:
2306 2307 2308
      return ReduceJSLoadProperty(node);
    case IrOpcode::kJSStoreProperty:
      return ReduceJSStoreProperty(node);
2309 2310
    case IrOpcode::kJSInstanceOf:
      return ReduceJSInstanceOf(node);
2311 2312 2313 2314
    case IrOpcode::kJSLoadContext:
      return ReduceJSLoadContext(node);
    case IrOpcode::kJSStoreContext:
      return ReduceJSStoreContext(node);
2315 2316
    case IrOpcode::kJSConvertReceiver:
      return ReduceJSConvertReceiver(node);
2317 2318
    case IrOpcode::kJSCreate:
      return ReduceJSCreate(node);
2319 2320
    case IrOpcode::kJSCreateArguments:
      return ReduceJSCreateArguments(node);
2321 2322
    case IrOpcode::kJSCreateArray:
      return ReduceJSCreateArray(node);
2323 2324
    case IrOpcode::kJSCreateIterResultObject:
      return ReduceJSCreateIterResultObject(node);
2325 2326
    case IrOpcode::kJSCreateFunctionContext:
      return ReduceJSCreateFunctionContext(node);
2327 2328
    case IrOpcode::kJSCreateWithContext:
      return ReduceJSCreateWithContext(node);
2329 2330
    case IrOpcode::kJSCreateCatchContext:
      return ReduceJSCreateCatchContext(node);
2331 2332
    case IrOpcode::kJSCreateBlockContext:
      return ReduceJSCreateBlockContext(node);
2333 2334
    case IrOpcode::kJSCallConstruct:
      return ReduceJSCallConstruct(node);
2335 2336
    case IrOpcode::kJSCallFunction:
      return ReduceJSCallFunction(node);
2337 2338 2339 2340 2341 2342
    case IrOpcode::kJSForInDone:
      return ReduceJSForInDone(node);
    case IrOpcode::kJSForInNext:
      return ReduceJSForInNext(node);
    case IrOpcode::kJSForInStep:
      return ReduceJSForInStep(node);
2343 2344
    case IrOpcode::kSelect:
      return ReduceSelect(node);
2345 2346 2347 2348 2349
    default:
      break;
  }
  return NoChange();
}
2350

2351 2352 2353 2354 2355 2356 2357

Node* JSTypedLowering::Word32Shl(Node* const lhs, int32_t const rhs) {
  if (rhs == 0) return lhs;
  return graph()->NewNode(machine()->Word32Shl(), lhs,
                          jsgraph()->Int32Constant(rhs));
}

2358

2359 2360 2361 2362 2363
// Helper that allocates a FixedArray holding argument values recorded in the
// given {frame_state}. Serves as backing store for JSCreateArguments nodes.
Node* JSTypedLowering::AllocateArguments(Node* effect, Node* control,
                                         Node* frame_state) {
  FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);
2364 2365 2366 2367
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  if (argument_count == 0) return jsgraph()->EmptyFixedArrayConstant();

  // Prepare an iterator over argument values recorded in the frame state.
2368 2369
  Node* const parameters = frame_state->InputAt(kFrameStateParametersInput);
  StateValuesAccess parameters_access(parameters);
2370
  auto parameters_it = ++parameters_access.begin();
2371 2372

  // Actually allocate the backing store.
2373
  AllocationBuilder a(jsgraph(), effect, control);
2374
  a.AllocateArray(argument_count, factory()->fixed_array_map());
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 2403 2404 2405 2406
  for (int i = 0; i < argument_count; ++i, ++parameters_it) {
    a.Store(AccessBuilder::ForFixedArraySlot(i), (*parameters_it).node);
  }
  return a.Finish();
}


// Helper that allocates a FixedArray holding argument values recorded in the
// given {frame_state}. Serves as backing store for JSCreateArguments nodes.
Node* JSTypedLowering::AllocateRestArguments(Node* effect, Node* control,
                                             Node* frame_state,
                                             int start_index) {
  FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  int num_elements = std::max(0, argument_count - start_index);
  if (num_elements == 0) return jsgraph()->EmptyFixedArrayConstant();

  // Prepare an iterator over argument values recorded in the frame state.
  Node* const parameters = frame_state->InputAt(kFrameStateParametersInput);
  StateValuesAccess parameters_access(parameters);
  auto parameters_it = ++parameters_access.begin();

  // Skip unused arguments.
  for (int i = 0; i < start_index; i++) {
    ++parameters_it;
  }

  // Actually allocate the backing store.
  AllocationBuilder a(jsgraph(), effect, control);
  a.AllocateArray(num_elements, factory()->fixed_array_map());
  for (int i = 0; i < num_elements; ++i, ++parameters_it) {
    a.Store(AccessBuilder::ForFixedArraySlot(i), (*parameters_it).node);
2407 2408 2409 2410 2411
  }
  return a.Finish();
}


2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
// Helper that allocates a FixedArray serving as a parameter map for values
// recorded in the given {frame_state}. Some elements map to slots within the
// given {context}. Serves as backing store for JSCreateArguments nodes.
Node* JSTypedLowering::AllocateAliasedArguments(
    Node* effect, Node* control, Node* frame_state, Node* context,
    Handle<SharedFunctionInfo> shared, bool* has_aliased_arguments) {
  FrameStateInfo state_info = OpParameter<FrameStateInfo>(frame_state);
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  if (argument_count == 0) return jsgraph()->EmptyFixedArrayConstant();

  // If there is no aliasing, the arguments object elements are not special in
  // any way, we can just return an unmapped backing store instead.
  int parameter_count = shared->internal_formal_parameter_count();
  if (parameter_count == 0) {
    return AllocateArguments(effect, control, frame_state);
  }

  // Calculate number of argument values being aliased/mapped.
  int mapped_count = Min(argument_count, parameter_count);
  *has_aliased_arguments = true;

  // Prepare an iterator over argument values recorded in the frame state.
  Node* const parameters = frame_state->InputAt(kFrameStateParametersInput);
  StateValuesAccess parameters_access(parameters);
  auto paratemers_it = ++parameters_access.begin();

  // The unmapped argument values recorded in the frame state are stored yet
  // another indirection away and then linked into the parameter map below,
  // whereas mapped argument values are replaced with a hole instead.
  AllocationBuilder aa(jsgraph(), effect, control);
  aa.AllocateArray(argument_count, factory()->fixed_array_map());
  for (int i = 0; i < mapped_count; ++i, ++paratemers_it) {
    aa.Store(AccessBuilder::ForFixedArraySlot(i), jsgraph()->TheHoleConstant());
  }
  for (int i = mapped_count; i < argument_count; ++i, ++paratemers_it) {
    aa.Store(AccessBuilder::ForFixedArraySlot(i), (*paratemers_it).node);
  }
  Node* arguments = aa.Finish();

  // Actually allocate the backing store.
2452
  AllocationBuilder a(jsgraph(), arguments, control);
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
  a.AllocateArray(mapped_count + 2, factory()->sloppy_arguments_elements_map());
  a.Store(AccessBuilder::ForFixedArraySlot(0), context);
  a.Store(AccessBuilder::ForFixedArraySlot(1), arguments);
  for (int i = 0; i < mapped_count; ++i) {
    int idx = Context::MIN_CONTEXT_SLOTS + parameter_count - 1 - i;
    a.Store(AccessBuilder::ForFixedArraySlot(i + 2), jsgraph()->Constant(idx));
  }
  return a.Finish();
}


2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
Node* JSTypedLowering::AllocateElements(Node* effect, Node* control,
                                        ElementsKind elements_kind,
                                        int capacity, PretenureFlag pretenure) {
  DCHECK_LE(1, capacity);
  DCHECK_LE(capacity, JSArray::kInitialMaxFastElementArray);

  Handle<Map> elements_map = IsFastDoubleElementsKind(elements_kind)
                                 ? factory()->fixed_double_array_map()
                                 : factory()->fixed_array_map();
  ElementAccess access = IsFastDoubleElementsKind(elements_kind)
                             ? AccessBuilder::ForFixedDoubleArrayElement()
                             : AccessBuilder::ForFixedArrayElement();
  Node* value =
      IsFastDoubleElementsKind(elements_kind)
          ? jsgraph()->Float64Constant(bit_cast<double>(kHoleNanInt64))
          : jsgraph()->TheHoleConstant();

  // Actually allocate the backing store.
  AllocationBuilder a(jsgraph(), effect, control);
  a.AllocateArray(capacity, elements_map, pretenure);
  for (int i = 0; i < capacity; ++i) {
2485
    Node* index = jsgraph()->Constant(i);
2486 2487 2488 2489 2490 2491
    a.Store(access, index, value);
  }
  return a.Finish();
}


2492 2493 2494 2495 2496 2497
Factory* JSTypedLowering::factory() const { return jsgraph()->factory(); }


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


2498 2499 2500
Isolate* JSTypedLowering::isolate() const { return jsgraph()->isolate(); }


2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
JSOperatorBuilder* JSTypedLowering::javascript() const {
  return jsgraph()->javascript();
}


CommonOperatorBuilder* JSTypedLowering::common() const {
  return jsgraph()->common();
}


2511 2512 2513 2514 2515
SimplifiedOperatorBuilder* JSTypedLowering::simplified() const {
  return jsgraph()->simplified();
}


2516 2517 2518 2519
MachineOperatorBuilder* JSTypedLowering::machine() const {
  return jsgraph()->machine();
}

2520 2521 2522 2523 2524

CompilationDependencies* JSTypedLowering::dependencies() const {
  return dependencies_;
}

2525 2526 2527
}  // namespace compiler
}  // namespace internal
}  // namespace v8