js-typed-lowering.cc 98.3 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 6
#include "src/compiler/js-typed-lowering.h"

7
#include "src/ast/modules.h"
8
#include "src/builtins/builtins-utils.h"
9
#include "src/codegen/code-factory.h"
10
#include "src/compiler/access-builder.h"
11
#include "src/compiler/allocation-builder.h"
12
#include "src/compiler/graph-assembler.h"
13
#include "src/compiler/js-graph.h"
14
#include "src/compiler/js-heap-broker.h"
15
#include "src/compiler/linkage.h"
16
#include "src/compiler/node-matchers.h"
17 18
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
19
#include "src/compiler/type-cache.h"
20
#include "src/compiler/types.h"
21
#include "src/execution/protectors.h"
22
#include "src/objects/js-generator.h"
23
#include "src/objects/module-inl.h"
24
#include "src/objects/objects-inl.h"
25 26 27 28 29 30 31 32 33

namespace v8 {
namespace internal {
namespace compiler {

// 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.
34
class JSBinopReduction final {
35 36
 public:
  JSBinopReduction(JSTypedLowering* lowering, Node* node)
37
      : lowering_(lowering), node_(node) {}
38

39
  bool GetCompareNumberOperationHint(NumberOperationHint* hint) {
40 41 42
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    switch (CompareOperationHintOf(node_->op())) {
      case CompareOperationHint::kSignedSmall:
43
        *hint = NumberOperationHint::kSignedSmall;
44 45 46 47 48
        return true;
      case CompareOperationHint::kNumber:
        *hint = NumberOperationHint::kNumber;
        return true;
      case CompareOperationHint::kNumberOrOddball:
49 50
        *hint = NumberOperationHint::kNumberOrOddball;
        return true;
51 52 53 54
      case CompareOperationHint::kAny:
      case CompareOperationHint::kNone:
      case CompareOperationHint::kString:
      case CompareOperationHint::kSymbol:
55
      case CompareOperationHint::kBigInt:
56
      case CompareOperationHint::kReceiver:
57
      case CompareOperationHint::kReceiverOrNullOrUndefined:
58 59
      case CompareOperationHint::kInternalizedString:
        break;
60 61 62 63
    }
    return false;
  }

64
  bool IsInternalizedStringCompareOperation() {
65 66 67 68
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    return (CompareOperationHintOf(node_->op()) ==
            CompareOperationHint::kInternalizedString) &&
           BothInputsMaybe(Type::InternalizedString());
69 70
  }

71
  bool IsReceiverCompareOperation() {
72 73 74 75
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    return (CompareOperationHintOf(node_->op()) ==
            CompareOperationHint::kReceiver) &&
           BothInputsMaybe(Type::Receiver());
76 77
  }

78
  bool IsReceiverOrNullOrUndefinedCompareOperation() {
79 80
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    return (CompareOperationHintOf(node_->op()) ==
81 82
            CompareOperationHint::kReceiverOrNullOrUndefined) &&
           BothInputsMaybe(Type::ReceiverOrNullOrUndefined());
83 84
  }

85
  bool IsStringCompareOperation() {
86 87 88 89
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    return (CompareOperationHintOf(node_->op()) ==
            CompareOperationHint::kString) &&
           BothInputsMaybe(Type::String());
90 91
  }

92
  bool IsSymbolCompareOperation() {
93 94 95 96
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    return (CompareOperationHintOf(node_->op()) ==
            CompareOperationHint::kSymbol) &&
           BothInputsMaybe(Type::Symbol());
97 98
  }

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  // Check if a string addition will definitely result in creating a ConsString,
  // i.e. if the combined length of the resulting string exceeds the ConsString
  // minimum length.
  bool ShouldCreateConsString() {
    DCHECK_EQ(IrOpcode::kJSAdd, node_->opcode());
    DCHECK(OneInputIs(Type::String()));
    if (BothInputsAre(Type::String()) ||
        BinaryOperationHintOf(node_->op()) == BinaryOperationHint::kString) {
      HeapObjectBinopMatcher m(node_);
      JSHeapBroker* broker = lowering_->broker();
      if (m.right().HasValue() && m.right().Ref(broker).IsString()) {
        StringRef right_string = m.right().Ref(broker).AsString();
        if (right_string.length() >= ConsString::kMinLength) return true;
      }
      if (m.left().HasValue() && m.left().Ref(broker).IsString()) {
        StringRef left_string = m.left().Ref(broker).AsString();
        if (left_string.length() >= ConsString::kMinLength) {
          // The invariant for ConsString requires the left hand side to be
          // a sequential or external string if the right hand side is the
          // empty string. Since we don't know anything about the right hand
          // side here, we must ensure that the left hand side satisfy the
          // constraints independent of the right hand side.
          return left_string.IsSeqString() || left_string.IsExternalString();
        }
      }
    }
    return false;
  }

128 129 130 131 132 133 134 135
  // Inserts a CheckReceiver for the left input.
  void CheckLeftInputToReceiver() {
    Node* left_input = graph()->NewNode(simplified()->CheckReceiver(), left(),
                                        effect(), control());
    node_->ReplaceInput(0, left_input);
    update_effect(left_input);
  }

136 137 138 139 140
  // Inserts a CheckReceiverOrNullOrUndefined for the left input.
  void CheckLeftInputToReceiverOrNullOrUndefined() {
    Node* left_input =
        graph()->NewNode(simplified()->CheckReceiverOrNullOrUndefined(), left(),
                         effect(), control());
141 142 143 144
    node_->ReplaceInput(0, left_input);
    update_effect(left_input);
  }

145 146 147 148
  // Checks that both inputs are Receiver, and if we don't know
  // statically that one side is already a Receiver, insert a
  // CheckReceiver node.
  void CheckInputsToReceiver() {
149
    if (!left_type().Is(Type::Receiver())) {
150 151
      CheckLeftInputToReceiver();
    }
152
    if (!right_type().Is(Type::Receiver())) {
153 154 155 156 157 158 159
      Node* right_input = graph()->NewNode(simplified()->CheckReceiver(),
                                           right(), effect(), control());
      node_->ReplaceInput(1, right_input);
      update_effect(right_input);
    }
  }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  // Checks that both inputs are Receiver, Null or Undefined and if
  // we don't know statically that one side is already a Receiver,
  // Null or Undefined, insert CheckReceiverOrNullOrUndefined nodes.
  void CheckInputsToReceiverOrNullOrUndefined() {
    if (!left_type().Is(Type::ReceiverOrNullOrUndefined())) {
      CheckLeftInputToReceiverOrNullOrUndefined();
    }
    if (!right_type().Is(Type::ReceiverOrNullOrUndefined())) {
      Node* right_input =
          graph()->NewNode(simplified()->CheckReceiverOrNullOrUndefined(),
                           right(), effect(), control());
      node_->ReplaceInput(1, right_input);
      update_effect(right_input);
    }
  }

176 177 178 179 180 181 182 183
  // Inserts a CheckSymbol for the left input.
  void CheckLeftInputToSymbol() {
    Node* left_input = graph()->NewNode(simplified()->CheckSymbol(), left(),
                                        effect(), control());
    node_->ReplaceInput(0, left_input);
    update_effect(left_input);
  }

184 185 186 187
  // Checks that both inputs are Symbol, and if we don't know
  // statically that one side is already a Symbol, insert a
  // CheckSymbol node.
  void CheckInputsToSymbol() {
188
    if (!left_type().Is(Type::Symbol())) {
189
      CheckLeftInputToSymbol();
190
    }
191
    if (!right_type().Is(Type::Symbol())) {
192 193 194 195 196 197 198
      Node* right_input = graph()->NewNode(simplified()->CheckSymbol(), right(),
                                           effect(), control());
      node_->ReplaceInput(1, right_input);
      update_effect(right_input);
    }
  }

199 200 201 202
  // Checks that both inputs are String, and if we don't know
  // statically that one side is already a String, insert a
  // CheckString node.
  void CheckInputsToString() {
203
    if (!left_type().Is(Type::String())) {
204
      Node* left_input =
205
          graph()->NewNode(simplified()->CheckString(FeedbackSource()), left(),
206
                           effect(), control());
207 208 209
      node_->ReplaceInput(0, left_input);
      update_effect(left_input);
    }
210
    if (!right_type().Is(Type::String())) {
211
      Node* right_input =
212
          graph()->NewNode(simplified()->CheckString(FeedbackSource()), right(),
213
                           effect(), control());
214 215 216 217 218
      node_->ReplaceInput(1, right_input);
      update_effect(right_input);
    }
  }

219 220 221 222
  // Checks that both inputs are InternalizedString, and if we don't know
  // statically that one side is already an InternalizedString, insert a
  // CheckInternalizedString node.
  void CheckInputsToInternalizedString() {
223
    if (!left_type().Is(Type::UniqueName())) {
224 225 226 227 228
      Node* left_input = graph()->NewNode(
          simplified()->CheckInternalizedString(), left(), effect(), control());
      node_->ReplaceInput(0, left_input);
      update_effect(left_input);
    }
229
    if (!right_type().Is(Type::UniqueName())) {
230 231 232 233 234 235 236 237
      Node* right_input =
          graph()->NewNode(simplified()->CheckInternalizedString(), right(),
                           effect(), control());
      node_->ReplaceInput(1, right_input);
      update_effect(right_input);
    }
  }

238
  void ConvertInputsToNumber() {
239 240
    DCHECK(left_type().Is(Type::PlainPrimitive()));
    DCHECK(right_type().Is(Type::PlainPrimitive()));
241 242
    node_->ReplaceInput(0, ConvertPlainPrimitiveToNumber(left()));
    node_->ReplaceInput(1, ConvertPlainPrimitiveToNumber(right()));
243 244
  }

245 246 247 248
  void ConvertInputsToUI32(Signedness left_signedness,
                           Signedness right_signedness) {
    node_->ReplaceInput(0, ConvertToUI32(left(), left_signedness));
    node_->ReplaceInput(1, ConvertToUI32(right(), right_signedness));
249 250 251 252 253 254 255 256 257 258
  }

  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
259
  // to the pure operator {op}.
260
  Reduction ChangeToPureOperator(const Operator* op, Type type = Type::Any()) {
261
    DCHECK_EQ(0, op->EffectInputCount());
262
    DCHECK_EQ(false, OperatorProperties::HasContextInput(op));
263
    DCHECK_EQ(0, op->ControlInputCount());
264
    DCHECK_EQ(2, op->ValueInputCount());
265

266
    // Remove the effects from the node, and update its effect/control usages.
267
    if (node_->op()->EffectInputCount() > 0) {
268
      lowering_->RelaxEffectsAndControls(node_);
269
    }
270 271
    // Remove the inputs corresponding to context, effect, and control.
    NodeProperties::RemoveNonValueInputs(node_);
272
    // Finally, update the operator to the new one.
273
    NodeProperties::ChangeOp(node_, op);
274

275 276
    // TODO(jarin): Replace the explicit typing hack with a call to some method
    // that encapsulates changing the operator and re-typing.
277
    Type node_type = NodeProperties::GetType(node_);
278
    NodeProperties::SetType(node_, Type::Intersect(node_type, type, zone()));
279

280 281 282
    return lowering_->Changed(node_);
  }

283
  Reduction ChangeToSpeculativeOperator(const Operator* op, Type upper_bound) {
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    DCHECK_EQ(1, op->EffectInputCount());
    DCHECK_EQ(1, op->EffectOutputCount());
    DCHECK_EQ(false, OperatorProperties::HasContextInput(op));
    DCHECK_EQ(1, op->ControlInputCount());
    DCHECK_EQ(0, op->ControlOutputCount());
    DCHECK_EQ(0, OperatorProperties::GetFrameStateInputCount(op));
    DCHECK_EQ(2, op->ValueInputCount());

    DCHECK_EQ(1, node_->op()->EffectInputCount());
    DCHECK_EQ(1, node_->op()->EffectOutputCount());
    DCHECK_EQ(1, node_->op()->ControlInputCount());
    DCHECK_EQ(2, node_->op()->ValueInputCount());

    // Reconnect the control output to bypass the IfSuccess node and
    // possibly disconnect from the IfException node.
299
    lowering_->RelaxControls(node_);
300 301 302 303 304 305 306 307 308 309

    // Remove the frame state and the context.
    if (OperatorProperties::HasFrameStateInput(node_->op())) {
      node_->RemoveInput(NodeProperties::FirstFrameStateIndex(node_));
    }
    node_->RemoveInput(NodeProperties::FirstContextIndex(node_));

    NodeProperties::ChangeOp(node_, op);

    // Update the type to number.
310
    Type node_type = NodeProperties::GetType(node_);
311 312 313 314 315 316
    NodeProperties::SetType(node_,
                            Type::Intersect(node_type, upper_bound, zone()));

    return lowering_->Changed(node_);
  }

317 318 319 320 321 322 323 324 325 326 327 328
  const Operator* NumberOp() {
    switch (node_->opcode()) {
      case IrOpcode::kJSAdd:
        return simplified()->NumberAdd();
      case IrOpcode::kJSSubtract:
        return simplified()->NumberSubtract();
      case IrOpcode::kJSMultiply:
        return simplified()->NumberMultiply();
      case IrOpcode::kJSDivide:
        return simplified()->NumberDivide();
      case IrOpcode::kJSModulus:
        return simplified()->NumberModulus();
329 330
      case IrOpcode::kJSExponentiate:
        return simplified()->NumberPow();
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      case IrOpcode::kJSBitwiseAnd:
        return simplified()->NumberBitwiseAnd();
      case IrOpcode::kJSBitwiseOr:
        return simplified()->NumberBitwiseOr();
      case IrOpcode::kJSBitwiseXor:
        return simplified()->NumberBitwiseXor();
      case IrOpcode::kJSShiftLeft:
        return simplified()->NumberShiftLeft();
      case IrOpcode::kJSShiftRight:
        return simplified()->NumberShiftRight();
      case IrOpcode::kJSShiftRightLogical:
        return simplified()->NumberShiftRightLogical();
      default:
        break;
    }
    UNREACHABLE();
  }

349
  bool LeftInputIs(Type t) { return left_type().Is(t); }
350

351
  bool RightInputIs(Type t) { return right_type().Is(t); }
352

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

355
  bool BothInputsAre(Type t) { return LeftInputIs(t) && RightInputIs(t); }
356

357
  bool BothInputsMaybe(Type t) {
358
    return left_type().Maybe(t) && right_type().Maybe(t);
359 360
  }

361
  bool OneInputCannotBe(Type t) {
362
    return !left_type().Maybe(t) || !right_type().Maybe(t);
363 364
  }

365
  bool NeitherInputCanBe(Type t) {
366
    return !left_type().Maybe(t) && !right_type().Maybe(t);
367 368 369 370 371 372 373
  }

  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); }
374 375 376
  Type left_type() { return NodeProperties::GetType(node_->InputAt(0)); }
  Type right_type() { return NodeProperties::GetType(node_->InputAt(1)); }
  Type type() { return NodeProperties::GetType(node_); }
377 378

  SimplifiedOperatorBuilder* simplified() { return lowering_->simplified(); }
379
  Graph* graph() const { return lowering_->graph(); }
380
  JSGraph* jsgraph() { return lowering_->jsgraph(); }
381
  Isolate* isolate() { return jsgraph()->isolate(); }
382
  JSOperatorBuilder* javascript() { return lowering_->javascript(); }
383
  CommonOperatorBuilder* common() { return jsgraph()->common(); }
384
  Zone* zone() const { return graph()->zone(); }
385 386 387 388 389

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

390
  Node* ConvertPlainPrimitiveToNumber(Node* node) {
391
    DCHECK(NodeProperties::GetType(node).Is(Type::PlainPrimitive()));
392
    // Avoid inserting too many eager ToNumber() operations.
393
    Reduction const reduction = lowering_->ReduceJSToNumberInput(node);
394
    if (reduction.Changed()) return reduction.replacement();
395
    if (NodeProperties::GetType(node).Is(Type::Number())) {
396 397
      return node;
    }
398
    return graph()->NewNode(simplified()->PlainPrimitiveToNumber(), node);
399 400
  }

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

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


423 424 425 426
// 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

427
JSTypedLowering::JSTypedLowering(Editor* editor, JSGraph* jsgraph,
428
                                 JSHeapBroker* broker, Zone* zone)
429 430
    : AdvancedReducer(editor),
      jsgraph_(jsgraph),
431
      broker_(broker),
432 433
      empty_string_type_(
          Type::Constant(broker, factory()->empty_string(), graph()->zone())),
434 435
      pointer_comparable_type_(
          Type::Union(Type::Oddball(),
436
                      Type::Union(Type::SymbolOrReceiver(), empty_string_type_,
437 438
                                  graph()->zone()),
                      graph()->zone())),
439
      type_cache_(TypeCache::Get()) {}
440

441 442
Reduction JSTypedLowering::ReduceJSBitwiseNot(Node* node) {
  Node* input = NodeProperties::GetValueInput(node, 0);
443
  Type input_type = NodeProperties::GetType(input);
444
  if (input_type.Is(Type::PlainPrimitive())) {
445 446 447 448 449 450 451 452 453 454 455
    // JSBitwiseNot(x) => NumberBitwiseXor(ToInt32(x), -1)
    node->InsertInput(graph()->zone(), 1, jsgraph()->SmiConstant(-1));
    NodeProperties::ChangeOp(node, javascript()->BitwiseXor());
    JSBinopReduction r(this, node);
    r.ConvertInputsToNumber();
    r.ConvertInputsToUI32(kSigned, kSigned);
    return r.ChangeToPureOperator(r.NumberOp(), Type::Signed32());
  }
  return NoChange();
}

456 457
Reduction JSTypedLowering::ReduceJSDecrement(Node* node) {
  Node* input = NodeProperties::GetValueInput(node, 0);
458
  Type input_type = NodeProperties::GetType(input);
459
  if (input_type.Is(Type::PlainPrimitive())) {
460 461 462 463 464 465 466 467 468 469 470 471 472
    // JSDecrement(x) => NumberSubtract(ToNumber(x), 1)
    node->InsertInput(graph()->zone(), 1, jsgraph()->OneConstant());
    NodeProperties::ChangeOp(node, javascript()->Subtract());
    JSBinopReduction r(this, node);
    r.ConvertInputsToNumber();
    DCHECK_EQ(simplified()->NumberSubtract(), r.NumberOp());
    return r.ChangeToPureOperator(r.NumberOp(), Type::Number());
  }
  return NoChange();
}

Reduction JSTypedLowering::ReduceJSIncrement(Node* node) {
  Node* input = NodeProperties::GetValueInput(node, 0);
473
  Type input_type = NodeProperties::GetType(input);
474
  if (input_type.Is(Type::PlainPrimitive())) {
475 476 477 478 479 480 481 482 483 484 485 486
    // JSIncrement(x) => NumberAdd(ToNumber(x), 1)
    node->InsertInput(graph()->zone(), 1, jsgraph()->OneConstant());
    BinaryOperationHint hint = BinaryOperationHint::kAny;  // Dummy.
    NodeProperties::ChangeOp(node, javascript()->Add(hint));
    JSBinopReduction r(this, node);
    r.ConvertInputsToNumber();
    DCHECK_EQ(simplified()->NumberAdd(), r.NumberOp());
    return r.ChangeToPureOperator(r.NumberOp(), Type::Number());
  }
  return NoChange();
}

487 488
Reduction JSTypedLowering::ReduceJSNegate(Node* node) {
  Node* input = NodeProperties::GetValueInput(node, 0);
489
  Type input_type = NodeProperties::GetType(input);
490
  if (input_type.Is(Type::PlainPrimitive())) {
491 492 493 494 495 496 497 498 499 500
    // JSNegate(x) => NumberMultiply(ToNumber(x), -1)
    node->InsertInput(graph()->zone(), 1, jsgraph()->SmiConstant(-1));
    NodeProperties::ChangeOp(node, javascript()->Multiply());
    JSBinopReduction r(this, node);
    r.ConvertInputsToNumber();
    return r.ChangeToPureOperator(r.NumberOp(), Type::Number());
  }
  return NoChange();
}

501 502
Reduction JSTypedLowering::ReduceJSAdd(Node* node) {
  JSBinopReduction r(this, node);
503
  if (r.BothInputsAre(Type::Number())) {
504
    // JSAdd(x:number, y:number) => NumberAdd(x, y)
505
    return r.ChangeToPureOperator(simplified()->NumberAdd(), Type::Number());
506
  }
507
  if (r.BothInputsAre(Type::PlainPrimitive()) &&
508
      r.NeitherInputCanBe(Type::StringOrReceiver())) {
509
    // JSAdd(x:-string, y:-string) => NumberAdd(ToNumber(x), ToNumber(y))
510
    r.ConvertInputsToNumber();
511
    return r.ChangeToPureOperator(simplified()->NumberAdd(), Type::Number());
512
  }
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

  // Strength-reduce if one input is already known to be a string.
  if (r.LeftInputIs(Type::String())) {
    // JSAdd(x:string, y) => JSAdd(x, JSToString(y))
    Reduction const reduction = ReduceJSToStringInput(r.right());
    if (reduction.Changed()) {
      NodeProperties::ReplaceValueInput(node, reduction.replacement(), 1);
    }
  } else if (r.RightInputIs(Type::String())) {
    // JSAdd(x, y:string) => JSAdd(JSToString(x), y)
    Reduction const reduction = ReduceJSToStringInput(r.left());
    if (reduction.Changed()) {
      NodeProperties::ReplaceValueInput(node, reduction.replacement(), 0);
    }
  }

  // Always bake in String feedback into the graph.
530
  if (BinaryOperationHintOf(node->op()) == BinaryOperationHint::kString) {
531 532
    r.CheckInputsToString();
  }
533 534 535 536 537

  // Strength-reduce concatenation of empty strings if both sides are
  // primitives, as in that case the ToPrimitive on the other side is
  // definitely going to be a no-op.
  if (r.BothInputsAre(Type::Primitive())) {
538
    if (r.LeftInputIs(empty_string_type_)) {
539 540 541
      // JSAdd("", x:primitive) => JSToString(x)
      NodeProperties::ReplaceValueInputs(node, r.right());
      NodeProperties::ChangeOp(node, javascript()->ToString());
542 543
      NodeProperties::SetType(
          node, Type::Intersect(r.type(), Type::String(), graph()->zone()));
544
      return Changed(node).FollowedBy(ReduceJSToString(node));
545
    } else if (r.RightInputIs(empty_string_type_)) {
546 547 548
      // JSAdd(x:primitive, "") => JSToString(x)
      NodeProperties::ReplaceValueInputs(node, r.left());
      NodeProperties::ChangeOp(node, javascript()->ToString());
549 550
      NodeProperties::SetType(
          node, Type::Intersect(r.type(), Type::String(), graph()->zone()));
551
      return Changed(node).FollowedBy(ReduceJSToString(node));
552
    }
553
  }
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  // Lower to string addition if both inputs are known to be strings.
  if (r.BothInputsAre(Type::String())) {
    Node* context = NodeProperties::GetContextInput(node);
    Node* frame_state = NodeProperties::GetFrameStateInput(node);
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);

    // Compute the resulting length.
    Node* left_length =
        graph()->NewNode(simplified()->StringLength(), r.left());
    Node* right_length =
        graph()->NewNode(simplified()->StringLength(), r.right());
    Node* length =
        graph()->NewNode(simplified()->NumberAdd(), left_length, right_length);

570 571
    PropertyCellRef string_length_protector(
        broker(), factory()->string_length_protector());
572 573
    if (string_length_protector.value().AsSmi() ==
        Protectors::kProtectorValid) {
574 575 576 577 578 579
      // We can just deoptimize if the {length} is out-of-bounds. Besides
      // generating a shorter code sequence than the version below, this
      // has the additional benefit of not holding on to the lazy {frame_state}
      // and thus potentially reduces the number of live ranges and allows for
      // more truncations.
      length = effect = graph()->NewNode(
580
          simplified()->CheckBounds(FeedbackSource()), length,
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
          jsgraph()->Constant(String::kMaxLength + 1), effect, control);
    } else {
      // Check if we would overflow the allowed maximum string length.
      Node* check =
          graph()->NewNode(simplified()->NumberLessThanOrEqual(), length,
                           jsgraph()->Constant(String::kMaxLength));
      Node* branch =
          graph()->NewNode(common()->Branch(BranchHint::kTrue), check, control);
      Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
      Node* efalse = effect;
      {
        // Throw a RangeError in case of overflow.
        Node* vfalse = efalse = if_false = graph()->NewNode(
            javascript()->CallRuntime(Runtime::kThrowInvalidStringLength),
            context, frame_state, efalse, if_false);

        // Update potential {IfException} uses of {node} to point to the
        // %ThrowInvalidStringLength runtime call node instead.
        Node* on_exception = nullptr;
        if (NodeProperties::IsExceptionalCall(node, &on_exception)) {
          NodeProperties::ReplaceControlInput(on_exception, vfalse);
          NodeProperties::ReplaceEffectInput(on_exception, efalse);
          if_false = graph()->NewNode(common()->IfSuccess(), vfalse);
          Revisit(on_exception);
        }
606

607 608 609 610 611 612 613
        // The above %ThrowInvalidStringLength runtime call is an unconditional
        // throw, making it impossible to return a successful completion in this
        // case. We simply connect the successful completion to the graph end.
        if_false = graph()->NewNode(common()->Throw(), efalse, if_false);
        // TODO(bmeurer): This should be on the AdvancedReducer somehow.
        NodeProperties::MergeControlToEnd(graph(), common(), if_false);
        Revisit(graph()->end());
614
      }
615 616
      control = graph()->NewNode(common()->IfTrue(), branch);
      length = effect =
617
          graph()->NewNode(common()->TypeGuard(type_cache_->kStringLengthType),
618
                           length, effect, control);
619
    }
620

621 622 623 624 625 626
    // TODO(bmeurer): Ideally this should always use StringConcat and decide to
    // optimize to NewConsString later during SimplifiedLowering, but for that
    // to work we need to know that it's safe to create a ConsString.
    Operator const* const op = r.ShouldCreateConsString()
                                   ? simplified()->NewConsString()
                                   : simplified()->StringConcat();
627 628 629 630 631 632
    Node* value = graph()->NewNode(op, length, r.left(), r.right());
    ReplaceWithValue(node, value, effect, control);
    return Replace(value);
  }

  // We never get here when we had String feedback.
633
  DCHECK_NE(BinaryOperationHint::kString, BinaryOperationHintOf(node->op()));
634
  if (r.OneInputIs(Type::String())) {
635 636 637 638 639 640
    StringAddFlags flags = STRING_ADD_CHECK_NONE;
    if (!r.LeftInputIs(Type::String())) {
      flags = STRING_ADD_CONVERT_LEFT;
    } else if (!r.RightInputIs(Type::String())) {
      flags = STRING_ADD_CONVERT_RIGHT;
    }
641 642 643 644 645 646 647
    Operator::Properties properties = node->op()->properties();
    if (r.NeitherInputCanBe(Type::Receiver())) {
      // Both sides are already strings, so we know that the
      // string addition will not cause any observable side
      // effects; it can still throw obviously.
      properties = Operator::kNoWrite | Operator::kNoDeopt;
    }
648

649 650
    // JSAdd(x:string, y) => CallStub[StringAdd](x, y)
    // JSAdd(x, y:string) => CallStub[StringAdd](x, y)
651
    Callable const callable = CodeFactory::StringAdd(isolate(), flags);
652
    auto call_descriptor = Linkage::GetStubCallDescriptor(
653 654
        graph()->zone(), callable.descriptor(),
        callable.descriptor().GetStackParameterCount(),
655
        CallDescriptor::kNeedsFrameState, properties);
656
    DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
657 658
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
659
    NodeProperties::ChangeOp(node, common()->Call(call_descriptor));
660 661
    return Changed(node);
  }
662 663 664
  return NoChange();
}

665
Reduction JSTypedLowering::ReduceNumberBinop(Node* node) {
666
  JSBinopReduction r(this, node);
667
  if (r.BothInputsAre(Type::PlainPrimitive())) {
668
    r.ConvertInputsToNumber();
669
    return r.ChangeToPureOperator(r.NumberOp(), Type::Number());
670 671
  }
  return NoChange();
672
}
673

674
Reduction JSTypedLowering::ReduceInt32Binop(Node* node) {
675
  JSBinopReduction r(this, node);
676
  if (r.BothInputsAre(Type::PlainPrimitive())) {
677 678
    r.ConvertInputsToNumber();
    r.ConvertInputsToUI32(kSigned, kSigned);
679
    return r.ChangeToPureOperator(r.NumberOp(), Type::Signed32());
680 681
  }
  return NoChange();
682 683
}

684
Reduction JSTypedLowering::ReduceUI32Shift(Node* node, Signedness signedness) {
685
  JSBinopReduction r(this, node);
686
  if (r.BothInputsAre(Type::PlainPrimitive())) {
687
    r.ConvertInputsToNumber();
688
    r.ConvertInputsToUI32(signedness, kUnsigned);
689 690 691
    return r.ChangeToPureOperator(r.NumberOp(), signedness == kUnsigned
                                                    ? Type::Unsigned32()
                                                    : Type::Signed32());
692 693 694
  }
  return NoChange();
}
695 696 697 698 699

Reduction JSTypedLowering::ReduceJSComparison(Node* node) {
  JSBinopReduction r(this, node);
  if (r.BothInputsAre(Type::String())) {
    // If both inputs are definitely strings, perform a string comparison.
700
    const Operator* stringOp;
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    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();
    }
719
    r.ChangeToPureOperator(stringOp);
720
    return Changed(node);
721
  }
722

723 724 725 726 727 728 729
  const Operator* less_than;
  const Operator* less_than_or_equal;
  if (r.BothInputsAre(Type::Signed32()) ||
      r.BothInputsAre(Type::Unsigned32())) {
    less_than = simplified()->NumberLessThan();
    less_than_or_equal = simplified()->NumberLessThanOrEqual();
  } else if (r.OneInputCannotBe(Type::StringOrReceiver()) &&
730
             r.BothInputsAre(Type::PlainPrimitive())) {
731 732 733
    r.ConvertInputsToNumber();
    less_than = simplified()->NumberLessThan();
    less_than_or_equal = simplified()->NumberLessThanOrEqual();
734 735 736 737
  } else if (r.IsStringCompareOperation()) {
    r.CheckInputsToString();
    less_than = simplified()->StringLessThan();
    less_than_or_equal = simplified()->StringLessThanOrEqual();
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
  } else {
    return NoChange();
  }
  const Operator* comparison;
  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:
758
      return NoChange();
759
  }
760
  return r.ChangeToPureOperator(comparison);
761 762
}

763
Reduction JSTypedLowering::ReduceJSEqual(Node* node) {
764 765
  JSBinopReduction r(this, node);

766
  if (r.BothInputsAre(Type::UniqueName())) {
767
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
768 769 770
  }
  if (r.IsInternalizedStringCompareOperation()) {
    r.CheckInputsToInternalizedString();
771
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
772
  }
773
  if (r.BothInputsAre(Type::String())) {
774
    return r.ChangeToPureOperator(simplified()->StringEqual());
775
  }
776
  if (r.BothInputsAre(Type::Boolean())) {
777
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
778
  }
779
  if (r.BothInputsAre(Type::Receiver())) {
780
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
781
  }
782
  if (r.OneInputIs(Type::NullOrUndefined())) {
783
    RelaxEffectsAndControls(node);
784
    node->RemoveInput(r.LeftInputIs(Type::NullOrUndefined()) ? 0 : 1);
785 786
    node->TrimInputCount(1);
    NodeProperties::ChangeOp(node, simplified()->ObjectIsUndetectable());
787 788
    return Changed(node);
  }
789 790 791

  if (r.BothInputsAre(Type::Signed32()) ||
      r.BothInputsAre(Type::Unsigned32())) {
792
    return r.ChangeToPureOperator(simplified()->NumberEqual());
793
  } else if (r.BothInputsAre(Type::Number())) {
794
    return r.ChangeToPureOperator(simplified()->NumberEqual());
795 796
  } else if (r.IsReceiverCompareOperation()) {
    r.CheckInputsToReceiver();
797
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
798 799 800 801 802 803 804 805 806 807 808 809 810 811
  } else if (r.IsReceiverOrNullOrUndefinedCompareOperation()) {
    // Check that both inputs are Receiver, Null or Undefined.
    r.CheckInputsToReceiverOrNullOrUndefined();

    // If one side is known to be a detectable receiver now, we
    // can simply perform reference equality here, since this
    // known detectable receiver is going to only match itself.
    if (r.OneInputIs(Type::DetectableReceiver())) {
      return r.ChangeToPureOperator(simplified()->ReferenceEqual());
    }

    // Known that both sides are Receiver, Null or Undefined, the
    // abstract equality operation can be performed like this:
    //
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    // if left == undefined || left == null
    //    then ObjectIsUndetectable(right)
    // else if right == undefined || right == null
    //    then ObjectIsUndetectable(left)
    // else ReferenceEqual(left, right)
#define __ gasm.
    JSGraphAssembler gasm(jsgraph(), jsgraph()->zone());
    gasm.InitializeEffectControl(r.effect(), r.control());

    auto lhs = TNode<Object>::UncheckedCast(r.left());
    auto rhs = TNode<Object>::UncheckedCast(r.right());

    auto done = __ MakeLabel(MachineRepresentation::kTagged);
    auto check_undetectable = __ MakeLabel(MachineRepresentation::kTagged);

    __ GotoIf(__ ReferenceEqual(lhs, __ UndefinedConstant()),
              &check_undetectable, rhs);
    __ GotoIf(__ ReferenceEqual(lhs, __ NullConstant()), &check_undetectable,
              rhs);
    __ GotoIf(__ ReferenceEqual(rhs, __ UndefinedConstant()),
              &check_undetectable, lhs);
    __ GotoIf(__ ReferenceEqual(rhs, __ NullConstant()), &check_undetectable,
              lhs);
    __ Goto(&done, __ ReferenceEqual(lhs, rhs));

    __ Bind(&check_undetectable);
    __ Goto(&done,
            __ ObjectIsUndetectable(check_undetectable.PhiAt<Object>(0)));

    __ Bind(&done);
    Node* value = done.PhiAt(0);
    ReplaceWithValue(node, value, gasm.effect(), gasm.control());
844
    return Replace(value);
845
#undef __
846 847
  } else if (r.IsStringCompareOperation()) {
    r.CheckInputsToString();
848
    return r.ChangeToPureOperator(simplified()->StringEqual());
849 850 851
  } else if (r.IsSymbolCompareOperation()) {
    r.CheckInputsToSymbol();
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
852
  }
853 854 855
  return NoChange();
}

856
Reduction JSTypedLowering::ReduceJSStrictEqual(Node* node) {
857
  JSBinopReduction r(this, node);
858 859 860 861
  if (r.type().IsSingleton()) {
    // Let ConstantFoldingReducer handle this.
    return NoChange();
  }
862 863
  if (r.left() == r.right()) {
    // x === x is always true if x != NaN
864 865 866
    Node* replacement = graph()->NewNode(
        simplified()->BooleanNot(),
        graph()->NewNode(simplified()->ObjectIsNaN(), r.left()));
867
    DCHECK(NodeProperties::GetType(replacement).Is(r.type()));
868 869
    ReplaceWithValue(node, replacement);
    return Replace(replacement);
870
  }
871

872
  if (r.BothInputsAre(Type::Unique())) {
873
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
874
  }
875
  if (r.OneInputIs(pointer_comparable_type_)) {
876
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
877
  }
878 879
  if (r.IsInternalizedStringCompareOperation()) {
    r.CheckInputsToInternalizedString();
880
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
881
  }
882
  if (r.BothInputsAre(Type::String())) {
883
    return r.ChangeToPureOperator(simplified()->StringEqual());
884
  }
885

886
  NumberOperationHint hint;
887 888
  if (r.BothInputsAre(Type::Signed32()) ||
      r.BothInputsAre(Type::Unsigned32())) {
889
    return r.ChangeToPureOperator(simplified()->NumberEqual());
890
  } else if (r.GetCompareNumberOperationHint(&hint)) {
891
    return r.ChangeToSpeculativeOperator(
892
        simplified()->SpeculativeNumberEqual(hint), Type::Boolean());
893
  } else if (r.BothInputsAre(Type::Number())) {
894
    return r.ChangeToPureOperator(simplified()->NumberEqual());
895 896 897
  } else if (r.IsReceiverCompareOperation()) {
    // For strict equality, it's enough to know that one input is a Receiver,
    // as a strict equality comparison with a Receiver can only yield true if
898
    // both sides refer to the same Receiver.
899
    r.CheckLeftInputToReceiver();
900
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
901 902 903 904 905 906
  } else if (r.IsReceiverOrNullOrUndefinedCompareOperation()) {
    // For strict equality, it's enough to know that one input is a Receiver,
    // Null or Undefined, as a strict equality comparison with a Receiver,
    // Null or Undefined can only yield true if both sides refer to the same
    // instance.
    r.CheckLeftInputToReceiverOrNullOrUndefined();
907
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
908 909
  } else if (r.IsStringCompareOperation()) {
    r.CheckInputsToString();
910
    return r.ChangeToPureOperator(simplified()->StringEqual());
911
  } else if (r.IsSymbolCompareOperation()) {
912 913 914 915
    // For strict equality, it's enough to know that one input is a Symbol,
    // as a strict equality comparison with a Symbol can only yield true if
    // both sides refer to the same Symbol.
    r.CheckLeftInputToSymbol();
916
    return r.ChangeToPureOperator(simplified()->ReferenceEqual());
917 918 919 920
  }
  return NoChange();
}

921 922
Reduction JSTypedLowering::ReduceJSToName(Node* node) {
  Node* const input = NodeProperties::GetValueInput(node, 0);
923
  Type const input_type = NodeProperties::GetType(input);
924
  if (input_type.Is(Type::Name())) {
925 926 927 928 929 930 931
    // JSToName(x:name) => x
    ReplaceWithValue(node, input);
    return Replace(input);
  }
  return NoChange();
}

932 933
Reduction JSTypedLowering::ReduceJSToLength(Node* node) {
  Node* input = NodeProperties::GetValueInput(node, 0);
934
  Type input_type = NodeProperties::GetType(input);
935
  if (input_type.Is(type_cache_->kIntegerOrMinusZero)) {
936
    if (input_type.IsNone() || input_type.Max() <= 0.0) {
937
      input = jsgraph()->ZeroConstant();
938
    } else if (input_type.Min() >= kMaxSafeInteger) {
939 940
      input = jsgraph()->Constant(kMaxSafeInteger);
    } else {
941
      if (input_type.Min() <= 0.0) {
942 943
        input = graph()->NewNode(simplified()->NumberMax(),
                                 jsgraph()->ZeroConstant(), input);
944
      }
945
      if (input_type.Max() > kMaxSafeInteger) {
946 947
        input = graph()->NewNode(simplified()->NumberMin(),
                                 jsgraph()->Constant(kMaxSafeInteger), input);
948 949 950 951 952 953 954
      }
    }
    ReplaceWithValue(node, input);
    return Replace(input);
  }
  return NoChange();
}
955

956 957
Reduction JSTypedLowering::ReduceJSToNumberInput(Node* input) {
  // Try constant-folding of JSToNumber with constant inputs.
958
  Type input_type = NodeProperties::GetType(input);
959

960
  if (input_type.Is(Type::String())) {
961
    HeapObjectMatcher m(input);
962 963
    if (m.HasValue() && m.Ref(broker()).IsString()) {
      StringRef input_value = m.Ref(broker()).AsString();
964 965 966
      double number;
      ASSIGN_RETURN_NO_CHANGE_IF_DATA_MISSING(number, input_value.ToNumber());
      return Replace(jsgraph()->Constant(number));
967 968
    }
  }
969
  if (input_type.IsHeapConstant()) {
970
    HeapObjectRef input_value = input_type.AsHeapConstant()->Ref();
971 972 973
    double value;
    if (input_value.OddballToNumber().To(&value)) {
      return Replace(jsgraph()->Constant(value));
974 975
    }
  }
976
  if (input_type.Is(Type::Number())) {
977 978 979
    // JSToNumber(x:number) => x
    return Changed(input);
  }
980
  if (input_type.Is(Type::Undefined())) {
981 982 983
    // JSToNumber(undefined) => #NaN
    return Replace(jsgraph()->NaNConstant());
  }
984
  if (input_type.Is(Type::Null())) {
985 986 987 988 989 990
    // JSToNumber(null) => #0
    return Replace(jsgraph()->ZeroConstant());
  }
  return NoChange();
}

991
Reduction JSTypedLowering::ReduceJSToNumber(Node* node) {
992 993
  // Try to reduce the input first.
  Node* const input = node->InputAt(0);
994
  Reduction reduction = ReduceJSToNumberInput(input);
995
  if (reduction.Changed()) {
996
    ReplaceWithValue(node, reduction.replacement());
997 998
    return reduction;
  }
999
  Type const input_type = NodeProperties::GetType(input);
1000
  if (input_type.Is(Type::PlainPrimitive())) {
1001 1002
    RelaxEffectsAndControls(node);
    node->TrimInputCount(1);
1003
    // For a PlainPrimitive, ToNumeric is the same as ToNumber.
1004
    Type node_type = NodeProperties::GetType(node);
1005 1006
    NodeProperties::SetType(
        node, Type::Intersect(node_type, Type::Number(), graph()->zone()));
1007 1008
    NodeProperties::ChangeOp(node, simplified()->PlainPrimitiveToNumber());
    return Changed(node);
1009
  }
1010 1011 1012 1013 1014 1015
  return NoChange();
}

Reduction JSTypedLowering::ReduceJSToNumeric(Node* node) {
  Node* const input = NodeProperties::GetValueInput(node, 0);
  Type const input_type = NodeProperties::GetType(input);
1016 1017
  if (input_type.Is(Type::NonBigIntPrimitive())) {
    // ToNumeric(x:primitive\bigint) => ToNumber(x)
1018
    NodeProperties::ChangeOp(node, javascript()->ToNumber());
1019
    return Changed(node).FollowedBy(ReduceJSToNumber(node));
1020
  }
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  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)
  }
1031
  Type input_type = NodeProperties::GetType(input);
1032
  if (input_type.Is(Type::String())) {
1033 1034
    return Changed(input);  // JSToString(x:string) => x
  }
1035
  if (input_type.Is(Type::Boolean())) {
1036 1037 1038 1039
    return Replace(graph()->NewNode(
        common()->Select(MachineRepresentation::kTagged), input,
        jsgraph()->HeapConstant(factory()->true_string()),
        jsgraph()->HeapConstant(factory()->false_string())));
1040
  }
1041
  if (input_type.Is(Type::Undefined())) {
1042 1043
    return Replace(jsgraph()->HeapConstant(factory()->undefined_string()));
  }
1044
  if (input_type.Is(Type::Null())) {
1045 1046
    return Replace(jsgraph()->HeapConstant(factory()->null_string()));
  }
1047
  if (input_type.Is(Type::NaN())) {
1048 1049
    return Replace(jsgraph()->HeapConstant(factory()->NaN_string()));
  }
1050
  if (input_type.Is(Type::Number())) {
1051 1052
    return Replace(graph()->NewNode(simplified()->NumberToString(), input));
  }
1053 1054 1055 1056
  return NoChange();
}

Reduction JSTypedLowering::ReduceJSToString(Node* node) {
1057
  DCHECK_EQ(IrOpcode::kJSToString, node->opcode());
1058 1059 1060 1061
  // Try to reduce the input first.
  Node* const input = node->InputAt(0);
  Reduction reduction = ReduceJSToStringInput(input);
  if (reduction.Changed()) {
1062
    ReplaceWithValue(node, reduction.replacement());
1063 1064 1065 1066 1067
    return reduction;
  }
  return NoChange();
}

1068 1069 1070
Reduction JSTypedLowering::ReduceJSToObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSToObject, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
1071
  Type receiver_type = NodeProperties::GetType(receiver);
1072
  Node* context = NodeProperties::GetContextInput(node);
1073
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
1074 1075
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
1076
  if (receiver_type.Is(Type::Receiver())) {
1077 1078 1079
    ReplaceWithValue(node, receiver, effect, control);
    return Replace(receiver);
  }
1080

1081 1082 1083 1084
  // Check whether {receiver} is a spec object.
  Node* check = graph()->NewNode(simplified()->ObjectIsReceiver(), receiver);
  Node* branch =
      graph()->NewNode(common()->Branch(BranchHint::kTrue), check, control);
1085

1086 1087 1088
  Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
  Node* etrue = effect;
  Node* rtrue = receiver;
1089

1090 1091 1092 1093 1094
  Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
  Node* efalse = effect;
  Node* rfalse;
  {
    // Convert {receiver} using the ToObjectStub.
1095
    Callable callable = Builtins::CallableFor(isolate(), Builtins::kToObject);
1096
    auto call_descriptor = Linkage::GetStubCallDescriptor(
1097 1098
        graph()->zone(), callable.descriptor(),
        callable.descriptor().GetStackParameterCount(),
1099
        CallDescriptor::kNeedsFrameState, node->op()->properties());
1100 1101 1102 1103
    rfalse = efalse = if_false =
        graph()->NewNode(common()->Call(call_descriptor),
                         jsgraph()->HeapConstant(callable.code()), receiver,
                         context, frame_state, efalse, if_false);
1104 1105
  }

1106 1107 1108 1109
  // Update potential {IfException} uses of {node} to point to the above
  // ToObject stub call node instead. Note that the stub can only throw on
  // receivers that can be null or undefined.
  Node* on_exception = nullptr;
1110
  if (receiver_type.Maybe(Type::NullOrUndefined()) &&
1111 1112 1113 1114 1115 1116 1117
      NodeProperties::IsExceptionalCall(node, &on_exception)) {
    NodeProperties::ReplaceControlInput(on_exception, if_false);
    NodeProperties::ReplaceEffectInput(on_exception, efalse);
    if_false = graph()->NewNode(common()->IfSuccess(), if_false);
    Revisit(on_exception);
  }

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  control = graph()->NewNode(common()->Merge(2), if_true, if_false);
  effect = graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);

  // Morph the {node} into an appropriate Phi.
  ReplaceWithValue(node, node, effect, control);
  node->ReplaceInput(0, rtrue);
  node->ReplaceInput(1, rfalse);
  node->ReplaceInput(2, control);
  node->TrimInputCount(3);
  NodeProperties::ChangeOp(node,
                           common()->Phi(MachineRepresentation::kTagged, 2));
  return Changed(node);
}
1131

1132 1133 1134
Reduction JSTypedLowering::ReduceJSLoadNamed(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadNamed, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
1135
  Type receiver_type = NodeProperties::GetType(receiver);
1136 1137
  NameRef name(broker(), NamedAccessOf(node->op()).name());
  NameRef length_str(broker(), factory()->length_string());
1138
  // Optimize "length" property of strings.
1139
  if (name.equals(length_str) && receiver_type.Is(Type::String())) {
1140 1141
    Node* value = graph()->NewNode(simplified()->StringLength(), receiver);
    ReplaceWithValue(node, value);
1142 1143 1144 1145 1146
    return Replace(value);
  }
  return NoChange();
}

1147 1148 1149
Reduction JSTypedLowering::ReduceJSHasInPrototypeChain(Node* node) {
  DCHECK_EQ(IrOpcode::kJSHasInPrototypeChain, node->opcode());
  Node* value = NodeProperties::GetValueInput(node, 0);
1150
  Type value_type = NodeProperties::GetType(value);
1151 1152 1153 1154 1155 1156 1157 1158
  Node* prototype = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // If {value} cannot be a receiver, then it cannot have {prototype} in
  // it's prototype chain (all Primitive values have a null prototype).
1159
  if (value_type.Is(Type::Primitive())) {
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    Node* value = jsgraph()->FalseConstant();
    ReplaceWithValue(node, value, effect, control);
    return Replace(value);
  }

  Node* check0 = graph()->NewNode(simplified()->ObjectIsSmi(), value);
  Node* branch0 =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), check0, control);

  Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0);
  Node* etrue0 = effect;
  Node* vtrue0 = jsgraph()->FalseConstant();

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

  // Loop through the {value}s prototype chain looking for the {prototype}.
  Node* loop = control = graph()->NewNode(common()->Loop(2), control, control);
  Node* eloop = effect =
      graph()->NewNode(common()->EffectPhi(2), effect, effect, loop);
1179 1180
  Node* terminate = graph()->NewNode(common()->Terminate(), eloop, loop);
  NodeProperties::MergeControlToEnd(graph(), common(), terminate);
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 1234 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 1284 1285 1286 1287 1288
  Node* vloop = value = graph()->NewNode(
      common()->Phi(MachineRepresentation::kTagged, 2), value, value, loop);
  NodeProperties::SetType(vloop, Type::NonInternal());

  // Load the {value} map and instance type.
  Node* value_map = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMap()), value, effect, control);
  Node* value_instance_type = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapInstanceType()), value_map,
      effect, control);

  // Check if the {value} is a special receiver, because for special
  // receivers, i.e. proxies or API values that need access checks,
  // we have to use the %HasInPrototypeChain runtime function instead.
  Node* check1 = graph()->NewNode(
      simplified()->NumberLessThanOrEqual(), value_instance_type,
      jsgraph()->Constant(LAST_SPECIAL_RECEIVER_TYPE));
  Node* branch1 =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), check1, control);

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

  Node* if_true1 = graph()->NewNode(common()->IfTrue(), branch1);
  Node* etrue1 = effect;
  Node* vtrue1;

  // Check if the {value} is not a receiver at all.
  Node* check10 =
      graph()->NewNode(simplified()->NumberLessThan(), value_instance_type,
                       jsgraph()->Constant(FIRST_JS_RECEIVER_TYPE));
  Node* branch10 =
      graph()->NewNode(common()->Branch(BranchHint::kTrue), check10, if_true1);

  // A primitive value cannot match the {prototype} we're looking for.
  if_true1 = graph()->NewNode(common()->IfTrue(), branch10);
  vtrue1 = jsgraph()->FalseConstant();

  Node* if_false1 = graph()->NewNode(common()->IfFalse(), branch10);
  Node* efalse1 = etrue1;
  Node* vfalse1;
  {
    // Slow path, need to call the %HasInPrototypeChain runtime function.
    vfalse1 = efalse1 = if_false1 = graph()->NewNode(
        javascript()->CallRuntime(Runtime::kHasInPrototypeChain), value,
        prototype, context, frame_state, efalse1, if_false1);

    // Replace any potential {IfException} uses of {node} to catch
    // exceptions from this %HasInPrototypeChain runtime call instead.
    Node* on_exception = nullptr;
    if (NodeProperties::IsExceptionalCall(node, &on_exception)) {
      NodeProperties::ReplaceControlInput(on_exception, vfalse1);
      NodeProperties::ReplaceEffectInput(on_exception, efalse1);
      if_false1 = graph()->NewNode(common()->IfSuccess(), vfalse1);
      Revisit(on_exception);
    }
  }

  // Load the {value} prototype.
  Node* value_prototype = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapPrototype()), value_map,
      effect, control);

  // Check if we reached the end of {value}s prototype chain.
  Node* check2 = graph()->NewNode(simplified()->ReferenceEqual(),
                                  value_prototype, jsgraph()->NullConstant());
  Node* branch2 = graph()->NewNode(common()->Branch(), check2, control);

  Node* if_true2 = graph()->NewNode(common()->IfTrue(), branch2);
  Node* etrue2 = effect;
  Node* vtrue2 = jsgraph()->FalseConstant();

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

  // Check if we reached the {prototype}.
  Node* check3 = graph()->NewNode(simplified()->ReferenceEqual(),
                                  value_prototype, prototype);
  Node* branch3 = graph()->NewNode(common()->Branch(), check3, control);

  Node* if_true3 = graph()->NewNode(common()->IfTrue(), branch3);
  Node* etrue3 = effect;
  Node* vtrue3 = jsgraph()->TrueConstant();

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

  // Close the loop.
  vloop->ReplaceInput(1, value_prototype);
  eloop->ReplaceInput(1, effect);
  loop->ReplaceInput(1, control);

  control = graph()->NewNode(common()->Merge(5), if_true0, if_true1, if_true2,
                             if_true3, if_false1);
  effect = graph()->NewNode(common()->EffectPhi(5), etrue0, etrue1, etrue2,
                            etrue3, efalse1, control);

  // Morph the {node} into an appropriate Phi.
  ReplaceWithValue(node, node, effect, control);
  node->ReplaceInput(0, vtrue0);
  node->ReplaceInput(1, vtrue1);
  node->ReplaceInput(2, vtrue2);
  node->ReplaceInput(3, vtrue3);
  node->ReplaceInput(4, vfalse1);
  node->ReplaceInput(5, control);
  node->TrimInputCount(6);
  NodeProperties::ChangeOp(node,
                           common()->Phi(MachineRepresentation::kTagged, 5));
  return Changed(node);
}

1289 1290 1291
Reduction JSTypedLowering::ReduceJSOrdinaryHasInstance(Node* node) {
  DCHECK_EQ(IrOpcode::kJSOrdinaryHasInstance, node->opcode());
  Node* constructor = NodeProperties::GetValueInput(node, 0);
1292
  Type constructor_type = NodeProperties::GetType(constructor);
1293
  Node* object = NodeProperties::GetValueInput(node, 1);
1294
  Type object_type = NodeProperties::GetType(object);
1295

1296 1297
  // Check if the {constructor} cannot be callable.
  // See ES6 section 7.3.19 OrdinaryHasInstance ( C, O ) step 1.
1298
  if (!constructor_type.Maybe(Type::Callable())) {
1299
    Node* value = jsgraph()->FalseConstant();
1300
    ReplaceWithValue(node, value);
1301 1302 1303 1304 1305 1306
    return Replace(value);
  }

  // If the {constructor} cannot be a JSBoundFunction and then {object}
  // cannot be a JSReceiver, then this can be constant-folded to false.
  // See ES6 section 7.3.19 OrdinaryHasInstance ( C, O ) step 2 and 3.
1307 1308
  if (!object_type.Maybe(Type::Receiver()) &&
      !constructor_type.Maybe(Type::BoundFunction())) {
1309
    Node* value = jsgraph()->FalseConstant();
1310
    ReplaceWithValue(node, value);
1311 1312 1313
    return Replace(value);
  }

1314
  return NoChange();
1315 1316
}

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
Reduction JSTypedLowering::ReduceJSHasContextExtension(Node* node) {
  DCHECK_EQ(IrOpcode::kJSHasContextExtension, node->opcode());
  size_t depth = OpParameter<size_t>(node->op());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* context = NodeProperties::GetContextInput(node);
  Node* control = graph()->start();
  for (size_t i = 0; i < depth; ++i) {
    context = effect = graph()->NewNode(
        simplified()->LoadField(
            AccessBuilder::ForContextSlotKnownPointer(Context::PREVIOUS_INDEX)),
        context, effect, control);
  }
  Node* const scope_info = effect = graph()->NewNode(
      simplified()->LoadField(
          AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX)),
      context, effect, control);
  Node* scope_info_flags = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForScopeInfoFlags()), scope_info,
      effect, control);
  Node* flags_masked = graph()->NewNode(
      simplified()->NumberBitwiseAnd(), scope_info_flags,
1338
      jsgraph()->SmiConstant(ScopeInfo::HasContextExtensionSlotBit::kMask));
1339 1340 1341 1342 1343 1344 1345 1346
  Node* no_extension = graph()->NewNode(
      simplified()->NumberEqual(), flags_masked, jsgraph()->SmiConstant(0));
  Node* has_extension =
      graph()->NewNode(simplified()->BooleanNot(), no_extension);
  ReplaceWithValue(node, has_extension, effect, control);
  return Changed(node);
}

1347 1348 1349
Reduction JSTypedLowering::ReduceJSLoadContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadContext, node->opcode());
  ContextAccess const& access = ContextAccessOf(node->op());
1350
  Node* effect = NodeProperties::GetEffectInput(node);
1351
  Node* context = NodeProperties::GetContextInput(node);
1352
  Node* control = graph()->start();
1353
  for (size_t i = 0; i < access.depth(); ++i) {
1354
    context = effect = graph()->NewNode(
1355
        simplified()->LoadField(
1356
            AccessBuilder::ForContextSlotKnownPointer(Context::PREVIOUS_INDEX)),
1357
        context, effect, control);
1358
  }
1359
  node->ReplaceInput(0, context);
1360
  node->ReplaceInput(1, effect);
1361
  node->AppendInput(jsgraph()->zone(), control);
1362 1363 1364
  NodeProperties::ChangeOp(
      node,
      simplified()->LoadField(AccessBuilder::ForContextSlot(access.index())));
1365 1366 1367 1368 1369 1370
  return Changed(node);
}

Reduction JSTypedLowering::ReduceJSStoreContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreContext, node->opcode());
  ContextAccess const& access = ContextAccessOf(node->op());
1371
  Node* effect = NodeProperties::GetEffectInput(node);
1372
  Node* context = NodeProperties::GetContextInput(node);
1373
  Node* control = graph()->start();
1374
  Node* value = NodeProperties::GetValueInput(node, 0);
1375
  for (size_t i = 0; i < access.depth(); ++i) {
1376
    context = effect = graph()->NewNode(
1377
        simplified()->LoadField(
1378
            AccessBuilder::ForContextSlotKnownPointer(Context::PREVIOUS_INDEX)),
1379
        context, effect, control);
1380
  }
1381 1382
  node->ReplaceInput(0, context);
  node->ReplaceInput(1, value);
1383
  node->ReplaceInput(2, effect);
1384 1385 1386
  NodeProperties::ChangeOp(
      node,
      simplified()->StoreField(AccessBuilder::ForContextSlot(access.index())));
1387 1388 1389
  return Changed(node);
}

1390 1391 1392
Node* JSTypedLowering::BuildGetModuleCell(Node* node) {
  DCHECK(node->opcode() == IrOpcode::kJSLoadModule ||
         node->opcode() == IrOpcode::kJSStoreModule);
1393 1394 1395
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

1396
  int32_t cell_index = OpParameter<int32_t>(node->op());
1397
  Node* module = NodeProperties::GetValueInput(node, 0);
1398
  Type module_type = NodeProperties::GetType(module);
1399

1400
  if (module_type.IsHeapConstant()) {
1401 1402
    SourceTextModuleRef module_constant =
        module_type.AsHeapConstant()->Ref().AsSourceTextModule();
1403 1404
    base::Optional<CellRef> cell_constant = module_constant.GetCell(cell_index);
    if (cell_constant.has_value()) return jsgraph()->Constant(*cell_constant);
1405
  }
1406

1407
  FieldAccess field_access;
1408
  int index;
1409 1410
  if (SourceTextModuleDescriptor::GetCellIndexKind(cell_index) ==
      SourceTextModuleDescriptor::kExport) {
1411
    field_access = AccessBuilder::ForModuleRegularExports();
1412 1413
    index = cell_index - 1;
  } else {
1414 1415
    DCHECK_EQ(SourceTextModuleDescriptor::GetCellIndexKind(cell_index),
              SourceTextModuleDescriptor::kImport);
1416
    field_access = AccessBuilder::ForModuleRegularImports();
1417 1418
    index = -cell_index - 1;
  }
1419 1420 1421
  Node* array = effect = graph()->NewNode(simplified()->LoadField(field_access),
                                          module, effect, control);
  return graph()->NewNode(
1422 1423
      simplified()->LoadField(AccessBuilder::ForFixedArraySlot(index)), array,
      effect, control);
1424
}
1425

1426 1427 1428 1429 1430 1431 1432
Reduction JSTypedLowering::ReduceJSLoadModule(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadModule, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  Node* cell = BuildGetModuleCell(node);
  if (cell->op()->EffectOutputCount() > 0) effect = cell;
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
  Node* value = effect =
      graph()->NewNode(simplified()->LoadField(AccessBuilder::ForCellValue()),
                       cell, effect, control);

  ReplaceWithValue(node, value, effect, control);
  return Changed(value);
}

Reduction JSTypedLowering::ReduceJSStoreModule(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreModule, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* value = NodeProperties::GetValueInput(node, 1);
1446 1447 1448
  DCHECK_EQ(SourceTextModuleDescriptor::GetCellIndexKind(
                OpParameter<int32_t>(node->op())),
            SourceTextModuleDescriptor::kExport);
1449

1450 1451
  Node* cell = BuildGetModuleCell(node);
  if (cell->op()->EffectOutputCount() > 0) effect = cell;
1452 1453 1454 1455 1456 1457 1458 1459
  effect =
      graph()->NewNode(simplified()->StoreField(AccessBuilder::ForCellValue()),
                       cell, value, effect, control);

  ReplaceWithValue(node, effect, effect, control);
  return Changed(value);
}

1460 1461
namespace {

1462 1463
void ReduceBuiltin(JSGraph* jsgraph, Node* node, int builtin_index, int arity,
                   CallDescriptor::Flags flags) {
1464
  // Patch {node} to a direct CEntry call.
1465 1466
  //
  // ----------- A r g u m e n t s -----------
1467
  // -- 0: CEntry
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
  // --- Stack args ---
  // -- 1: receiver
  // -- [2, 2 + n[: the n actual arguments passed to the builtin
  // -- 2 + n: argc, including the receiver and implicit args (Smi)
  // -- 2 + n + 1: target
  // -- 2 + n + 2: new_target
  // --- Register args ---
  // -- 2 + n + 3: the C entry point
  // -- 2 + n + 4: argc (Int32)
  // -----------------------------------

  // The logic contained here is mirrored in Builtins::Generate_Adaptor.
  // Keep these in sync.

1482
  const bool is_construct = (node->opcode() == IrOpcode::kJSConstruct);
1483 1484 1485 1486 1487 1488

  Node* target = NodeProperties::GetValueInput(node, 0);
  Node* new_target = is_construct
                         ? NodeProperties::GetValueInput(node, arity + 1)
                         : jsgraph->UndefinedConstant();

1489 1490 1491 1492
  // CPP builtins are implemented in C++, and we can inline it.
  // CPP builtins create a builtin exit frame.
  DCHECK(Builtins::IsCpp(builtin_index));
  const bool has_builtin_exit_frame = true;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

  Node* stub = jsgraph->CEntryStubConstant(1, kDontSaveFPRegs, kArgvOnStack,
                                           has_builtin_exit_frame);
  node->ReplaceInput(0, stub);

  Zone* zone = jsgraph->zone();
  if (is_construct) {
    // Unify representations between construct and call nodes.
    // Remove new target and add receiver as a stack parameter.
    Node* receiver = jsgraph->UndefinedConstant();
    node->RemoveInput(arity + 1);
    node->InsertInput(zone, 1, receiver);
  }

  const int argc = arity + BuiltinArguments::kNumExtraArgsWithReceiver;
1508
  Node* argc_node = jsgraph->Constant(argc);
1509

1510 1511
  static const int kStubAndReceiver = 2;
  int cursor = arity + kStubAndReceiver;
1512
  node->InsertInput(zone, cursor++, jsgraph->PaddingConstant());
1513 1514 1515
  node->InsertInput(zone, cursor++, argc_node);
  node->InsertInput(zone, cursor++, target);
  node->InsertInput(zone, cursor++, new_target);
1516 1517

  Address entry = Builtins::CppEntryOf(builtin_index);
1518
  ExternalReference entry_ref = ExternalReference::Create(entry);
1519 1520
  Node* entry_node = jsgraph->ExternalConstant(entry_ref);

1521 1522
  node->InsertInput(zone, cursor++, entry_node);
  node->InsertInput(zone, cursor++, argc_node);
1523 1524 1525 1526

  static const int kReturnCount = 1;
  const char* debug_name = Builtins::name(builtin_index);
  Operator::Properties properties = node->op()->properties();
1527
  auto call_descriptor = Linkage::GetCEntryStubCallDescriptor(
1528 1529
      zone, kReturnCount, argc, debug_name, properties, flags);

1530
  NodeProperties::ChangeOp(node, jsgraph->common()->Call(call_descriptor));
1531 1532
}

1533
bool NeedsArgumentAdaptorFrame(SharedFunctionInfoRef shared, int arity) {
1534
  static const int sentinel = kDontAdaptArgumentsSentinel;
1535
  const int num_decl_parms = shared.internal_formal_parameter_count();
1536 1537 1538
  return (num_decl_parms != arity && num_decl_parms != sentinel);
}

1539 1540
}  // namespace

1541 1542 1543 1544 1545 1546 1547 1548
Reduction JSTypedLowering::ReduceJSConstructForwardVarargs(Node* node) {
  DCHECK_EQ(IrOpcode::kJSConstructForwardVarargs, node->opcode());
  ConstructForwardVarargsParameters p =
      ConstructForwardVarargsParametersOf(node->op());
  DCHECK_LE(2u, p.arity());
  int const arity = static_cast<int>(p.arity() - 2);
  int const start_index = static_cast<int>(p.start_index());
  Node* target = NodeProperties::GetValueInput(node, 0);
1549
  Type target_type = NodeProperties::GetType(target);
1550 1551 1552
  Node* new_target = NodeProperties::GetValueInput(node, arity + 1);

  // Check if {target} is a JSFunction.
1553
  if (target_type.IsHeapConstant() &&
1554
      target_type.AsHeapConstant()->Ref().IsJSFunction()) {
1555
    // Only optimize [[Construct]] here if {function} is a Constructor.
1556
    JSFunctionRef function = target_type.AsHeapConstant()->Ref().AsJSFunction();
1557
    if (!function.map().is_constructor()) return NoChange();
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    // Patch {node} to an indirect call via ConstructFunctionForwardVarargs.
    Callable callable = CodeFactory::ConstructFunctionForwardVarargs(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()->Constant(arity));
    node->InsertInput(graph()->zone(), 4, jsgraph()->Constant(start_index));
    node->InsertInput(graph()->zone(), 5, jsgraph()->UndefinedConstant());
    NodeProperties::ChangeOp(
        node, common()->Call(Linkage::GetStubCallDescriptor(
1569
                  graph()->zone(), callable.descriptor(), arity + 1,
1570 1571 1572 1573 1574 1575 1576
                  CallDescriptor::kNeedsFrameState)));
    return Changed(node);
  }

  return NoChange();
}

1577 1578 1579
Reduction JSTypedLowering::ReduceJSConstruct(Node* node) {
  DCHECK_EQ(IrOpcode::kJSConstruct, node->opcode());
  ConstructParameters const& p = ConstructParametersOf(node->op());
1580 1581 1582
  DCHECK_LE(2u, p.arity());
  int const arity = static_cast<int>(p.arity() - 2);
  Node* target = NodeProperties::GetValueInput(node, 0);
1583
  Type target_type = NodeProperties::GetType(target);
1584 1585 1586
  Node* new_target = NodeProperties::GetValueInput(node, arity + 1);

  // Check if {target} is a known JSFunction.
1587
  if (target_type.IsHeapConstant() &&
1588 1589
      target_type.AsHeapConstant()->Ref().IsJSFunction()) {
    JSFunctionRef function = target_type.AsHeapConstant()->Ref().AsJSFunction();
1590

1591
    // Only optimize [[Construct]] here if {function} is a Constructor.
1592
    if (!function.map().is_constructor()) return NoChange();
1593

1594 1595 1596 1597
    if (!function.serialized()) {
      TRACE_BROKER_MISSING(broker(), "data for function " << function);
      return NoChange();
    }
1598

1599
    // Patch {node} to an indirect call via the {function}s construct stub.
1600
    bool use_builtin_construct_stub = function.shared().construct_as_builtin();
1601
    CodeRef code(broker(),
1602
                 use_builtin_construct_stub
1603 1604
                     ? BUILTIN_CODE(isolate(), JSBuiltinsConstructStub)
                     : BUILTIN_CODE(isolate(), JSConstructStubGeneric));
1605
    node->RemoveInput(arity + 1);
1606
    node->InsertInput(graph()->zone(), 0, jsgraph()->Constant(code));
1607 1608 1609 1610 1611
    node->InsertInput(graph()->zone(), 2, new_target);
    node->InsertInput(graph()->zone(), 3, jsgraph()->Constant(arity));
    node->InsertInput(graph()->zone(), 4, jsgraph()->UndefinedConstant());
    node->InsertInput(graph()->zone(), 5, jsgraph()->UndefinedConstant());
    NodeProperties::ChangeOp(
1612 1613 1614
        node, common()->Call(Linkage::GetStubCallDescriptor(
                  graph()->zone(), ConstructStubDescriptor{}, 1 + arity,
                  CallDescriptor::kNeedsFrameState)));
1615 1616 1617 1618 1619 1620
    return Changed(node);
  }

  return NoChange();
}

1621 1622 1623
Reduction JSTypedLowering::ReduceJSCallForwardVarargs(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCallForwardVarargs, node->opcode());
  CallForwardVarargsParameters p = CallForwardVarargsParametersOf(node->op());
1624 1625 1626
  DCHECK_LE(2u, p.arity());
  int const arity = static_cast<int>(p.arity() - 2);
  int const start_index = static_cast<int>(p.start_index());
1627
  Node* target = NodeProperties::GetValueInput(node, 0);
1628
  Type target_type = NodeProperties::GetType(target);
1629 1630

  // Check if {target} is a JSFunction.
1631
  if (target_type.Is(Type::Function())) {
1632 1633 1634 1635 1636 1637
    // Compute flags for the call.
    CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;
    // Patch {node} to an indirect call via CallFunctionForwardVarargs.
    Callable callable = CodeFactory::CallFunctionForwardVarargs(isolate());
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
1638 1639
    node->InsertInput(graph()->zone(), 2, jsgraph()->Constant(arity));
    node->InsertInput(graph()->zone(), 3, jsgraph()->Constant(start_index));
1640
    NodeProperties::ChangeOp(
1641
        node, common()->Call(Linkage::GetStubCallDescriptor(
1642
                  graph()->zone(), callable.descriptor(), arity + 1, flags)));
1643 1644 1645 1646 1647
    return Changed(node);
  }

  return NoChange();
}
1648

1649 1650 1651
Reduction JSTypedLowering::ReduceJSCall(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCall, node->opcode());
  CallParameters const& p = CallParametersOf(node->op());
1652
  int arity = static_cast<int>(p.arity() - 2);
1653
  ConvertReceiverMode convert_mode = p.convert_mode();
1654
  Node* target = NodeProperties::GetValueInput(node, 0);
1655
  Type target_type = NodeProperties::GetType(target);
1656
  Node* receiver = NodeProperties::GetValueInput(node, 1);
1657
  Type receiver_type = NodeProperties::GetType(receiver);
1658 1659
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
1660

1661
  // Try to infer receiver {convert_mode} from {receiver} type.
1662
  if (receiver_type.Is(Type::NullOrUndefined())) {
1663
    convert_mode = ConvertReceiverMode::kNullOrUndefined;
1664
  } else if (!receiver_type.Maybe(Type::NullOrUndefined())) {
1665 1666 1667
    convert_mode = ConvertReceiverMode::kNotNullOrUndefined;
  }

1668 1669 1670 1671
  // Check if we know the SharedFunctionInfo of {target}.
  base::Optional<JSFunctionRef> function;
  base::Optional<SharedFunctionInfoRef> shared;

1672
  if (target_type.IsHeapConstant() &&
1673
      target_type.AsHeapConstant()->Ref().IsJSFunction()) {
1674
    function = target_type.AsHeapConstant()->Ref().AsJSFunction();
1675

1676 1677
    if (!function->serialized()) {
      TRACE_BROKER_MISSING(broker(), "data for function " << *function);
1678 1679
      return NoChange();
    }
1680 1681 1682 1683 1684 1685 1686 1687 1688
    shared = function->shared();
  } else if (target->opcode() == IrOpcode::kJSCreateClosure) {
    CreateClosureParameters const& ccp =
        CreateClosureParametersOf(target->op());
    shared = SharedFunctionInfoRef(broker(), ccp.shared_info());
  } else if (target->opcode() == IrOpcode::kCheckClosure) {
    FeedbackCellRef cell(broker(), FeedbackCellOf(target->op()));
    shared = cell.value().AsFeedbackVector().shared_function_info();
  }
1689

1690
  if (shared.has_value()) {
1691
    // Do not inline the call if we need to check whether to break at entry.
1692
    if (shared->HasBreakInfo()) return NoChange();
1693

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

1698 1699
    // Check if we need to convert the {receiver}, but bailout if it would
    // require data from a foreign native context.
1700
    if (is_sloppy(shared->language_mode()) && !shared->native() &&
1701
        !receiver_type.Is(Type::Receiver())) {
1702 1703
      if (!function.has_value() || !function->native_context().equals(
                                       broker()->target_native_context())) {
1704 1705 1706
        return NoChange();
      }
      Node* global_proxy =
1707
          jsgraph()->Constant(function->native_context().global_proxy_object());
1708
      receiver = effect =
1709 1710
          graph()->NewNode(simplified()->ConvertReceiver(convert_mode),
                           receiver, global_proxy, effect, control);
1711 1712 1713
      NodeProperties::ReplaceValueInput(node, receiver, 1);
    }

1714 1715 1716 1717 1718 1719
    // Load the context from the {target}.
    Node* context = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForJSFunctionContext()), target,
        effect, control);
    NodeProperties::ReplaceContextInput(node, context);

1720 1721 1722
    // Update the effect dependency for the {node}.
    NodeProperties::ReplaceEffectInput(node, effect);

1723 1724
    // Compute flags for the call.
    CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;
1725
    Node* new_target = jsgraph()->UndefinedConstant();
1726

1727
    if (NeedsArgumentAdaptorFrame(*shared, arity)) {
1728 1729 1730 1731 1732
      // Check if it's safe to skip the arguments adaptor for {shared},
      // that is whether the target function anyways cannot observe the
      // actual arguments. Details can be found in this document at
      // https://bit.ly/v8-faster-calls-with-arguments-mismatch and
      // on the tracking bug at https://crbug.com/v8/8895
1733
      if (shared->is_safe_to_skip_arguments_adaptor()) {
1734 1735 1736
        // Currently we only support skipping arguments adaptor frames
        // for strict mode functions, since there's Function.arguments
        // legacy accessor, which is still available in sloppy mode.
1737
        DCHECK_EQ(LanguageMode::kStrict, shared->language_mode());
1738 1739

        // Massage the arguments to match the expected number of arguments.
1740
        int expected_argument_count = shared->internal_formal_parameter_count();
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
        for (; arity > expected_argument_count; --arity) {
          node->RemoveInput(arity + 1);
        }
        for (; arity < expected_argument_count; ++arity) {
          node->InsertInput(graph()->zone(), arity + 2,
                            jsgraph()->UndefinedConstant());
        }

        // Patch {node} to a direct call.
        node->InsertInput(graph()->zone(), arity + 2, new_target);
1751 1752
        node->InsertInput(graph()->zone(), arity + 3,
                          jsgraph()->Constant(arity));
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
        NodeProperties::ChangeOp(node,
                                 common()->Call(Linkage::GetJSCallDescriptor(
                                     graph()->zone(), false, 1 + arity,
                                     flags | CallDescriptor::kCanUseRoots)));
      } else {
        // Patch {node} to an indirect call via the ArgumentsAdaptorTrampoline.
        Callable callable = CodeFactory::ArgumentAdaptor(isolate());
        node->InsertInput(graph()->zone(), 0,
                          jsgraph()->HeapConstant(callable.code()));
        node->InsertInput(graph()->zone(), 2, new_target);
1763
        node->InsertInput(graph()->zone(), 3, jsgraph()->Constant(arity));
1764 1765
        node->InsertInput(
            graph()->zone(), 4,
1766
            jsgraph()->Constant(shared->internal_formal_parameter_count()));
1767 1768 1769 1770 1771
        NodeProperties::ChangeOp(
            node,
            common()->Call(Linkage::GetStubCallDescriptor(
                graph()->zone(), callable.descriptor(), 1 + arity, flags)));
      }
1772 1773
    } else if (shared->HasBuiltinId() &&
               Builtins::IsCpp(shared->builtin_id())) {
1774
      // Patch {node} to a direct CEntry call.
1775 1776 1777
      ReduceBuiltin(jsgraph(), node, shared->builtin_id(), arity, flags);
    } else if (shared->HasBuiltinId()) {
      DCHECK(Builtins::HasJSLinkage(shared->builtin_id()));
1778 1779
      // Patch {node} to a direct code object call.
      Callable callable = Builtins::CallableFor(
1780
          isolate(), static_cast<Builtins::Name>(shared->builtin_id()));
1781 1782 1783 1784
      CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;

      const CallInterfaceDescriptor& descriptor = callable.descriptor();
      auto call_descriptor = Linkage::GetStubCallDescriptor(
1785
          graph()->zone(), descriptor, 1 + arity, flags);
1786 1787 1788
      Node* stub_code = jsgraph()->HeapConstant(callable.code());
      node->InsertInput(graph()->zone(), 0, stub_code);  // Code object.
      node->InsertInput(graph()->zone(), 2, new_target);
1789
      node->InsertInput(graph()->zone(), 3, jsgraph()->Constant(arity));
1790
      NodeProperties::ChangeOp(node, common()->Call(call_descriptor));
1791 1792 1793
    } else {
      // Patch {node} to a direct call.
      node->InsertInput(graph()->zone(), arity + 2, new_target);
1794
      node->InsertInput(graph()->zone(), arity + 3, jsgraph()->Constant(arity));
1795 1796
      NodeProperties::ChangeOp(node,
                               common()->Call(Linkage::GetJSCallDescriptor(
1797 1798
                                   graph()->zone(), false, 1 + arity,
                                   flags | CallDescriptor::kCanUseRoots)));
1799
    }
1800
    return Changed(node);
1801
  }
1802

1803
  // Check if {target} is a JSFunction.
1804
  if (target_type.Is(Type::Function())) {
1805 1806 1807
    // Compute flags for the call.
    CallDescriptor::Flags flags = CallDescriptor::kNeedsFrameState;
    // Patch {node} to an indirect call via the CallFunction builtin.
1808
    Callable callable = CodeFactory::CallFunction(isolate(), convert_mode);
1809 1810
    node->InsertInput(graph()->zone(), 0,
                      jsgraph()->HeapConstant(callable.code()));
1811
    node->InsertInput(graph()->zone(), 2, jsgraph()->Constant(arity));
1812 1813
    NodeProperties::ChangeOp(
        node, common()->Call(Linkage::GetStubCallDescriptor(
1814
                  graph()->zone(), callable.descriptor(), 1 + arity, flags)));
1815 1816 1817
    return Changed(node);
  }

1818 1819 1820
  // Maybe we did at least learn something about the {receiver}.
  if (p.convert_mode() != convert_mode) {
    NodeProperties::ChangeOp(
1821 1822 1823
        node,
        javascript()->Call(p.arity(), p.frequency(), p.feedback(), convert_mode,
                           p.speculation_mode(), p.feedback_relation()));
1824 1825 1826
    return Changed(node);
  }

1827 1828 1829
  return NoChange();
}

1830 1831
Reduction JSTypedLowering::ReduceJSForInNext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSForInNext, node->opcode());
1832
  ForInMode const mode = ForInModeOf(node->op());
1833 1834 1835 1836 1837
  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);
1838
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
1839 1840 1841 1842 1843 1844 1845 1846
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

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

1847 1848 1849 1850 1851 1852 1853
  switch (mode) {
    case ForInMode::kUseEnumCacheKeys:
    case ForInMode::kUseEnumCacheKeysAndIndices: {
      // Ensure that the expected map still matches that of the {receiver}.
      Node* check = graph()->NewNode(simplified()->ReferenceEqual(),
                                     receiver_map, cache_type);
      effect =
1854
          graph()->NewNode(simplified()->CheckIf(DeoptimizeReason::kWrongMap),
1855
                           check, effect, control);
1856

1857 1858 1859
      // Since the change to LoadElement() below is effectful, we connect
      // node to all effect uses.
      ReplaceWithValue(node, node, node, control);
1860 1861 1862 1863 1864 1865 1866 1867 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

      // Morph the {node} into a LoadElement.
      node->ReplaceInput(0, cache_array);
      node->ReplaceInput(1, index);
      node->ReplaceInput(2, effect);
      node->ReplaceInput(3, control);
      node->TrimInputCount(4);
      NodeProperties::ChangeOp(
          node,
          simplified()->LoadElement(AccessBuilder::ForFixedArrayElement()));
      NodeProperties::SetType(node, Type::InternalizedString());
      break;
    }
    case ForInMode::kGeneric: {
      // Load the next {key} from the {cache_array}.
      Node* key = effect = graph()->NewNode(
          simplified()->LoadElement(AccessBuilder::ForFixedArrayElement()),
          cache_array, index, effect, control);

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

      Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
      Node* etrue;
      Node* vtrue;
      {
        // Don't need filtering since expected map still matches that of the
        // {receiver}.
        etrue = effect;
        vtrue = key;
      }
1894

1895 1896 1897 1898 1899 1900 1901 1902
      Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
      Node* efalse;
      Node* vfalse;
      {
        // Filter the {key} to check if it's still a valid property of the
        // {receiver} (does the ToName conversion implicitly).
        Callable const callable =
            Builtins::CallableFor(isolate(), Builtins::kForInFilter);
1903
        auto call_descriptor = Linkage::GetStubCallDescriptor(
1904 1905
            graph()->zone(), callable.descriptor(),
            callable.descriptor().GetStackParameterCount(),
1906
            CallDescriptor::kNeedsFrameState);
1907 1908 1909 1910
        vfalse = efalse = if_false =
            graph()->NewNode(common()->Call(call_descriptor),
                             jsgraph()->HeapConstant(callable.code()), key,
                             receiver, context, frame_state, effect, if_false);
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921

        // Update potential {IfException} uses of {node} to point to the above
        // ForInFilter stub call node instead.
        Node* if_exception = nullptr;
        if (NodeProperties::IsExceptionalCall(node, &if_exception)) {
          if_false = graph()->NewNode(common()->IfSuccess(), vfalse);
          NodeProperties::ReplaceControlInput(if_exception, vfalse);
          NodeProperties::ReplaceEffectInput(if_exception, efalse);
          Revisit(if_exception);
        }
      }
1922

1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
      control = graph()->NewNode(common()->Merge(2), if_true, if_false);
      effect = graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
      ReplaceWithValue(node, node, effect, control);

      // Morph the {node} into a Phi.
      node->ReplaceInput(0, vtrue);
      node->ReplaceInput(1, vfalse);
      node->ReplaceInput(2, control);
      node->TrimInputCount(3);
      NodeProperties::ChangeOp(
          node, common()->Phi(MachineRepresentation::kTagged, 2));
1934
    }
1935 1936 1937 1938 1939
  }

  return Changed(node);
}

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
Reduction JSTypedLowering::ReduceJSForInPrepare(Node* node) {
  DCHECK_EQ(IrOpcode::kJSForInPrepare, node->opcode());
  ForInMode const mode = ForInModeOf(node->op());
  Node* enumerator = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* cache_type = enumerator;
  Node* cache_array = nullptr;
  Node* cache_length = nullptr;

  switch (mode) {
    case ForInMode::kUseEnumCacheKeys:
    case ForInMode::kUseEnumCacheKeysAndIndices: {
      // Check that the {enumerator} is a Map.
      effect = graph()->NewNode(
          simplified()->CheckMaps(CheckMapsFlag::kNone,
                                  ZoneHandleSet<Map>(factory()->meta_map())),
          enumerator, effect, control);

      // Load the enum cache from the {enumerator} map.
      Node* descriptor_array = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForMapDescriptors()),
          enumerator, effect, control);
      Node* enum_cache = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForDescriptorArrayEnumCache()),
          descriptor_array, effect, control);
      cache_array = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForEnumCacheKeys()),
          enum_cache, effect, control);

      // Load the enum length of the {enumerator} map.
      Node* bit_field3 = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForMapBitField3()), enumerator,
          effect, control);
1974 1975 1976 1977
      STATIC_ASSERT(Map::Bits3::EnumLengthBits::kShift == 0);
      cache_length = graph()->NewNode(
          simplified()->NumberBitwiseAnd(), bit_field3,
          jsgraph()->Constant(Map::Bits3::EnumLengthBits::kMask));
1978 1979 1980 1981
      break;
    }
    case ForInMode::kGeneric: {
      // Check if the {enumerator} is a Map or a FixedArray.
1982
      Node* check = effect = graph()->NewNode(
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
          simplified()->CompareMaps(ZoneHandleSet<Map>(factory()->meta_map())),
          enumerator, effect, control);
      Node* branch =
          graph()->NewNode(common()->Branch(BranchHint::kTrue), check, control);

      Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
      Node* etrue = effect;
      Node* cache_array_true;
      Node* cache_length_true;
      {
        // Load the enum cache from the {enumerator} map.
        Node* descriptor_array = etrue = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForMapDescriptors()),
            enumerator, etrue, if_true);
        Node* enum_cache = etrue =
            graph()->NewNode(simplified()->LoadField(
                                 AccessBuilder::ForDescriptorArrayEnumCache()),
                             descriptor_array, etrue, if_true);
        cache_array_true = etrue = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForEnumCacheKeys()),
            enum_cache, etrue, if_true);

        // Load the enum length of the {enumerator} map.
        Node* bit_field3 = etrue = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForMapBitField3()),
            enumerator, etrue, if_true);
2009 2010 2011 2012
        STATIC_ASSERT(Map::Bits3::EnumLengthBits::kShift == 0);
        cache_length_true = graph()->NewNode(
            simplified()->NumberBitwiseAnd(), bit_field3,
            jsgraph()->Constant(Map::Bits3::EnumLengthBits::kMask));
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
      }

      Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
      Node* efalse = effect;
      Node* cache_array_false;
      Node* cache_length_false;
      {
        // The {enumerator} is the FixedArray with the keys to iterate.
        cache_array_false = enumerator;
        cache_length_false = efalse = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForFixedArrayLength()),
            cache_array_false, efalse, if_false);
      }

      // Rewrite the uses of the {node}.
      control = graph()->NewNode(common()->Merge(2), if_true, if_false);
      effect = graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
      cache_array =
          graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                           cache_array_true, cache_array_false, control);
      cache_length =
          graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                           cache_length_true, cache_length_false, control);
      break;
    }
  }

  // Update the uses of {node}.
  for (Edge edge : node->use_edges()) {
    Node* const user = edge.from();
    if (NodeProperties::IsEffectEdge(edge)) {
      edge.UpdateTo(effect);
      Revisit(user);
    } else if (NodeProperties::IsControlEdge(edge)) {
      edge.UpdateTo(control);
      Revisit(user);
    } else {
      DCHECK(NodeProperties::IsValueEdge(edge));
      switch (ProjectionIndexOf(user->op())) {
        case 0:
          Replace(user, cache_type);
          break;
        case 1:
          Replace(user, cache_array);
          break;
        case 2:
          Replace(user, cache_length);
          break;
        default:
          UNREACHABLE();
      }
    }
  }
  node->Kill();
  return Replace(effect);
}

2070 2071 2072 2073 2074
Reduction JSTypedLowering::ReduceJSLoadMessage(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadMessage, node->opcode());
  ExternalReference const ref =
      ExternalReference::address_of_pending_message_obj(isolate());
  node->ReplaceInput(0, jsgraph()->ExternalConstant(ref));
2075
  NodeProperties::ChangeOp(node, simplified()->LoadMessage());
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
  return Changed(node);
}

Reduction JSTypedLowering::ReduceJSStoreMessage(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreMessage, node->opcode());
  ExternalReference const ref =
      ExternalReference::address_of_pending_message_obj(isolate());
  Node* value = NodeProperties::GetValueInput(node, 0);
  node->ReplaceInput(0, jsgraph()->ExternalConstant(ref));
  node->ReplaceInput(1, value);
2086
  NodeProperties::ChangeOp(node, simplified()->StoreMessage());
2087 2088 2089
  return Changed(node);
}

2090 2091 2092
Reduction JSTypedLowering::ReduceJSGeneratorStore(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGeneratorStore, node->opcode());
  Node* generator = NodeProperties::GetValueInput(node, 0);
2093
  Node* continuation = NodeProperties::GetValueInput(node, 1);
2094
  Node* offset = NodeProperties::GetValueInput(node, 2);
2095 2096 2097
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
2098
  int value_count = GeneratorStoreValueCountOf(node->op());
2099

2100 2101
  FieldAccess array_field =
      AccessBuilder::ForJSGeneratorObjectParametersAndRegisters();
2102 2103 2104
  FieldAccess context_field = AccessBuilder::ForJSGeneratorObjectContext();
  FieldAccess continuation_field =
      AccessBuilder::ForJSGeneratorObjectContinuation();
2105
  FieldAccess input_or_debug_pos_field =
2106
      AccessBuilder::ForJSGeneratorObjectInputOrDebugPos();
2107

2108 2109
  Node* array = effect = graph()->NewNode(simplified()->LoadField(array_field),
                                          generator, effect, control);
2110

2111
  for (int i = 0; i < value_count; ++i) {
2112
    Node* value = NodeProperties::GetValueInput(node, 3 + i);
2113 2114 2115 2116 2117
    if (value != jsgraph()->OptimizedOutConstant()) {
      effect = graph()->NewNode(
          simplified()->StoreField(AccessBuilder::ForFixedArraySlot(i)), array,
          value, effect, control);
    }
2118 2119 2120 2121
  }

  effect = graph()->NewNode(simplified()->StoreField(context_field), generator,
                            context, effect, control);
2122 2123
  effect = graph()->NewNode(simplified()->StoreField(continuation_field),
                            generator, continuation, effect, control);
2124 2125
  effect = graph()->NewNode(simplified()->StoreField(input_or_debug_pos_field),
                            generator, offset, effect, control);
2126

2127 2128
  ReplaceWithValue(node, effect, effect, control);
  return Changed(effect);
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
}

Reduction JSTypedLowering::ReduceJSGeneratorRestoreContinuation(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGeneratorRestoreContinuation, node->opcode());
  Node* generator = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  FieldAccess continuation_field =
      AccessBuilder::ForJSGeneratorObjectContinuation();

2140
  Node* continuation = effect = graph()->NewNode(
2141
      simplified()->LoadField(continuation_field), generator, effect, control);
2142 2143 2144
  Node* executing = jsgraph()->Constant(JSGeneratorObject::kGeneratorExecuting);
  effect = graph()->NewNode(simplified()->StoreField(continuation_field),
                            generator, executing, effect, control);
2145

2146 2147
  ReplaceWithValue(node, continuation, effect, control);
  return Changed(continuation);
2148 2149
}

2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
Reduction JSTypedLowering::ReduceJSGeneratorRestoreContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGeneratorRestoreContext, node->opcode());

  const Operator* new_op =
      simplified()->LoadField(AccessBuilder::ForJSGeneratorObjectContext());

  // Mutate the node in-place.
  DCHECK(OperatorProperties::HasContextInput(node->op()));
  DCHECK(!OperatorProperties::HasContextInput(new_op));
  node->RemoveInput(NodeProperties::FirstContextIndex(node));

  NodeProperties::ChangeOp(node, new_op);
  return Changed(node);
}

2165 2166 2167 2168 2169
Reduction JSTypedLowering::ReduceJSGeneratorRestoreRegister(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGeneratorRestoreRegister, node->opcode());
  Node* generator = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
2170
  int index = RestoreRegisterIndexOf(node->op());
2171

2172 2173
  FieldAccess array_field =
      AccessBuilder::ForJSGeneratorObjectParametersAndRegisters();
2174 2175
  FieldAccess element_field = AccessBuilder::ForFixedArraySlot(index);

2176 2177 2178 2179 2180 2181 2182
  Node* array = effect = graph()->NewNode(simplified()->LoadField(array_field),
                                          generator, effect, control);
  Node* element = effect = graph()->NewNode(
      simplified()->LoadField(element_field), array, effect, control);
  Node* stale = jsgraph()->StaleRegisterConstant();
  effect = graph()->NewNode(simplified()->StoreField(element_field), array,
                            stale, effect, control);
2183

2184 2185
  ReplaceWithValue(node, element, effect, control);
  return Changed(element);
2186
}
2187

2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
Reduction JSTypedLowering::ReduceJSGeneratorRestoreInputOrDebugPos(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGeneratorRestoreInputOrDebugPos, node->opcode());

  FieldAccess input_or_debug_pos_field =
      AccessBuilder::ForJSGeneratorObjectInputOrDebugPos();
  const Operator* new_op = simplified()->LoadField(input_or_debug_pos_field);

  // Mutate the node in-place.
  DCHECK(OperatorProperties::HasContextInput(node->op()));
  DCHECK(!OperatorProperties::HasContextInput(new_op));
  node->RemoveInput(NodeProperties::FirstContextIndex(node));

  NodeProperties::ChangeOp(node, new_op);
  return Changed(node);
}

2204 2205
Reduction JSTypedLowering::ReduceObjectIsArray(Node* node) {
  Node* value = NodeProperties::GetValueInput(node, 0);
2206
  Type value_type = NodeProperties::GetType(value);
2207 2208 2209 2210 2211 2212
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Constant-fold based on {value} type.
2213
  if (value_type.Is(Type::Array())) {
2214 2215 2216
    Node* value = jsgraph()->TrueConstant();
    ReplaceWithValue(node, value);
    return Replace(value);
2217
  } else if (!value_type.Maybe(Type::ArrayOrProxy())) {
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
    Node* value = jsgraph()->FalseConstant();
    ReplaceWithValue(node, value);
    return Replace(value);
  }

  int count = 0;
  Node* values[5];
  Node* effects[5];
  Node* controls[4];

  // Check if the {value} is a Smi.
  Node* check = graph()->NewNode(simplified()->ObjectIsSmi(), value);
  control =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), check, control);

  // The {value} is a Smi.
  controls[count] = graph()->NewNode(common()->IfTrue(), control);
  effects[count] = effect;
  values[count] = jsgraph()->FalseConstant();
  count++;

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

  // Load the {value}s instance type.
  Node* value_map = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMap()), value, effect, control);
  Node* value_instance_type = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapInstanceType()), value_map,
      effect, control);

  // Check if the {value} is a JSArray.
  check = graph()->NewNode(simplified()->NumberEqual(), value_instance_type,
                           jsgraph()->Constant(JS_ARRAY_TYPE));
  control = graph()->NewNode(common()->Branch(), check, control);

  // The {value} is a JSArray.
  controls[count] = graph()->NewNode(common()->IfTrue(), control);
  effects[count] = effect;
  values[count] = jsgraph()->TrueConstant();
  count++;

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

  // Check if the {value} is a JSProxy.
  check = graph()->NewNode(simplified()->NumberEqual(), value_instance_type,
                           jsgraph()->Constant(JS_PROXY_TYPE));
  control =
      graph()->NewNode(common()->Branch(BranchHint::kFalse), check, control);

  // The {value} is neither a JSArray nor a JSProxy.
  controls[count] = graph()->NewNode(common()->IfFalse(), control);
  effects[count] = effect;
  values[count] = jsgraph()->FalseConstant();
  count++;

  control = graph()->NewNode(common()->IfTrue(), control);

  // Let the %ArrayIsArray runtime function deal with the JSProxy {value}.
  value = effect = control =
      graph()->NewNode(javascript()->CallRuntime(Runtime::kArrayIsArray), value,
                       context, frame_state, effect, control);
  NodeProperties::SetType(value, Type::Boolean());

  // Update potential {IfException} uses of {node} to point to the above
  // %ArrayIsArray runtime call node instead.
  Node* on_exception = nullptr;
  if (NodeProperties::IsExceptionalCall(node, &on_exception)) {
    NodeProperties::ReplaceControlInput(on_exception, control);
    NodeProperties::ReplaceEffectInput(on_exception, effect);
    control = graph()->NewNode(common()->IfSuccess(), control);
    Revisit(on_exception);
  }

  // The {value} is neither a JSArray nor a JSProxy.
  controls[count] = control;
  effects[count] = effect;
  values[count] = value;
  count++;

  control = graph()->NewNode(common()->Merge(count), count, controls);
  effects[count] = control;
  values[count] = control;
  effect = graph()->NewNode(common()->EffectPhi(count), count + 1, effects);
  value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, count),
                           count + 1, values);
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
}

2307 2308
Reduction JSTypedLowering::ReduceJSParseInt(Node* node) {
  Node* value = NodeProperties::GetValueInput(node, 0);
2309
  Type value_type = NodeProperties::GetType(value);
2310
  Node* radix = NodeProperties::GetValueInput(node, 1);
2311
  Type radix_type = NodeProperties::GetType(radix);
2312 2313
  // We need kTenOrUndefined and kZeroOrUndefined because
  // the type representing {0,10} would become the range 1-10.
2314 2315 2316
  if (value_type.Is(type_cache_->kSafeInteger) &&
      (radix_type.Is(type_cache_->kTenOrUndefined) ||
       radix_type.Is(type_cache_->kZeroOrUndefined))) {
2317 2318 2319 2320 2321 2322 2323 2324 2325
    // Number.parseInt(a:safe-integer) -> a
    // Number.parseInt(a:safe-integer,b:#0\/undefined) -> a
    // Number.parseInt(a:safe-integer,b:#10\/undefined) -> a
    ReplaceWithValue(node, value);
    return Replace(value);
  }
  return NoChange();
}

2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
Reduction JSTypedLowering::ReduceJSResolvePromise(Node* node) {
  DCHECK_EQ(IrOpcode::kJSResolvePromise, node->opcode());
  Node* resolution = NodeProperties::GetValueInput(node, 1);
  Type resolution_type = NodeProperties::GetType(resolution);
  // We can strength-reduce JSResolvePromise to JSFulfillPromise
  // if the {resolution} is known to be a primitive, as in that
  // case we don't perform the implicit chaining (via "then").
  if (resolution_type.Is(Type::Primitive())) {
    // JSResolvePromise(p,v:primitive) -> JSFulfillPromise(p,v)
    node->RemoveInput(3);  // frame state
    NodeProperties::ChangeOp(node, javascript()->FulfillPromise());
    return Changed(node);
  }
  return NoChange();
}

2342
Reduction JSTypedLowering::Reduce(Node* node) {
2343 2344
  DisallowHeapAccess no_heap_access;

2345 2346
  switch (node->opcode()) {
    case IrOpcode::kJSEqual:
2347
      return ReduceJSEqual(node);
2348
    case IrOpcode::kJSStrictEqual:
2349
      return ReduceJSStrictEqual(node);
2350 2351 2352 2353 2354 2355 2356 2357
    case IrOpcode::kJSLessThan:         // fall through
    case IrOpcode::kJSGreaterThan:      // fall through
    case IrOpcode::kJSLessThanOrEqual:  // fall through
    case IrOpcode::kJSGreaterThanOrEqual:
      return ReduceJSComparison(node);
    case IrOpcode::kJSBitwiseOr:
    case IrOpcode::kJSBitwiseXor:
    case IrOpcode::kJSBitwiseAnd:
2358
      return ReduceInt32Binop(node);
2359 2360
    case IrOpcode::kJSShiftLeft:
    case IrOpcode::kJSShiftRight:
2361
      return ReduceUI32Shift(node, kSigned);
2362
    case IrOpcode::kJSShiftRightLogical:
2363
      return ReduceUI32Shift(node, kUnsigned);
2364 2365 2366 2367 2368 2369
    case IrOpcode::kJSAdd:
      return ReduceJSAdd(node);
    case IrOpcode::kJSSubtract:
    case IrOpcode::kJSMultiply:
    case IrOpcode::kJSDivide:
    case IrOpcode::kJSModulus:
2370
    case IrOpcode::kJSExponentiate:
2371
      return ReduceNumberBinop(node);
2372 2373
    case IrOpcode::kJSBitwiseNot:
      return ReduceJSBitwiseNot(node);
2374 2375 2376 2377
    case IrOpcode::kJSDecrement:
      return ReduceJSDecrement(node);
    case IrOpcode::kJSIncrement:
      return ReduceJSIncrement(node);
2378 2379
    case IrOpcode::kJSNegate:
      return ReduceJSNegate(node);
2380 2381
    case IrOpcode::kJSHasInPrototypeChain:
      return ReduceJSHasInPrototypeChain(node);
2382 2383
    case IrOpcode::kJSOrdinaryHasInstance:
      return ReduceJSOrdinaryHasInstance(node);
2384 2385
    case IrOpcode::kJSToLength:
      return ReduceJSToLength(node);
2386 2387
    case IrOpcode::kJSToName:
      return ReduceJSToName(node);
2388
    case IrOpcode::kJSToNumber:
2389
    case IrOpcode::kJSToNumberConvertBigInt:
2390
      return ReduceJSToNumber(node);
2391
    case IrOpcode::kJSToNumeric:
2392
      return ReduceJSToNumeric(node);
2393
    case IrOpcode::kJSToString:
2394
      return ReduceJSToString(node);
2395 2396
    case IrOpcode::kJSToObject:
      return ReduceJSToObject(node);
2397 2398
    case IrOpcode::kJSLoadNamed:
      return ReduceJSLoadNamed(node);
2399 2400 2401 2402
    case IrOpcode::kJSLoadContext:
      return ReduceJSLoadContext(node);
    case IrOpcode::kJSStoreContext:
      return ReduceJSStoreContext(node);
2403 2404 2405 2406
    case IrOpcode::kJSLoadModule:
      return ReduceJSLoadModule(node);
    case IrOpcode::kJSStoreModule:
      return ReduceJSStoreModule(node);
2407 2408
    case IrOpcode::kJSConstructForwardVarargs:
      return ReduceJSConstructForwardVarargs(node);
2409 2410
    case IrOpcode::kJSConstruct:
      return ReduceJSConstruct(node);
2411 2412
    case IrOpcode::kJSCallForwardVarargs:
      return ReduceJSCallForwardVarargs(node);
2413 2414
    case IrOpcode::kJSCall:
      return ReduceJSCall(node);
2415 2416
    case IrOpcode::kJSForInPrepare:
      return ReduceJSForInPrepare(node);
2417 2418
    case IrOpcode::kJSForInNext:
      return ReduceJSForInNext(node);
2419 2420
    case IrOpcode::kJSHasContextExtension:
      return ReduceJSHasContextExtension(node);
2421 2422 2423 2424
    case IrOpcode::kJSLoadMessage:
      return ReduceJSLoadMessage(node);
    case IrOpcode::kJSStoreMessage:
      return ReduceJSStoreMessage(node);
2425 2426 2427 2428
    case IrOpcode::kJSGeneratorStore:
      return ReduceJSGeneratorStore(node);
    case IrOpcode::kJSGeneratorRestoreContinuation:
      return ReduceJSGeneratorRestoreContinuation(node);
2429 2430
    case IrOpcode::kJSGeneratorRestoreContext:
      return ReduceJSGeneratorRestoreContext(node);
2431 2432
    case IrOpcode::kJSGeneratorRestoreRegister:
      return ReduceJSGeneratorRestoreRegister(node);
2433 2434
    case IrOpcode::kJSGeneratorRestoreInputOrDebugPos:
      return ReduceJSGeneratorRestoreInputOrDebugPos(node);
2435 2436
    case IrOpcode::kJSObjectIsArray:
      return ReduceObjectIsArray(node);
2437 2438
    case IrOpcode::kJSParseInt:
      return ReduceJSParseInt(node);
2439 2440
    case IrOpcode::kJSResolvePromise:
      return ReduceJSResolvePromise(node);
2441 2442 2443 2444 2445
    default:
      break;
  }
  return NoChange();
}
2446

2447 2448 2449 2450 2451 2452 2453

Factory* JSTypedLowering::factory() const { return jsgraph()->factory(); }


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


2454 2455 2456
Isolate* JSTypedLowering::isolate() const { return jsgraph()->isolate(); }


2457 2458 2459 2460 2461 2462 2463 2464 2465
JSOperatorBuilder* JSTypedLowering::javascript() const {
  return jsgraph()->javascript();
}


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

2466 2467 2468 2469
SimplifiedOperatorBuilder* JSTypedLowering::simplified() const {
  return jsgraph()->simplified();
}

2470 2471 2472
}  // namespace compiler
}  // namespace internal
}  // namespace v8