js-create-lowering.cc 81.3 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/js-create-lowering.h"

7
#include "src/codegen/code-factory.h"
8
#include "src/compiler/access-builder.h"
9
#include "src/compiler/allocation-builder-inl.h"
10
#include "src/compiler/common-operator.h"
11
#include "src/compiler/compilation-dependencies.h"
12 13 14
#include "src/compiler/js-graph.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/linkage.h"
15
#include "src/compiler/node-matchers.h"
16
#include "src/compiler/node-properties.h"
17
#include "src/compiler/node.h"
18
#include "src/compiler/operator-properties.h"
19 20
#include "src/compiler/simplified-operator.h"
#include "src/compiler/state-values-utils.h"
21
#include "src/execution/protectors.h"
22
#include "src/objects/arguments.h"
23
#include "src/objects/hash-table-inl.h"
24
#include "src/objects/heap-number.h"
25
#include "src/objects/js-collection-iterator.h"
26
#include "src/objects/js-generator.h"
27 28
#include "src/objects/js-promise.h"
#include "src/objects/js-regexp-inl.h"
29
#include "src/objects/objects-inl.h"
30
#include "src/objects/template-objects.h"
31 32 33 34 35 36 37 38

namespace v8 {
namespace internal {
namespace compiler {

namespace {

// Retrieves the frame state holding actual argument values.
39 40 41 42
FrameState GetArgumentsFrameState(FrameState frame_state) {
  FrameState outer_state{NodeProperties::GetFrameStateInput(frame_state)};
  return outer_state.frame_state_info().type() ==
                 FrameStateType::kArgumentsAdaptor
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
             ? outer_state
             : frame_state;
}

// When initializing arrays, we'll unfold the loop if the number of
// elements is known to be of this type.
const int kElementLoopUnrollLimit = 16;

// Limits up to which context allocations are inlined.
const int kFunctionContextAllocationLimit = 16;
const int kBlockContextAllocationLimit = 16;

}  // namespace

Reduction JSCreateLowering::Reduce(Node* node) {
  switch (node->opcode()) {
    case IrOpcode::kJSCreate:
      return ReduceJSCreate(node);
    case IrOpcode::kJSCreateArguments:
      return ReduceJSCreateArguments(node);
    case IrOpcode::kJSCreateArray:
      return ReduceJSCreateArray(node);
65 66
    case IrOpcode::kJSCreateArrayIterator:
      return ReduceJSCreateArrayIterator(node);
67 68
    case IrOpcode::kJSCreateAsyncFunctionObject:
      return ReduceJSCreateAsyncFunctionObject(node);
69 70
    case IrOpcode::kJSCreateBoundFunction:
      return ReduceJSCreateBoundFunction(node);
71 72
    case IrOpcode::kJSCreateClosure:
      return ReduceJSCreateClosure(node);
73 74
    case IrOpcode::kJSCreateCollectionIterator:
      return ReduceJSCreateCollectionIterator(node);
75 76
    case IrOpcode::kJSCreateIterResultObject:
      return ReduceJSCreateIterResultObject(node);
77 78
    case IrOpcode::kJSCreateStringIterator:
      return ReduceJSCreateStringIterator(node);
79 80
    case IrOpcode::kJSCreateKeyValueArray:
      return ReduceJSCreateKeyValueArray(node);
81 82
    case IrOpcode::kJSCreatePromise:
      return ReduceJSCreatePromise(node);
83 84
    case IrOpcode::kJSCreateLiteralArray:
    case IrOpcode::kJSCreateLiteralObject:
85 86 87
      return ReduceJSCreateLiteralArrayOrObject(node);
    case IrOpcode::kJSCreateLiteralRegExp:
      return ReduceJSCreateLiteralRegExp(node);
88 89
    case IrOpcode::kJSGetTemplateObject:
      return ReduceJSGetTemplateObject(node);
90 91
    case IrOpcode::kJSCreateEmptyLiteralArray:
      return ReduceJSCreateEmptyLiteralArray(node);
92 93
    case IrOpcode::kJSCreateEmptyLiteralObject:
      return ReduceJSCreateEmptyLiteralObject(node);
94 95 96 97 98 99 100 101
    case IrOpcode::kJSCreateFunctionContext:
      return ReduceJSCreateFunctionContext(node);
    case IrOpcode::kJSCreateWithContext:
      return ReduceJSCreateWithContext(node);
    case IrOpcode::kJSCreateCatchContext:
      return ReduceJSCreateCatchContext(node);
    case IrOpcode::kJSCreateBlockContext:
      return ReduceJSCreateBlockContext(node);
102 103
    case IrOpcode::kJSCreateGeneratorObject:
      return ReduceJSCreateGeneratorObject(node);
104 105
    case IrOpcode::kJSCreateObject:
      return ReduceJSCreateObject(node);
106 107 108 109 110 111 112 113 114 115
    default:
      break;
  }
  return NoChange();
}

Reduction JSCreateLowering::ReduceJSCreate(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreate, node->opcode());
  Node* const new_target = NodeProperties::GetValueInput(node, 1);
  Node* const effect = NodeProperties::GetEffectInput(node);
116
  Node* const control = NodeProperties::GetControlInput(node);
117

118 119 120
  base::Optional<MapRef> initial_map =
      NodeProperties::GetJSCreateMap(broker(), node);
  if (!initial_map.has_value()) return NoChange();
121

122 123
  JSFunctionRef original_constructor =
      HeapObjectMatcher(new_target).Ref(broker()).AsJSFunction();
124 125 126
  SlackTrackingPrediction slack_tracking_prediction =
      dependencies()->DependOnInitialMapInstanceSizePrediction(
          original_constructor);
127 128 129

  // Emit code to allocate the JSObject instance for the
  // {original_constructor}.
130
  AllocationBuilder a(jsgraph(), effect, control);
131
  a.Allocate(slack_tracking_prediction.instance_size());
132
  a.Store(AccessBuilder::ForMap(), *initial_map);
133
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
134 135 136
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
137 138
  for (int i = 0; i < slack_tracking_prediction.inobject_property_count();
       ++i) {
139
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(*initial_map, i),
140
            jsgraph()->UndefinedConstant());
141
  }
142 143 144 145

  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
146 147 148 149 150
}

Reduction JSCreateLowering::ReduceJSCreateArguments(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateArguments, node->opcode());
  CreateArgumentsType type = CreateArgumentsTypeOf(node->op());
151
  FrameState frame_state{NodeProperties::GetFrameStateInput(node)};
152
  Node* const control = graph()->start();
153
  FrameStateInfo state_info = frame_state.frame_state_info();
154
  SharedFunctionInfoRef shared(broker(),
155
                               state_info.shared_info().ToHandleChecked());
156 157 158

  // Use the ArgumentsAccessStub for materializing both mapped and unmapped
  // arguments object, but only for non-inlined (i.e. outermost) frames.
159
  if (!frame_state.has_outer_frame_state()) {
160 161
    switch (type) {
      case CreateArgumentsType::kMappedArguments: {
162
        // TODO(turbofan): Duplicate parameters are not handled yet.
163
        if (shared.has_duplicate_parameters()) return NoChange();
164 165 166
        Node* const callee = NodeProperties::GetValueInput(node, 0);
        Node* const context = NodeProperties::GetContextInput(node);
        Node* effect = NodeProperties::GetEffectInput(node);
167
        Node* const arguments_length =
168
            graph()->NewNode(simplified()->ArgumentsLength());
169 170
        // Allocate the elements backing store.
        bool has_aliased_arguments = false;
171 172 173
        Node* const elements = effect =
            AllocateAliasedArguments(effect, control, context, arguments_length,
                                     shared, &has_aliased_arguments);
174
        // Load the arguments object map.
175 176
        Node* const arguments_map = jsgraph()->Constant(
            has_aliased_arguments
177 178
                ? native_context().fast_aliased_arguments_map()
                : native_context().sloppy_arguments_map());
179
        // Actually allocate and initialize the arguments object.
180
        AllocationBuilder a(jsgraph(), effect, control);
181
        STATIC_ASSERT(JSSloppyArgumentsObject::kSize == 5 * kTaggedSize);
182 183
        a.Allocate(JSSloppyArgumentsObject::kSize);
        a.Store(AccessBuilder::ForMap(), arguments_map);
184 185
        a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
                jsgraph()->EmptyFixedArrayConstant());
186 187 188 189 190
        a.Store(AccessBuilder::ForJSObjectElements(), elements);
        a.Store(AccessBuilder::ForArgumentsLength(), arguments_length);
        a.Store(AccessBuilder::ForArgumentsCallee(), callee);
        RelaxControls(node);
        a.FinishAndChange(node);
191 192
        return Changed(node);
      }
193 194
      case CreateArgumentsType::kUnmappedArguments: {
        Node* effect = NodeProperties::GetEffectInput(node);
195
        Node* const arguments_length =
196
            graph()->NewNode(simplified()->ArgumentsLength());
197 198
        // Allocate the elements backing store.
        Node* const elements = effect =
199 200 201
            graph()->NewNode(simplified()->NewArgumentsElements(
                                 CreateArgumentsType::kUnmappedArguments,
                                 shared.internal_formal_parameter_count()),
202
                             arguments_length, effect);
203
        // Load the arguments object map.
204
        Node* const arguments_map =
205
            jsgraph()->Constant(native_context().strict_arguments_map());
206
        // Actually allocate and initialize the arguments object.
207
        AllocationBuilder a(jsgraph(), effect, control);
208
        STATIC_ASSERT(JSStrictArgumentsObject::kSize == 4 * kTaggedSize);
209 210
        a.Allocate(JSStrictArgumentsObject::kSize);
        a.Store(AccessBuilder::ForMap(), arguments_map);
211 212
        a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
                jsgraph()->EmptyFixedArrayConstant());
213 214 215 216 217 218
        a.Store(AccessBuilder::ForJSObjectElements(), elements);
        a.Store(AccessBuilder::ForArgumentsLength(), arguments_length);
        RelaxControls(node);
        a.FinishAndChange(node);
        return Changed(node);
      }
219
      case CreateArgumentsType::kRestParameter: {
220
        Node* effect = NodeProperties::GetEffectInput(node);
221
        Node* const arguments_length =
222
            graph()->NewNode(simplified()->ArgumentsLength());
223
        Node* const rest_length = graph()->NewNode(
224
            simplified()->RestLength(shared.internal_formal_parameter_count()));
225
        // Allocate the elements backing store.
226
        Node* const elements = effect =
227 228 229
            graph()->NewNode(simplified()->NewArgumentsElements(
                                 CreateArgumentsType::kRestParameter,
                                 shared.internal_formal_parameter_count()),
230
                             arguments_length, effect);
231
        // Load the JSArray object map.
232
        Node* const jsarray_map = jsgraph()->Constant(
233
            native_context().js_array_packed_elements_map());
234
        // Actually allocate and initialize the jsarray.
235
        AllocationBuilder a(jsgraph(), effect, control);
236 237
        STATIC_ASSERT(JSArray::kHeaderSize == 4 * kTaggedSize);
        a.Allocate(JSArray::kHeaderSize);
238
        a.Store(AccessBuilder::ForMap(), jsarray_map);
239 240
        a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
                jsgraph()->EmptyFixedArrayConstant());
241 242 243 244
        a.Store(AccessBuilder::ForJSObjectElements(), elements);
        a.Store(AccessBuilder::ForJSArrayLength(PACKED_ELEMENTS), rest_length);
        RelaxControls(node);
        a.FinishAndChange(node);
245 246
        return Changed(node);
      }
247
    }
248
    UNREACHABLE();
249 250 251
  }
  // Use inline allocation for all mapped arguments objects within inlined
  // (i.e. non-outermost) frames, independent of the object size.
252
  DCHECK_EQ(frame_state.outer_frame_state()->opcode(), IrOpcode::kFrameState);
253 254
  switch (type) {
    case CreateArgumentsType::kMappedArguments: {
255 256 257
      Node* const callee = NodeProperties::GetValueInput(node, 0);
      Node* const context = NodeProperties::GetContextInput(node);
      Node* effect = NodeProperties::GetEffectInput(node);
258
      // TODO(turbofan): Duplicate parameters are not handled yet.
259
      if (shared.has_duplicate_parameters()) return NoChange();
260 261 262
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
263 264
      FrameState args_state = GetArgumentsFrameState(frame_state);
      if (args_state.parameters()->opcode() == IrOpcode::kDeadValue) {
265 266 267 268 269
        // This protects against an incompletely propagated DeadValue node.
        // If the FrameState has a DeadValue input, then this node will be
        // pruned anyway.
        return NoChange();
      }
270
      FrameStateInfo args_state_info = args_state.frame_state_info();
271 272 273 274 275 276
      int length = args_state_info.parameter_count() - 1;  // Minus receiver.
      // Check that the array allocated for arguments is not "large".
      {
        const int alloc_size = FixedArray::SizeFor(length);
        if (alloc_size > kMaxRegularHeapObjectSize) return NoChange();
      }
277 278 279 280 281
      // Prepare element backing store to be used by arguments object.
      bool has_aliased_arguments = false;
      Node* const elements = AllocateAliasedArguments(
          effect, control, args_state, context, shared, &has_aliased_arguments);
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
282
      // Load the arguments object map.
283
      Node* const arguments_map = jsgraph()->Constant(
284 285
          has_aliased_arguments ? native_context().fast_aliased_arguments_map()
                                : native_context().sloppy_arguments_map());
286
      // Actually allocate and initialize the arguments object.
287
      AllocationBuilder a(jsgraph(), effect, control);
288
      STATIC_ASSERT(JSSloppyArgumentsObject::kSize == 5 * kTaggedSize);
289
      a.Allocate(JSSloppyArgumentsObject::kSize);
290
      a.Store(AccessBuilder::ForMap(), arguments_map);
291 292
      a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
              jsgraph()->EmptyFixedArrayConstant());
293 294 295 296 297 298
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
      a.Store(AccessBuilder::ForArgumentsLength(), jsgraph()->Constant(length));
      a.Store(AccessBuilder::ForArgumentsCallee(), callee);
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
299 300
    }
    case CreateArgumentsType::kUnmappedArguments: {
301 302 303 304 305 306
      // Use inline allocation for all unmapped arguments objects within inlined
      // (i.e. non-outermost) frames, independent of the object size.
      Node* effect = NodeProperties::GetEffectInput(node);
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
307 308
      FrameState args_state = GetArgumentsFrameState(frame_state);
      if (args_state.parameters()->opcode() == IrOpcode::kDeadValue) {
309 310 311 312 313
        // This protects against an incompletely propagated DeadValue node.
        // If the FrameState has a DeadValue input, then this node will be
        // pruned anyway.
        return NoChange();
      }
314
      FrameStateInfo args_state_info = args_state.frame_state_info();
315 316 317 318 319 320
      int length = args_state_info.parameter_count() - 1;  // Minus receiver.
      // Check that the array allocated for arguments is not "large".
      {
        const int alloc_size = FixedArray::SizeFor(length);
        if (alloc_size > kMaxRegularHeapObjectSize) return NoChange();
      }
321 322 323
      // Prepare element backing store to be used by arguments object.
      Node* const elements = AllocateArguments(effect, control, args_state);
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
324
      // Load the arguments object map.
325
      Node* const arguments_map =
326
          jsgraph()->Constant(native_context().strict_arguments_map());
327
      // Actually allocate and initialize the arguments object.
328
      AllocationBuilder a(jsgraph(), effect, control);
329
      STATIC_ASSERT(JSStrictArgumentsObject::kSize == 4 * kTaggedSize);
330
      a.Allocate(JSStrictArgumentsObject::kSize);
331
      a.Store(AccessBuilder::ForMap(), arguments_map);
332 333
      a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
              jsgraph()->EmptyFixedArrayConstant());
334 335 336 337 338
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
      a.Store(AccessBuilder::ForArgumentsLength(), jsgraph()->Constant(length));
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
339 340
    }
    case CreateArgumentsType::kRestParameter: {
341
      int start_index = shared.internal_formal_parameter_count();
342 343 344 345 346 347
      // Use inline allocation for all unmapped arguments objects within inlined
      // (i.e. non-outermost) frames, independent of the object size.
      Node* effect = NodeProperties::GetEffectInput(node);
      // Choose the correct frame state and frame state info depending on
      // whether there conceptually is an arguments adaptor frame in the call
      // chain.
348 349
      FrameState args_state = GetArgumentsFrameState(frame_state);
      if (args_state.parameters()->opcode() == IrOpcode::kDeadValue) {
350 351 352 353 354
        // This protects against an incompletely propagated DeadValue node.
        // If the FrameState has a DeadValue input, then this node will be
        // pruned anyway.
        return NoChange();
      }
355
      FrameStateInfo args_state_info = args_state.frame_state_info();
356 357 358 359
      // Prepare element backing store to be used by the rest array.
      Node* const elements =
          AllocateRestArguments(effect, control, args_state, start_index);
      effect = elements->op()->EffectOutputCount() > 0 ? elements : effect;
360
      // Load the JSArray object map.
361 362
      Node* const jsarray_map =
          jsgraph()->Constant(native_context().js_array_packed_elements_map());
363
      // Actually allocate and initialize the jsarray.
364
      AllocationBuilder a(jsgraph(), effect, control);
365 366 367 368

      // -1 to minus receiver
      int argument_count = args_state_info.parameter_count() - 1;
      int length = std::max(0, argument_count - start_index);
369 370
      STATIC_ASSERT(JSArray::kHeaderSize == 4 * kTaggedSize);
      a.Allocate(JSArray::kHeaderSize);
371
      a.Store(AccessBuilder::ForMap(), jsarray_map);
372 373
      a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
              jsgraph()->EmptyFixedArrayConstant());
374
      a.Store(AccessBuilder::ForJSObjectElements(), elements);
375
      a.Store(AccessBuilder::ForJSArrayLength(PACKED_ELEMENTS),
376 377 378 379 380 381
              jsgraph()->Constant(length));
      RelaxControls(node);
      a.FinishAndChange(node);
      return Changed(node);
    }
  }
382
  UNREACHABLE();
383 384
}

385 386 387 388 389
Reduction JSCreateLowering::ReduceJSCreateGeneratorObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateGeneratorObject, node->opcode());
  Node* const closure = NodeProperties::GetValueInput(node, 0);
  Node* const receiver = NodeProperties::GetValueInput(node, 1);
  Node* const context = NodeProperties::GetContextInput(node);
390
  Type const closure_type = NodeProperties::GetType(closure);
391 392
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* const control = NodeProperties::GetControlInput(node);
393
  if (closure_type.IsHeapConstant()) {
394 395 396
    DCHECK(closure_type.AsHeapConstant()->Ref().IsJSFunction());
    JSFunctionRef js_function =
        closure_type.AsHeapConstant()->Ref().AsJSFunction();
397
    if (!js_function.has_initial_map()) return NoChange();
398

399 400
    SlackTrackingPrediction slack_tracking_prediction =
        dependencies()->DependOnInitialMapInstanceSizePrediction(js_function);
401

402
    MapRef initial_map = js_function.initial_map();
403 404
    DCHECK(initial_map.instance_type() == JS_GENERATOR_OBJECT_TYPE ||
           initial_map.instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE);
405

406
    // Allocate a register file.
407
    SharedFunctionInfoRef shared = js_function.shared();
408 409
    DCHECK(shared.HasBytecodeArray());
    int parameter_count_no_receiver = shared.internal_formal_parameter_count();
410 411
    int size = parameter_count_no_receiver +
               shared.GetBytecodeArray().register_count();
412
    AllocationBuilder ab(jsgraph(), effect, control);
413
    ab.AllocateArray(size, MapRef(broker(), factory()->fixed_array_map()));
414 415 416 417
    for (int i = 0; i < size; ++i) {
      ab.Store(AccessBuilder::ForFixedArraySlot(i),
               jsgraph()->UndefinedConstant());
    }
418
    Node* parameters_and_registers = effect = ab.Finish();
419

420
    // Emit code to allocate the JS[Async]GeneratorObject instance.
421
    AllocationBuilder a(jsgraph(), effect, control);
422
    a.Allocate(slack_tracking_prediction.instance_size());
423 424
    Node* undefined = jsgraph()->UndefinedConstant();
    a.Store(AccessBuilder::ForMap(), initial_map);
425 426 427 428
    a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
            jsgraph()->EmptyFixedArrayConstant());
    a.Store(AccessBuilder::ForJSObjectElements(),
            jsgraph()->EmptyFixedArrayConstant());
429 430 431 432 433 434 435 436
    a.Store(AccessBuilder::ForJSGeneratorObjectContext(), context);
    a.Store(AccessBuilder::ForJSGeneratorObjectFunction(), closure);
    a.Store(AccessBuilder::ForJSGeneratorObjectReceiver(), receiver);
    a.Store(AccessBuilder::ForJSGeneratorObjectInputOrDebugPos(), undefined);
    a.Store(AccessBuilder::ForJSGeneratorObjectResumeMode(),
            jsgraph()->Constant(JSGeneratorObject::kNext));
    a.Store(AccessBuilder::ForJSGeneratorObjectContinuation(),
            jsgraph()->Constant(JSGeneratorObject::kGeneratorExecuting));
437 438
    a.Store(AccessBuilder::ForJSGeneratorObjectParametersAndRegisters(),
            parameters_and_registers);
439

440
    if (initial_map.instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE) {
441
      a.Store(AccessBuilder::ForJSAsyncGeneratorObjectQueue(), undefined);
442 443
      a.Store(AccessBuilder::ForJSAsyncGeneratorObjectIsAwaiting(),
              jsgraph()->ZeroConstant());
444 445 446
    }

    // Handle in-object properties, too.
447 448
    for (int i = 0; i < slack_tracking_prediction.inobject_property_count();
         ++i) {
449 450
      a.Store(AccessBuilder::ForJSObjectInObjectProperty(initial_map, i),
              undefined);
451 452 453 454 455 456 457
    }
    a.FinishAndChange(node);
    return Changed(node);
  }
  return NoChange();
}

458 459
// Constructs an array with a variable {length} when no upper bound
// is known for the capacity.
460
Reduction JSCreateLowering::ReduceNewArray(
461
    Node* node, Node* length, MapRef initial_map, ElementsKind elements_kind,
462
    AllocationType allocation,
463
    const SlackTrackingPrediction& slack_tracking_prediction) {
464 465 466 467 468 469
  DCHECK_EQ(IrOpcode::kJSCreateArray, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Constructing an Array via new Array(N) where N is an unsigned
  // integer, always creates a holey backing store.
470
  ASSIGN_RETURN_NO_CHANGE_IF_DATA_MISSING(
471 472
      initial_map,
      initial_map.AsElementsKind(GetHoleyElementsKind(elements_kind)));
473

474 475 476 477 478 479
  // Because CheckBounds performs implicit conversion from string to number, an
  // additional CheckNumber is required to behave correctly for calls with a
  // single string argument.
  length = effect = graph()->NewNode(
      simplified()->CheckNumber(FeedbackSource{}), length, effect, control);

480 481 482 483
  // Check that the {limit} is an unsigned integer in the valid range.
  // This has to be kept in sync with src/runtime/runtime-array.cc,
  // where this limit is protected.
  length = effect = graph()->NewNode(
484
      simplified()->CheckBounds(FeedbackSource()), length,
485 486 487 488
      jsgraph()->Constant(JSArray::kInitialMaxFastElementArray), effect,
      control);

  // Construct elements and properties for the resulting JSArray.
489
  Node* elements = effect =
490
      graph()->NewNode(IsDoubleElementsKind(initial_map.elements_kind())
491 492
                           ? simplified()->NewDoubleElements(allocation)
                           : simplified()->NewSmiOrObjectElements(allocation),
493
                       length, effect, control);
494 495

  // Perform the allocation of the actual JSArray object.
496
  AllocationBuilder a(jsgraph(), effect, control);
497
  a.Allocate(slack_tracking_prediction.instance_size(), allocation);
498
  a.Store(AccessBuilder::ForMap(), initial_map);
499 500
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
501
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
502
  a.Store(AccessBuilder::ForJSArrayLength(initial_map.elements_kind()), length);
503 504
  for (int i = 0; i < slack_tracking_prediction.inobject_property_count();
       ++i) {
505
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(initial_map, i),
506 507 508 509 510 511 512 513 514
            jsgraph()->UndefinedConstant());
  }
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

// Constructs an array with a variable {length} when an actual
// upper bound is known for the {capacity}.
515 516
Reduction JSCreateLowering::ReduceNewArray(
    Node* node, Node* length, int capacity, MapRef initial_map,
517
    ElementsKind elements_kind, AllocationType allocation,
518
    const SlackTrackingPrediction& slack_tracking_prediction) {
519 520
  DCHECK(node->opcode() == IrOpcode::kJSCreateArray ||
         node->opcode() == IrOpcode::kJSCreateEmptyLiteralArray);
521
  DCHECK(NodeProperties::GetType(length).Is(Type::Number()));
522 523 524
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

525
  // Determine the appropriate elements kind.
526
  if (NodeProperties::GetType(length).Max() > 0.0) {
527 528
    elements_kind = GetHoleyElementsKind(elements_kind);
  }
529 530
  ASSIGN_RETURN_NO_CHANGE_IF_DATA_MISSING(
      initial_map, initial_map.AsElementsKind(elements_kind));
531
  DCHECK(IsFastElementsKind(elements_kind));
532 533 534 535 536 537 538

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

  // Perform the allocation of the actual JSArray object.
543
  AllocationBuilder a(jsgraph(), effect, control);
544
  a.Allocate(slack_tracking_prediction.instance_size(), allocation);
545
  a.Store(AccessBuilder::ForMap(), initial_map);
546 547
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
548 549
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
  a.Store(AccessBuilder::ForJSArrayLength(elements_kind), length);
550 551
  for (int i = 0; i < slack_tracking_prediction.inobject_property_count();
       ++i) {
552
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(initial_map, i),
553 554
            jsgraph()->UndefinedConstant());
  }
555 556 557 558 559
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

560 561
Reduction JSCreateLowering::ReduceNewArray(
    Node* node, std::vector<Node*> values, MapRef initial_map,
562
    ElementsKind elements_kind, AllocationType allocation,
563
    const SlackTrackingPrediction& slack_tracking_prediction) {
564 565 566 567
  DCHECK_EQ(IrOpcode::kJSCreateArray, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

568
  // Determine the appropriate elements kind.
569
  DCHECK(IsFastElementsKind(elements_kind));
570 571
  ASSIGN_RETURN_NO_CHANGE_IF_DATA_MISSING(
      initial_map, initial_map.AsElementsKind(elements_kind));
572 573 574 575

  // Check {values} based on the {elements_kind}. These checks are guarded
  // by the {elements_kind} feedback on the {site}, so it's safe to just
  // deoptimize in this case.
576
  if (IsSmiElementsKind(elements_kind)) {
577
    for (auto& value : values) {
578
      if (!NodeProperties::GetType(value).Is(Type::SignedSmall())) {
579
        value = effect = graph()->NewNode(
580
            simplified()->CheckSmi(FeedbackSource()), value, effect, control);
581 582
      }
    }
583
  } else if (IsDoubleElementsKind(elements_kind)) {
584
    for (auto& value : values) {
585
      if (!NodeProperties::GetType(value).Is(Type::Number())) {
586
        value = effect =
587
            graph()->NewNode(simplified()->CheckNumber(FeedbackSource()), value,
588
                             effect, control);
589 590 591 592 593 594 595 596
      }
      // Make sure we do not store signaling NaNs into double arrays.
      value = graph()->NewNode(simplified()->NumberSilenceNaN(), value);
    }
  }

  // Setup elements, properties and length.
  Node* elements = effect =
597
      AllocateElements(effect, control, elements_kind, values, allocation);
598 599 600
  Node* length = jsgraph()->Constant(static_cast<int>(values.size()));

  // Perform the allocation of the actual JSArray object.
601
  AllocationBuilder a(jsgraph(), effect, control);
602
  a.Allocate(slack_tracking_prediction.instance_size(), allocation);
603
  a.Store(AccessBuilder::ForMap(), initial_map);
604 605
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
606 607
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
  a.Store(AccessBuilder::ForJSArrayLength(elements_kind), length);
608 609
  for (int i = 0; i < slack_tracking_prediction.inobject_property_count();
       ++i) {
610
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(initial_map, i),
611 612
            jsgraph()->UndefinedConstant());
  }
613 614 615 616 617
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

618 619 620
Reduction JSCreateLowering::ReduceJSCreateArray(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateArray, node->opcode());
  CreateArrayParameters const& p = CreateArrayParametersOf(node->op());
621
  int const arity = static_cast<int>(p.arity());
622 623 624 625
  base::Optional<AllocationSiteRef> site_ref;
  {
    Handle<AllocationSite> site;
    if (p.site().ToHandle(&site)) {
626
      site_ref = AllocationSiteRef(broker(), site);
627
    }
628
  }
629
  AllocationType allocation = AllocationType::kYoung;
630 631 632 633 634

  base::Optional<MapRef> initial_map =
      NodeProperties::GetJSCreateMap(broker(), node);
  if (!initial_map.has_value()) return NoChange();

635
  Node* new_target = NodeProperties::GetValueInput(node, 1);
636 637 638 639 640
  JSFunctionRef original_constructor =
      HeapObjectMatcher(new_target).Ref(broker()).AsJSFunction();
  SlackTrackingPrediction slack_tracking_prediction =
      dependencies()->DependOnInitialMapInstanceSizePrediction(
          original_constructor);
641

642 643 644 645 646 647 648 649 650 651 652 653
  // Tells whether we are protected by either the {site} or a
  // protector cell to do certain speculative optimizations.
  bool can_inline_call = false;

  // Check if we have a feedback {site} on the {node}.
  ElementsKind elements_kind = initial_map->elements_kind();
  if (site_ref) {
    elements_kind = site_ref->GetElementsKind();
    can_inline_call = site_ref->CanInlineCall();
    allocation = dependencies()->DependOnPretenureMode(*site_ref);
    dependencies()->DependOnElementsKind(*site_ref);
  } else {
654
    PropertyCellRef array_constructor_protector(
655
        broker(), factory()->array_constructor_protector());
656 657
    can_inline_call = array_constructor_protector.value().AsSmi() ==
                      Protectors::kProtectorValid;
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  }

  if (arity == 0) {
    Node* length = jsgraph()->ZeroConstant();
    int capacity = JSArray::kPreallocatedArrayElements;
    return ReduceNewArray(node, length, capacity, *initial_map, elements_kind,
                          allocation, slack_tracking_prediction);
  } else if (arity == 1) {
    Node* length = NodeProperties::GetValueInput(node, 2);
    Type length_type = NodeProperties::GetType(length);
    if (!length_type.Maybe(Type::Number())) {
      // Handle the single argument case, where we know that the value
      // cannot be a valid Array length.
      elements_kind = GetMoreGeneralElementsKind(
          elements_kind, IsHoleyElementsKind(elements_kind) ? HOLEY_ELEMENTS
                                                            : PACKED_ELEMENTS);
      return ReduceNewArray(node, std::vector<Node*>{length}, *initial_map,
                            elements_kind, allocation,
                            slack_tracking_prediction);
    }
    if (length_type.Is(Type::SignedSmall()) && length_type.Min() >= 0 &&
        length_type.Max() <= kElementLoopUnrollLimit &&
        length_type.Min() == length_type.Max()) {
      int capacity = static_cast<int>(length_type.Max());
682 683 684
      // Replace length with a constant in order to protect against a potential
      // typer bug leading to length > capacity.
      length = jsgraph()->Constant(capacity);
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
      return ReduceNewArray(node, length, capacity, *initial_map, elements_kind,
                            allocation, slack_tracking_prediction);
    }
    if (length_type.Maybe(Type::UnsignedSmall()) && can_inline_call) {
      return ReduceNewArray(node, length, *initial_map, elements_kind,
                            allocation, slack_tracking_prediction);
    }
  } else if (arity <= JSArray::kInitialMaxFastElementArray) {
    // Gather the values to store into the newly created array.
    bool values_all_smis = true, values_all_numbers = true,
         values_any_nonnumber = false;
    std::vector<Node*> values;
    values.reserve(p.arity());
    for (int i = 0; i < arity; ++i) {
      Node* value = NodeProperties::GetValueInput(node, 2 + i);
      Type value_type = NodeProperties::GetType(value);
      if (!value_type.Is(Type::SignedSmall())) {
        values_all_smis = false;
      }
      if (!value_type.Is(Type::Number())) {
        values_all_numbers = false;
706
      }
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
      if (!value_type.Maybe(Type::Number())) {
        values_any_nonnumber = true;
      }
      values.push_back(value);
    }

    // Try to figure out the ideal elements kind statically.
    if (values_all_smis) {
      // Smis can be stored with any elements kind.
    } else if (values_all_numbers) {
      elements_kind = GetMoreGeneralElementsKind(
          elements_kind, IsHoleyElementsKind(elements_kind)
                             ? HOLEY_DOUBLE_ELEMENTS
                             : PACKED_DOUBLE_ELEMENTS);
    } else if (values_any_nonnumber) {
      elements_kind = GetMoreGeneralElementsKind(
          elements_kind, IsHoleyElementsKind(elements_kind) ? HOLEY_ELEMENTS
                                                            : PACKED_ELEMENTS);
    } else if (!can_inline_call) {
      // We have some crazy combination of types for the {values} where
      // there's no clear decision on the elements kind statically. And
      // we don't have a protection against deoptimization loops for the
      // checks that are introduced in the call to ReduceNewArray, so
      // we cannot inline this invocation of the Array constructor here.
      return NoChange();
732
    }
733 734
    return ReduceNewArray(node, values, *initial_map, elements_kind, allocation,
                          slack_tracking_prediction);
735
  }
736
  return NoChange();
737 738
}

739 740 741 742 743 744 745 746 747
Reduction JSCreateLowering::ReduceJSCreateArrayIterator(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateArrayIterator, node->opcode());
  CreateArrayIteratorParameters const& p =
      CreateArrayIteratorParametersOf(node->op());
  Node* iterated_object = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Create the JSArrayIterator result.
748
  AllocationBuilder a(jsgraph(), effect, control);
749
  a.Allocate(JSArrayIterator::kHeaderSize, AllocationType::kYoung,
750
             Type::OtherObject());
751
  a.Store(AccessBuilder::ForMap(),
752
          native_context().initial_array_iterator_map());
753
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
754 755 756 757 758 759 760 761 762 763 764 765 766
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSArrayIteratorIteratedObject(), iterated_object);
  a.Store(AccessBuilder::ForJSArrayIteratorNextIndex(),
          jsgraph()->ZeroConstant());
  a.Store(AccessBuilder::ForJSArrayIteratorKind(),
          jsgraph()->Constant(static_cast<int>(p.kind())));
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

767 768 769 770 771 772 773 774 775 776 777 778
Reduction JSCreateLowering::ReduceJSCreateAsyncFunctionObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateAsyncFunctionObject, node->opcode());
  int const register_count = RegisterCountOf(node->op());
  Node* closure = NodeProperties::GetValueInput(node, 0);
  Node* receiver = NodeProperties::GetValueInput(node, 1);
  Node* promise = NodeProperties::GetValueInput(node, 2);
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Create the register file.
  AllocationBuilder ab(jsgraph(), effect, control);
779 780
  ab.AllocateArray(register_count,
                   MapRef(broker(), factory()->fixed_array_map()));
781 782 783 784 785 786 787 788
  for (int i = 0; i < register_count; ++i) {
    ab.Store(AccessBuilder::ForFixedArraySlot(i),
             jsgraph()->UndefinedConstant());
  }
  Node* parameters_and_registers = effect = ab.Finish();

  // Create the JSAsyncFunctionObject result.
  AllocationBuilder a(jsgraph(), effect, control);
789
  a.Allocate(JSAsyncFunctionObject::kHeaderSize);
790 791
  a.Store(AccessBuilder::ForMap(),
          native_context().async_function_object_map());
792 793 794 795
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  a.Store(AccessBuilder::ForJSGeneratorObjectContext(), context);
  a.Store(AccessBuilder::ForJSGeneratorObjectFunction(), closure);
  a.Store(AccessBuilder::ForJSGeneratorObjectReceiver(), receiver);
  a.Store(AccessBuilder::ForJSGeneratorObjectInputOrDebugPos(),
          jsgraph()->UndefinedConstant());
  a.Store(AccessBuilder::ForJSGeneratorObjectResumeMode(),
          jsgraph()->Constant(JSGeneratorObject::kNext));
  a.Store(AccessBuilder::ForJSGeneratorObjectContinuation(),
          jsgraph()->Constant(JSGeneratorObject::kGeneratorExecuting));
  a.Store(AccessBuilder::ForJSGeneratorObjectParametersAndRegisters(),
          parameters_and_registers);
  a.Store(AccessBuilder::ForJSAsyncFunctionObjectPromise(), promise);
  a.FinishAndChange(node);
  return Changed(node);
}

812 813
namespace {

814 815 816
MapRef MapForCollectionIterationKind(const NativeContextRef& native_context,
                                     CollectionKind collection_kind,
                                     IterationKind iteration_kind) {
817 818 819 820 821 822
  switch (collection_kind) {
    case CollectionKind::kSet:
      switch (iteration_kind) {
        case IterationKind::kKeys:
          UNREACHABLE();
        case IterationKind::kValues:
823
          return native_context.set_value_iterator_map();
824
        case IterationKind::kEntries:
825
          return native_context.set_key_value_iterator_map();
826 827 828 829 830
      }
      break;
    case CollectionKind::kMap:
      switch (iteration_kind) {
        case IterationKind::kKeys:
831
          return native_context.map_key_iterator_map();
832
        case IterationKind::kValues:
833
          return native_context.map_value_iterator_map();
834
        case IterationKind::kEntries:
835
          return native_context.map_key_value_iterator_map();
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
      }
      break;
  }
  UNREACHABLE();
}

}  // namespace

Reduction JSCreateLowering::ReduceJSCreateCollectionIterator(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateCollectionIterator, node->opcode());
  CreateCollectionIteratorParameters const& p =
      CreateCollectionIteratorParametersOf(node->op());
  Node* iterated_object = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Load the OrderedHashTable from the {receiver}.
  Node* table = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForJSCollectionTable()),
      iterated_object, effect, control);

857
  // Create the JSCollectionIterator result.
858
  AllocationBuilder a(jsgraph(), effect, control);
859
  a.Allocate(JSCollectionIterator::kHeaderSize, AllocationType::kYoung,
860
             Type::OtherObject());
861
  a.Store(AccessBuilder::ForMap(),
862 863
          MapForCollectionIterationKind(native_context(), p.collection_kind(),
                                        p.iteration_kind()));
864
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
865 866 867 868 869 870 871 872 873 874 875
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSCollectionIteratorTable(), table);
  a.Store(AccessBuilder::ForJSCollectionIteratorIndex(),
          jsgraph()->ZeroConstant());
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

876 877 878 879 880
Reduction JSCreateLowering::ReduceJSCreateBoundFunction(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateBoundFunction, node->opcode());
  CreateBoundFunctionParameters const& p =
      CreateBoundFunctionParametersOf(node->op());
  int const arity = static_cast<int>(p.arity());
881
  MapRef const map(broker(), p.map());
882 883 884 885 886 887 888 889
  Node* bound_target_function = NodeProperties::GetValueInput(node, 0);
  Node* bound_this = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Create the [[BoundArguments]] for the result.
  Node* bound_arguments = jsgraph()->EmptyFixedArrayConstant();
  if (arity > 0) {
890
    AllocationBuilder a(jsgraph(), effect, control);
891
    a.AllocateArray(arity, MapRef(broker(), factory()->fixed_array_map()));
892 893 894 895 896 897 898 899
    for (int i = 0; i < arity; ++i) {
      a.Store(AccessBuilder::ForFixedArraySlot(i),
              NodeProperties::GetValueInput(node, 2 + i));
    }
    bound_arguments = effect = a.Finish();
  }

  // Create the JSBoundFunction result.
900
  AllocationBuilder a(jsgraph(), effect, control);
901
  a.Allocate(JSBoundFunction::kHeaderSize, AllocationType::kYoung,
902
             Type::BoundFunction());
903
  a.Store(AccessBuilder::ForMap(), map);
904
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
905 906 907 908 909 910 911 912 913 914 915 916
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSBoundFunctionBoundTargetFunction(),
          bound_target_function);
  a.Store(AccessBuilder::ForJSBoundFunctionBoundThis(), bound_this);
  a.Store(AccessBuilder::ForJSBoundFunctionBoundArguments(), bound_arguments);
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

917
Reduction JSCreateLowering::ReduceJSCreateClosure(Node* node) {
918 919
  JSCreateClosureNode n(node);
  CreateClosureParameters const& p = n.Parameters();
920
  SharedFunctionInfoRef shared(broker(), p.shared_info());
921
  FeedbackCellRef feedback_cell = n.GetFeedbackCellRefChecked(broker());
922
  HeapObjectRef code(broker(), p.code());
923 924 925
  Effect effect = n.effect();
  Control control = n.control();
  Node* context = n.context();
926 927 928 929

  // Use inline allocation of closures only for instantiation sites that have
  // seen more than one instantiation, this simplifies the generated code and
  // also serves as a heuristic of which allocation sites benefit from it.
930
  if (!feedback_cell.map().equals(
931
          MapRef(broker(), factory()->many_closures_cell_map()))) {
932
    return NoChange();
933 934
  }

935
  MapRef function_map =
936
      native_context().GetFunctionMapFromIndex(shared.function_map_index());
937 938
  DCHECK(!function_map.IsInobjectSlackTrackingInProgress());
  DCHECK(!function_map.is_dictionary_map());
939

940 941 942 943 944 945 946 947 948
  // TODO(turbofan): We should use the pretenure flag from {p} here,
  // but currently the heuristic in the parser works against us, as
  // it marks closures like
  //
  //   args[l] = function(...) { ... }
  //
  // for old-space allocation, which doesn't always make sense. For
  // example in case of the bluebird-parallel benchmark, where this
  // is a core part of the *promisify* logic (see crbug.com/810132).
949
  AllocationType allocation = AllocationType::kYoung;
950

951
  // Emit code to allocate the JSFunction instance.
952
  STATIC_ASSERT(JSFunction::kSizeWithoutPrototype == 7 * kTaggedSize);
953
  AllocationBuilder a(jsgraph(), effect, control);
954
  a.Allocate(function_map.instance_size(), allocation, Type::Function());
955
  a.Store(AccessBuilder::ForMap(), function_map);
956
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
957 958 959 960 961
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSFunctionSharedFunctionInfo(), shared);
  a.Store(AccessBuilder::ForJSFunctionContext(), context);
962
  a.Store(AccessBuilder::ForJSFunctionFeedbackCell(), feedback_cell);
963
  a.Store(AccessBuilder::ForJSFunctionCode(), code);
964
  STATIC_ASSERT(JSFunction::kSizeWithoutPrototype == 7 * kTaggedSize);
965
  if (function_map.has_prototype_slot()) {
966 967
    a.Store(AccessBuilder::ForJSFunctionPrototypeOrInitialMap(),
            jsgraph()->TheHoleConstant());
968
    STATIC_ASSERT(JSFunction::kSizeWithPrototype == 8 * kTaggedSize);
969
  }
970
  for (int i = 0; i < function_map.GetInObjectProperties(); i++) {
971 972 973 974 975 976
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(function_map, i),
            jsgraph()->UndefinedConstant());
  }
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
977 978
}

979 980 981 982 983 984
Reduction JSCreateLowering::ReduceJSCreateIterResultObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateIterResultObject, node->opcode());
  Node* value = NodeProperties::GetValueInput(node, 0);
  Node* done = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);

985
  Node* iterator_result_map =
986
      jsgraph()->Constant(native_context().iterator_result_map());
987 988

  // Emit code to allocate the JSIteratorResult instance.
989
  AllocationBuilder a(jsgraph(), effect, graph()->start());
990 991
  a.Allocate(JSIteratorResult::kSize);
  a.Store(AccessBuilder::ForMap(), iterator_result_map);
992
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
993 994 995 996 997
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSIteratorResultValue(), value);
  a.Store(AccessBuilder::ForJSIteratorResultDone(), done);
998
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kTaggedSize);
999 1000 1001 1002
  a.FinishAndChange(node);
  return Changed(node);
}

1003 1004 1005 1006 1007
Reduction JSCreateLowering::ReduceJSCreateStringIterator(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateStringIterator, node->opcode());
  Node* string = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);

1008 1009
  Node* map =
      jsgraph()->Constant(native_context().initial_string_iterator_map());
1010
  // Allocate new iterator and attach the iterator to this string.
1011
  AllocationBuilder a(jsgraph(), effect, graph()->start());
1012
  a.Allocate(JSStringIterator::kHeaderSize, AllocationType::kYoung,
1013
             Type::OtherObject());
1014
  a.Store(AccessBuilder::ForMap(), map);
1015
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
1016 1017 1018 1019 1020
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSStringIteratorString(), string);
  a.Store(AccessBuilder::ForJSStringIteratorIndex(), jsgraph()->SmiConstant(0));
1021
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kTaggedSize);
1022 1023 1024 1025
  a.FinishAndChange(node);
  return Changed(node);
}

1026 1027 1028 1029 1030 1031
Reduction JSCreateLowering::ReduceJSCreateKeyValueArray(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateKeyValueArray, node->opcode());
  Node* key = NodeProperties::GetValueInput(node, 0);
  Node* value = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);

1032
  Node* array_map =
1033
      jsgraph()->Constant(native_context().js_array_packed_elements_map());
1034 1035
  Node* length = jsgraph()->Constant(2);

1036
  AllocationBuilder aa(jsgraph(), effect, graph()->start());
1037
  aa.AllocateArray(2, MapRef(broker(), factory()->fixed_array_map()));
1038
  aa.Store(AccessBuilder::ForFixedArrayElement(PACKED_ELEMENTS),
1039
           jsgraph()->ZeroConstant(), key);
1040
  aa.Store(AccessBuilder::ForFixedArrayElement(PACKED_ELEMENTS),
1041
           jsgraph()->OneConstant(), value);
1042 1043
  Node* elements = aa.Finish();

1044
  AllocationBuilder a(jsgraph(), elements, graph()->start());
1045
  a.Allocate(JSArray::kHeaderSize);
1046
  a.Store(AccessBuilder::ForMap(), array_map);
1047 1048
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
1049
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
1050
  a.Store(AccessBuilder::ForJSArrayLength(PACKED_ELEMENTS), length);
1051
  STATIC_ASSERT(JSArray::kHeaderSize == 4 * kTaggedSize);
1052 1053 1054 1055
  a.FinishAndChange(node);
  return Changed(node);
}

1056 1057 1058 1059
Reduction JSCreateLowering::ReduceJSCreatePromise(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreatePromise, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);

1060
  MapRef promise_map = native_context().promise_function().initial_map();
1061

1062
  AllocationBuilder a(jsgraph(), effect, graph()->start());
1063
  a.Allocate(promise_map.instance_size());
1064
  a.Store(AccessBuilder::ForMap(), promise_map);
1065
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
1066 1067 1068
          jsgraph()->EmptyFixedArrayConstant());
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
1069 1070
  a.Store(AccessBuilder::ForJSObjectOffset(JSPromise::kReactionsOrResultOffset),
          jsgraph()->ZeroConstant());
1071 1072 1073
  STATIC_ASSERT(v8::Promise::kPending == 0);
  a.Store(AccessBuilder::ForJSObjectOffset(JSPromise::kFlagsOffset),
          jsgraph()->ZeroConstant());
1074 1075
  STATIC_ASSERT(JSPromise::kHeaderSize == 5 * kTaggedSize);
  for (int offset = JSPromise::kHeaderSize;
1076 1077 1078
       offset < JSPromise::kSizeWithEmbedderFields; offset += kTaggedSize) {
    a.Store(AccessBuilder::ForJSObjectOffset(offset),
            jsgraph()->ZeroConstant());
1079 1080 1081 1082 1083
  }
  a.FinishAndChange(node);
  return Changed(node);
}

1084
Reduction JSCreateLowering::ReduceJSCreateLiteralArrayOrObject(Node* node) {
1085 1086
  DCHECK(node->opcode() == IrOpcode::kJSCreateLiteralArray ||
         node->opcode() == IrOpcode::kJSCreateLiteralObject);
1087 1088 1089 1090
  JSCreateLiteralOpNode n(node);
  CreateLiteralParameters const& p = n.Parameters();
  Effect effect = n.effect();
  Control control = n.control();
1091 1092 1093 1094
  ProcessedFeedback const& feedback =
      broker()->GetFeedbackForArrayOrObjectLiteral(p.feedback());
  if (!feedback.IsInsufficient()) {
    AllocationSiteRef site = feedback.AsLiteral().value();
1095
    if (site.IsFastLiteral()) {
1096
      AllocationType allocation = AllocationType::kYoung;
1097
      if (FLAG_allocation_site_pretenuring) {
1098
        allocation = dependencies()->DependOnPretenureMode(site);
1099
      }
1100
      dependencies()->DependOnElementsKinds(site);
1101
      JSObjectRef boilerplate = site.boilerplate().value();
1102
      Node* value = effect =
1103
          AllocateFastLiteral(effect, control, boilerplate, allocation);
1104 1105
      ReplaceWithValue(node, value, effect, control);
      return Replace(value);
1106 1107
    }
  }
1108

1109 1110
  return NoChange();
}
1111

1112
Reduction JSCreateLowering::ReduceJSCreateEmptyLiteralArray(Node* node) {
1113 1114
  JSCreateEmptyLiteralArrayNode n(node);
  FeedbackParameter const& p = n.Parameters();
1115 1116 1117 1118
  ProcessedFeedback const& feedback =
      broker()->GetFeedbackForArrayOrObjectLiteral(p.feedback());
  if (!feedback.IsInsufficient()) {
    AllocationSiteRef site = feedback.AsLiteral().value();
1119 1120
    DCHECK(!site.PointsToLiteral());
    MapRef initial_map =
1121
        native_context().GetInitialJSArrayMap(site.GetElementsKind());
1122 1123
    AllocationType const allocation =
        dependencies()->DependOnPretenureMode(site);
1124
    dependencies()->DependOnElementsKind(site);
1125
    Node* length = jsgraph()->ZeroConstant();
1126 1127 1128
    DCHECK(!initial_map.IsInobjectSlackTrackingInProgress());
    SlackTrackingPrediction slack_tracking_prediction(
        initial_map, initial_map.instance_size());
1129
    return ReduceNewArray(node, length, 0, initial_map,
1130
                          initial_map.elements_kind(), allocation,
1131
                          slack_tracking_prediction);
1132 1133 1134 1135
  }
  return NoChange();
}

1136
Reduction JSCreateLowering::ReduceJSCreateEmptyLiteralObject(Node* node) {
1137 1138 1139 1140 1141
  DCHECK_EQ(IrOpcode::kJSCreateEmptyLiteralObject, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Retrieve the initial map for the object.
1142
  MapRef map = native_context().object_function().initial_map();
1143 1144 1145
  DCHECK(!map.is_dictionary_map());
  DCHECK(!map.IsInobjectSlackTrackingInProgress());
  Node* js_object_map = jsgraph()->Constant(map);
1146 1147 1148 1149 1150

  // Setup elements and properties.
  Node* elements = jsgraph()->EmptyFixedArrayConstant();

  // Perform the allocation of the actual JSArray object.
1151
  AllocationBuilder a(jsgraph(), effect, control);
1152
  a.Allocate(map.instance_size());
1153
  a.Store(AccessBuilder::ForMap(), js_object_map);
1154 1155
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
          jsgraph()->EmptyFixedArrayConstant());
1156
  a.Store(AccessBuilder::ForJSObjectElements(), elements);
1157 1158
  for (int i = 0; i < map.GetInObjectProperties(); i++) {
    a.Store(AccessBuilder::ForJSObjectInObjectProperty(map, i),
1159 1160 1161 1162 1163 1164 1165 1166
            jsgraph()->UndefinedConstant());
  }

  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

1167
Reduction JSCreateLowering::ReduceJSCreateLiteralRegExp(Node* node) {
1168 1169 1170 1171
  JSCreateLiteralRegExpNode n(node);
  CreateLiteralParameters const& p = n.Parameters();
  Effect effect = n.effect();
  Control control = n.control();
1172 1173 1174
  ProcessedFeedback const& feedback =
      broker()->GetFeedbackForRegExpLiteral(p.feedback());
  if (!feedback.IsInsufficient()) {
1175 1176
    RegExpBoilerplateDescriptionRef literal =
        feedback.AsRegExpLiteral().value();
1177
    Node* value = effect = AllocateLiteralRegExp(effect, control, literal);
1178 1179
    ReplaceWithValue(node, value, effect, control);
    return Replace(value);
1180 1181 1182 1183
  }
  return NoChange();
}

1184
Reduction JSCreateLowering::ReduceJSGetTemplateObject(Node* node) {
1185 1186
  JSGetTemplateObjectNode n(node);
  GetTemplateObjectParameters const& parameters = n.Parameters();
1187 1188 1189 1190 1191 1192 1193 1194 1195

  const ProcessedFeedback& feedback =
      broker()->GetFeedbackForTemplateObject(parameters.feedback());
  // TODO(v8:7790): Consider not generating JSGetTemplateObject operator
  // in the BytecodeGraphBuilder in the first place, if template_object is not
  // available.
  if (feedback.IsInsufficient()) return NoChange();

  JSArrayRef template_object = feedback.AsTemplateObject().value();
1196 1197 1198 1199 1200
  Node* value = jsgraph()->Constant(template_object);
  ReplaceWithValue(node, value);
  return Replace(value);
}

1201 1202
Reduction JSCreateLowering::ReduceJSCreateFunctionContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateFunctionContext, node->opcode());
1203 1204
  const CreateFunctionContextParameters& parameters =
      CreateFunctionContextParametersOf(node->op());
1205
  ScopeInfoRef scope_info(broker(), parameters.scope_info());
1206 1207
  int slot_count = parameters.slot_count();
  ScopeType scope_type = parameters.scope_type();
1208 1209 1210 1211 1212 1213 1214

  // Use inline allocation for function contexts up to a size limit.
  if (slot_count < kFunctionContextAllocationLimit) {
    // JSCreateFunctionContext[slot_count < limit]](fun)
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
    Node* context = NodeProperties::GetContextInput(node);
1215
    AllocationBuilder a(jsgraph(), effect, control);
1216
    STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 2);  // Ensure fully covered.
1217
    int context_length = slot_count + Context::MIN_CONTEXT_SLOTS;
1218 1219
    switch (scope_type) {
      case EVAL_SCOPE:
1220
        a.AllocateContext(context_length, native_context().eval_context_map());
1221 1222
        break;
      case FUNCTION_SCOPE:
1223 1224
        a.AllocateContext(context_length,
                          native_context().function_context_map());
1225 1226 1227 1228
        break;
      default:
        UNREACHABLE();
    }
1229 1230
    a.Store(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX),
            scope_info);
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
    for (int i = Context::MIN_CONTEXT_SLOTS; i < context_length; ++i) {
      a.Store(AccessBuilder::ForContextSlot(i), jsgraph()->UndefinedConstant());
    }
    RelaxControls(node);
    a.FinishAndChange(node);
    return Changed(node);
  }

  return NoChange();
}

Reduction JSCreateLowering::ReduceJSCreateWithContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateWithContext, node->opcode());
1245
  ScopeInfoRef scope_info(broker(), ScopeInfoOf(node->op()));
1246
  Node* extension = NodeProperties::GetValueInput(node, 0);
1247 1248 1249
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* context = NodeProperties::GetContextInput(node);
1250

1251
  AllocationBuilder a(jsgraph(), effect, control);
1252 1253 1254
  STATIC_ASSERT(Context::MIN_CONTEXT_EXTENDED_SLOTS ==
                3);  // Ensure fully covered.
  a.AllocateContext(Context::MIN_CONTEXT_EXTENDED_SLOTS,
1255
                    native_context().with_context_map());
1256
  a.Store(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX), scope_info);
1257
  a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
1258
  a.Store(AccessBuilder::ForContextSlot(Context::EXTENSION_INDEX), extension);
1259 1260 1261 1262 1263 1264 1265
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

Reduction JSCreateLowering::ReduceJSCreateCatchContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateCatchContext, node->opcode());
1266
  ScopeInfoRef scope_info(broker(), ScopeInfoOf(node->op()));
1267 1268 1269 1270
  Node* exception = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* context = NodeProperties::GetContextInput(node);
1271

1272
  AllocationBuilder a(jsgraph(), effect, control);
1273
  STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 2);  // Ensure fully covered.
1274
  a.AllocateContext(Context::MIN_CONTEXT_SLOTS + 1,
1275
                    native_context().catch_context_map());
1276
  a.Store(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX), scope_info);
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
  a.Store(AccessBuilder::ForContextSlot(Context::THROWN_OBJECT_INDEX),
          exception);
  RelaxControls(node);
  a.FinishAndChange(node);
  return Changed(node);
}

Reduction JSCreateLowering::ReduceJSCreateBlockContext(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateBlockContext, node->opcode());
1287
  ScopeInfoRef scope_info(broker(), ScopeInfoOf(node->op()));
1288
  int const context_length = scope_info.ContextLength();
1289 1290 1291 1292 1293 1294 1295

  // Use inline allocation for block contexts up to a size limit.
  if (context_length < kBlockContextAllocationLimit) {
    // JSCreateBlockContext[scope[length < limit]](fun)
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
    Node* context = NodeProperties::GetContextInput(node);
1296

1297
    AllocationBuilder a(jsgraph(), effect, control);
1298
    STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 2);  // Ensure fully covered.
1299
    a.AllocateContext(context_length, native_context().block_context_map());
1300 1301
    a.Store(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX),
            scope_info);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    a.Store(AccessBuilder::ForContextSlot(Context::PREVIOUS_INDEX), context);
    for (int i = Context::MIN_CONTEXT_SLOTS; i < context_length; ++i) {
      a.Store(AccessBuilder::ForContextSlot(i), jsgraph()->UndefinedConstant());
    }
    RelaxControls(node);
    a.FinishAndChange(node);
    return Changed(node);
  }

  return NoChange();
}

1314 1315 1316 1317
namespace {
base::Optional<MapRef> GetObjectCreateMap(JSHeapBroker* broker,
                                          HeapObjectRef prototype) {
  MapRef standard_map =
1318
      broker->target_native_context().object_function().initial_map();
1319 1320 1321
  if (prototype.equals(standard_map.prototype())) {
    return standard_map;
  }
1322
  if (prototype.map().oddball_type() == OddballType::kNull) {
1323 1324
    return broker->target_native_context()
        .slow_object_with_null_prototype_map();
1325 1326 1327 1328 1329 1330 1331 1332
  }
  if (prototype.IsJSObject()) {
    return prototype.AsJSObject().GetObjectCreateMap();
  }
  return base::Optional<MapRef>();
}
}  // namespace

1333 1334 1335 1336 1337
Reduction JSCreateLowering::ReduceJSCreateObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSCreateObject, node->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* prototype = NodeProperties::GetValueInput(node, 0);
1338 1339
  Type prototype_type = NodeProperties::GetType(prototype);
  if (!prototype_type.IsHeapConstant()) return NoChange();
1340

1341
  HeapObjectRef prototype_const = prototype_type.AsHeapConstant()->Ref();
1342
  auto maybe_instance_map = GetObjectCreateMap(broker(), prototype_const);
1343 1344
  if (!maybe_instance_map) return NoChange();
  MapRef instance_map = maybe_instance_map.value();
1345

1346
  Node* properties = jsgraph()->EmptyFixedArrayConstant();
1347
  if (instance_map.is_dictionary_map()) {
1348
    DCHECK_EQ(prototype_const.map().oddball_type(), OddballType::kNull);
1349
    // Allocate an empty NameDictionary as backing store for the properties.
1350
    MapRef map(broker(), factory()->name_dictionary_map());
1351 1352 1353
    int capacity =
        NameDictionary::ComputeCapacity(NameDictionary::kInitialCapacity);
    DCHECK(base::bits::IsPowerOfTwo(capacity));
1354
    int length = NameDictionary::EntryToIndex(InternalIndex(capacity));
1355 1356
    int size = NameDictionary::SizeFor(length);

1357
    AllocationBuilder a(jsgraph(), effect, control);
1358
    a.Allocate(size, AllocationType::kYoung, Type::Any());
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    a.Store(AccessBuilder::ForMap(), map);
    // Initialize FixedArray fields.
    a.Store(AccessBuilder::ForFixedArrayLength(),
            jsgraph()->SmiConstant(length));
    // Initialize HashTable fields.
    a.Store(AccessBuilder::ForHashTableBaseNumberOfElements(),
            jsgraph()->SmiConstant(0));
    a.Store(AccessBuilder::ForHashTableBaseNumberOfDeletedElement(),
            jsgraph()->SmiConstant(0));
    a.Store(AccessBuilder::ForHashTableBaseCapacity(),
            jsgraph()->SmiConstant(capacity));
    // Initialize Dictionary fields.
    a.Store(AccessBuilder::ForDictionaryNextEnumerationIndex(),
            jsgraph()->SmiConstant(PropertyDetails::kInitialIndex));
    a.Store(AccessBuilder::ForDictionaryObjectHashIndex(),
            jsgraph()->SmiConstant(PropertyArray::kNoHashSentinel));
    // Initialize the Properties fields.
    Node* undefined = jsgraph()->UndefinedConstant();
    STATIC_ASSERT(NameDictionary::kElementsStartIndex ==
                  NameDictionary::kObjectHashIndex + 1);
    for (int index = NameDictionary::kElementsStartIndex; index < length;
         index++) {
      a.Store(AccessBuilder::ForFixedArraySlot(index, kNoWriteBarrier),
              undefined);
    }
    properties = effect = a.Finish();
  }

1387
  int const instance_size = instance_map.instance_size();
1388
  if (instance_size > kMaxRegularHeapObjectSize) return NoChange();
1389
  CHECK(!instance_map.IsInobjectSlackTrackingInProgress());
1390 1391 1392

  // Emit code to allocate the JSObject instance for the given
  // {instance_map}.
1393
  AllocationBuilder a(jsgraph(), effect, control);
1394
  a.Allocate(instance_size, AllocationType::kYoung, Type::Any());
1395 1396 1397 1398 1399 1400 1401
  a.Store(AccessBuilder::ForMap(), instance_map);
  a.Store(AccessBuilder::ForJSObjectPropertiesOrHash(), properties);
  a.Store(AccessBuilder::ForJSObjectElements(),
          jsgraph()->EmptyFixedArrayConstant());
  // Initialize Object fields.
  Node* undefined = jsgraph()->UndefinedConstant();
  for (int offset = JSObject::kHeaderSize; offset < instance_size;
1402
       offset += kTaggedSize) {
1403 1404 1405 1406 1407 1408 1409 1410 1411
    a.Store(AccessBuilder::ForJSObjectOffset(offset, kNoWriteBarrier),
            undefined);
  }
  Node* value = effect = a.Finish();

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

1412 1413 1414
// Helper that allocates a FixedArray holding argument values recorded in the
// given {frame_state}. Serves as backing store for JSCreateArguments nodes.
Node* JSCreateLowering::AllocateArguments(Node* effect, Node* control,
1415 1416
                                          FrameState frame_state) {
  FrameStateInfo state_info = frame_state.frame_state_info();
1417 1418 1419 1420
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  if (argument_count == 0) return jsgraph()->EmptyFixedArrayConstant();

  // Prepare an iterator over argument values recorded in the frame state.
1421
  Node* const parameters = frame_state.parameters();
1422
  StateValuesAccess parameters_access(parameters);
1423
  auto parameters_it = parameters_access.begin_without_receiver();
1424 1425

  // Actually allocate the backing store.
1426
  AllocationBuilder a(jsgraph(), effect, control);
1427 1428
  a.AllocateArray(argument_count,
                  MapRef(broker(), factory()->fixed_array_map()));
1429
  for (int i = 0; i < argument_count; ++i, ++parameters_it) {
1430
    DCHECK_NOT_NULL(parameters_it.node());
1431
    a.Store(AccessBuilder::ForFixedArrayElement(), jsgraph()->Constant(i),
1432
            parameters_it.node());
1433 1434 1435 1436 1437 1438 1439
  }
  return a.Finish();
}

// Helper that allocates a FixedArray holding argument values recorded in the
// given {frame_state}. Serves as backing store for JSCreateArguments nodes.
Node* JSCreateLowering::AllocateRestArguments(Node* effect, Node* control,
1440
                                              FrameState frame_state,
1441
                                              int start_index) {
1442
  FrameStateInfo state_info = frame_state.frame_state_info();
1443 1444 1445 1446 1447
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  int num_elements = std::max(0, argument_count - start_index);
  if (num_elements == 0) return jsgraph()->EmptyFixedArrayConstant();

  // Prepare an iterator over argument values recorded in the frame state.
1448
  Node* const parameters = frame_state.parameters();
1449
  StateValuesAccess parameters_access(parameters);
1450 1451
  auto parameters_it =
      parameters_access.begin_without_receiver_and_skip(start_index);
1452 1453

  // Actually allocate the backing store.
1454
  AllocationBuilder a(jsgraph(), effect, control);
1455
  a.AllocateArray(num_elements, MapRef(broker(), factory()->fixed_array_map()));
1456
  for (int i = 0; i < num_elements; ++i, ++parameters_it) {
1457
    DCHECK_NOT_NULL(parameters_it.node());
1458
    a.Store(AccessBuilder::ForFixedArrayElement(), jsgraph()->Constant(i),
1459
            parameters_it.node());
1460 1461 1462 1463 1464 1465 1466 1467
  }
  return a.Finish();
}

// Helper that allocates a FixedArray serving as a parameter map for values
// recorded in the given {frame_state}. Some elements map to slots within the
// given {context}. Serves as backing store for JSCreateArguments nodes.
Node* JSCreateLowering::AllocateAliasedArguments(
1468
    Node* effect, Node* control, FrameState frame_state, Node* context,
1469
    const SharedFunctionInfoRef& shared, bool* has_aliased_arguments) {
1470
  FrameStateInfo state_info = frame_state.frame_state_info();
1471 1472 1473 1474 1475
  int argument_count = state_info.parameter_count() - 1;  // Minus receiver.
  if (argument_count == 0) return jsgraph()->EmptyFixedArrayConstant();

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

  // Calculate number of argument values being aliased/mapped.
1482
  int mapped_count = std::min(argument_count, parameter_count);
1483 1484 1485
  *has_aliased_arguments = true;

  // Prepare an iterator over argument values recorded in the frame state.
1486
  Node* const parameters = frame_state.parameters();
1487
  StateValuesAccess parameters_access(parameters);
1488 1489
  auto parameters_it =
      parameters_access.begin_without_receiver_and_skip(mapped_count);
1490 1491 1492 1493

  // The unmapped argument values recorded in the frame state are stored yet
  // another indirection away and then linked into the parameter map below,
  // whereas mapped argument values are replaced with a hole instead.
1494
  AllocationBuilder aa(jsgraph(), effect, control);
1495 1496
  aa.AllocateArray(argument_count,
                   MapRef(broker(), factory()->fixed_array_map()));
1497
  for (int i = 0; i < mapped_count; ++i) {
1498 1499
    aa.Store(AccessBuilder::ForFixedArrayElement(), jsgraph()->Constant(i),
             jsgraph()->TheHoleConstant());
1500
  }
1501
  for (int i = mapped_count; i < argument_count; ++i, ++parameters_it) {
1502
    DCHECK_NOT_NULL(parameters_it.node());
1503
    aa.Store(AccessBuilder::ForFixedArrayElement(), jsgraph()->Constant(i),
1504
             parameters_it.node());
1505 1506 1507 1508
  }
  Node* arguments = aa.Finish();

  // Actually allocate the backing store.
1509
  AllocationBuilder a(jsgraph(), arguments, control);
1510 1511 1512 1513 1514
  a.AllocateSloppyArgumentElements(
      mapped_count,
      MapRef(broker(), factory()->sloppy_arguments_elements_map()));
  a.Store(AccessBuilder::ForSloppyArgumentsElementsContext(), context);
  a.Store(AccessBuilder::ForSloppyArgumentsElementsArguments(), arguments);
1515
  for (int i = 0; i < mapped_count; ++i) {
1516
    int idx = shared.context_header_size() + parameter_count - 1 - i;
1517 1518
    a.Store(AccessBuilder::ForSloppyArgumentsElementsMappedEntry(),
            jsgraph()->Constant(i), jsgraph()->Constant(idx));
1519 1520 1521 1522
  }
  return a.Finish();
}

1523 1524 1525 1526 1527
// Helper that allocates a FixedArray serving as a parameter map for values
// unknown at compile-time, the true {arguments_length} and {arguments_frame}
// values can only be determined dynamically at run-time and are provided.
// Serves as backing store for JSCreateArguments nodes.
Node* JSCreateLowering::AllocateAliasedArguments(
1528 1529
    Node* effect, Node* control, Node* context, Node* arguments_length,
    const SharedFunctionInfoRef& shared, bool* has_aliased_arguments) {
1530 1531
  // If there is no aliasing, the arguments object elements are not
  // special in any way, we can just return an unmapped backing store.
1532
  int parameter_count = shared.internal_formal_parameter_count();
1533
  if (parameter_count == 0) {
1534 1535 1536
    return graph()->NewNode(
        simplified()->NewArgumentsElements(
            CreateArgumentsType::kUnmappedArguments, parameter_count),
1537
        arguments_length, effect);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  }

  // From here on we are going to allocate a mapped (aka. aliased) elements
  // backing store. We do not statically know how many arguments exist, but
  // dynamically selecting the hole for some of the "mapped" elements allows
  // using a static shape for the parameter map.
  int mapped_count = parameter_count;
  *has_aliased_arguments = true;

  // The unmapped argument values are stored yet another indirection away and
  // then linked into the parameter map below, whereas mapped argument values
  // (i.e. the first {mapped_count} elements) are replaced with a hole instead.
1550
  Node* arguments = effect =
1551 1552
      graph()->NewNode(simplified()->NewArgumentsElements(
                           CreateArgumentsType::kMappedArguments, mapped_count),
1553
                       arguments_length, effect);
1554 1555

  // Actually allocate the backing store.
1556
  AllocationBuilder a(jsgraph(), effect, control);
1557 1558 1559 1560 1561
  a.AllocateSloppyArgumentElements(
      mapped_count,
      MapRef(broker(), factory()->sloppy_arguments_elements_map()));
  a.Store(AccessBuilder::ForSloppyArgumentsElementsContext(), context);
  a.Store(AccessBuilder::ForSloppyArgumentsElementsArguments(), arguments);
1562
  for (int i = 0; i < mapped_count; ++i) {
1563
    int idx = shared.context_header_size() + parameter_count - 1 - i;
1564 1565 1566 1567
    Node* value = graph()->NewNode(
        common()->Select(MachineRepresentation::kTagged),
        graph()->NewNode(simplified()->NumberLessThan(), jsgraph()->Constant(i),
                         arguments_length),
1568
        jsgraph()->Constant(idx), jsgraph()->TheHoleConstant());
1569 1570
    a.Store(AccessBuilder::ForSloppyArgumentsElementsMappedEntry(),
            jsgraph()->Constant(i), value);
1571 1572 1573 1574
  }
  return a.Finish();
}

1575 1576 1577
Node* JSCreateLowering::AllocateElements(Node* effect, Node* control,
                                         ElementsKind elements_kind,
                                         int capacity,
1578
                                         AllocationType allocation) {
1579 1580 1581
  DCHECK_LE(1, capacity);
  DCHECK_LE(capacity, JSArray::kInitialMaxFastElementArray);

1582
  Handle<Map> elements_map = IsDoubleElementsKind(elements_kind)
1583 1584
                                 ? factory()->fixed_double_array_map()
                                 : factory()->fixed_array_map();
1585
  ElementAccess access = IsDoubleElementsKind(elements_kind)
1586 1587
                             ? AccessBuilder::ForFixedDoubleArrayElement()
                             : AccessBuilder::ForFixedArrayElement();
1588
  Node* value = jsgraph()->TheHoleConstant();
1589 1590

  // Actually allocate the backing store.
1591
  AllocationBuilder a(jsgraph(), effect, control);
1592
  a.AllocateArray(capacity, MapRef(broker(), elements_map), allocation);
1593 1594 1595 1596 1597 1598 1599
  for (int i = 0; i < capacity; ++i) {
    Node* index = jsgraph()->Constant(i);
    a.Store(access, index, value);
  }
  return a.Finish();
}

1600 1601 1602
Node* JSCreateLowering::AllocateElements(Node* effect, Node* control,
                                         ElementsKind elements_kind,
                                         std::vector<Node*> const& values,
1603
                                         AllocationType allocation) {
1604 1605 1606 1607
  int const capacity = static_cast<int>(values.size());
  DCHECK_LE(1, capacity);
  DCHECK_LE(capacity, JSArray::kInitialMaxFastElementArray);

1608
  Handle<Map> elements_map = IsDoubleElementsKind(elements_kind)
1609 1610
                                 ? factory()->fixed_double_array_map()
                                 : factory()->fixed_array_map();
1611
  ElementAccess access = IsDoubleElementsKind(elements_kind)
1612 1613 1614 1615
                             ? AccessBuilder::ForFixedDoubleArrayElement()
                             : AccessBuilder::ForFixedArrayElement();

  // Actually allocate the backing store.
1616
  AllocationBuilder a(jsgraph(), effect, control);
1617
  a.AllocateArray(capacity, MapRef(broker(), elements_map), allocation);
1618 1619 1620 1621 1622 1623 1624
  for (int i = 0; i < capacity; ++i) {
    Node* index = jsgraph()->Constant(i);
    a.Store(access, index, values[i]);
  }
  return a.Finish();
}

1625
Node* JSCreateLowering::AllocateFastLiteral(Node* effect, Node* control,
1626
                                            JSObjectRef boilerplate,
1627
                                            AllocationType allocation) {
1628
  // Compute the in-object properties to store first (might have effects).
1629
  MapRef boilerplate_map = boilerplate.map();
1630
  ZoneVector<std::pair<FieldAccess, Node*>> inobject_fields(zone());
1631 1632
  inobject_fields.reserve(boilerplate_map.GetInObjectProperties());
  int const boilerplate_nof = boilerplate_map.NumberOfOwnDescriptors();
1633
  for (InternalIndex i : InternalIndex::Range(boilerplate_nof)) {
1634
    PropertyDetails const property_details =
1635
        boilerplate_map.GetPropertyDetails(i);
1636 1637
    if (property_details.location() != kField) continue;
    DCHECK_EQ(kData, property_details.kind());
1638
    NameRef property_name = boilerplate_map.GetPropertyKey(i);
1639
    FieldIndex index = boilerplate_map.GetFieldIndexFor(i);
1640
    ConstFieldInfo const_field_info(boilerplate_map.object());
1641 1642 1643 1644 1645
    FieldAccess access = {kTaggedBase,
                          index.offset(),
                          property_name.object(),
                          MaybeHandle<Map>(),
                          Type::Any(),
1646
                          MachineType::AnyTagged(),
1647 1648
                          kFullWriteBarrier,
                          LoadSensitivity::kUnsafe,
1649
                          const_field_info};
1650
    Node* value;
1651
    if (boilerplate_map.IsUnboxedDoubleField(i)) {
1652 1653
      access.machine_type = MachineType::Float64();
      access.type = Type::Number();
1654
      uint64_t value_bits = boilerplate.RawFastDoublePropertyAsBitsAt(index);
1655
      if (value_bits == kHoleNanInt64) {
1656 1657 1658 1659 1660 1661
        // This special case is analogous to is_uninitialized being true in the
        // non-unboxed-double case below. The store of the hole NaN value here
        // will always be followed by another store that actually initializes
        // the field. The hole NaN should therefore be unobservable.
        // Load elimination expects there to be at most one const store to any
        // given field, so we always mark the unobservable ones as mutable.
1662
        access.const_field_info = ConstFieldInfo::None();
1663 1664
      }
      value = jsgraph()->Constant(bit_cast<double>(value_bits));
1665
    } else {
1666
      ObjectRef boilerplate_value = boilerplate.RawFastPropertyAt(index);
1667 1668 1669 1670 1671
      bool is_uninitialized =
          boilerplate_value.IsHeapObject() &&
          boilerplate_value.AsHeapObject().map().oddball_type() ==
              OddballType::kUninitialized;
      if (is_uninitialized) {
1672
        access.const_field_info = ConstFieldInfo::None();
1673
      }
1674 1675
      if (boilerplate_value.IsJSObject()) {
        JSObjectRef boilerplate_object = boilerplate_value.AsJSObject();
1676 1677
        value = effect = AllocateFastLiteral(effect, control,
                                             boilerplate_object, allocation);
1678
      } else if (property_details.representation().IsDouble()) {
1679
        double number = boilerplate_value.AsHeapNumber().value();
1680
        // Allocate a mutable HeapNumber box and store the value into it.
1681
        AllocationBuilder builder(jsgraph(), effect, control);
1682
        builder.Allocate(HeapNumber::kSize, allocation);
1683 1684
        builder.Store(AccessBuilder::ForMap(),
                      MapRef(broker(), factory()->heap_number_map()));
1685 1686 1687
        builder.Store(AccessBuilder::ForHeapNumberValue(),
                      jsgraph()->Constant(number));
        value = effect = builder.Finish();
1688 1689
      } else if (property_details.representation().IsSmi()) {
        // Ensure that value is stored as smi.
1690
        value = is_uninitialized
1691
                    ? jsgraph()->ZeroConstant()
1692
                    : jsgraph()->Constant(boilerplate_value.AsSmi());
1693
      } else {
1694
        value = jsgraph()->Constant(boilerplate_value);
1695 1696 1697 1698 1699 1700
      }
    }
    inobject_fields.push_back(std::make_pair(access, value));
  }

  // Fill slack at the end of the boilerplate object with filler maps.
1701
  int const boilerplate_length = boilerplate_map.GetInObjectProperties();
1702 1703
  for (int index = static_cast<int>(inobject_fields.size());
       index < boilerplate_length; ++index) {
1704 1705
    FieldAccess access =
        AccessBuilder::ForJSObjectInObjectProperty(boilerplate_map, index);
1706 1707 1708 1709
    Node* value = jsgraph()->HeapConstant(factory()->one_pointer_filler_map());
    inobject_fields.push_back(std::make_pair(access, value));
  }

1710
  // Setup the elements backing store.
1711
  Node* elements =
1712
      AllocateFastLiteralElements(effect, control, boilerplate, allocation);
1713 1714
  if (elements->op()->EffectOutputCount() > 0) effect = elements;

1715
  // Actually allocate and initialize the object.
1716
  AllocationBuilder builder(jsgraph(), effect, control);
1717
  builder.Allocate(boilerplate_map.instance_size(), allocation,
1718
                   Type::For(boilerplate_map));
1719
  builder.Store(AccessBuilder::ForMap(), boilerplate_map);
1720 1721
  builder.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
                jsgraph()->EmptyFixedArrayConstant());
1722
  builder.Store(AccessBuilder::ForJSObjectElements(), elements);
1723
  if (boilerplate.IsJSArray()) {
1724
    JSArrayRef boilerplate_array = boilerplate.AsJSArray();
1725
    builder.Store(
1726
        AccessBuilder::ForJSArrayLength(boilerplate_array.GetElementsKind()),
1727
        boilerplate_array.length());
1728
  }
1729
  for (auto const& inobject_field : inobject_fields) {
1730 1731 1732 1733 1734
    builder.Store(inobject_field.first, inobject_field.second);
  }
  return builder.Finish();
}

1735 1736
Node* JSCreateLowering::AllocateFastLiteralElements(Node* effect, Node* control,
                                                    JSObjectRef boilerplate,
1737
                                                    AllocationType allocation) {
1738
  FixedArrayBaseRef boilerplate_elements = boilerplate.elements();
1739 1740

  // Empty or copy-on-write elements just store a constant.
1741
  int const elements_length = boilerplate_elements.length();
1742 1743
  MapRef elements_map = boilerplate_elements.map();
  if (boilerplate_elements.length() == 0 || elements_map.IsFixedCowArrayMap()) {
1744
    if (allocation == AllocationType::kOld) {
1745 1746
      boilerplate.EnsureElementsTenured();
      boilerplate_elements = boilerplate.elements();
1747
    }
1748
    return jsgraph()->HeapConstant(boilerplate_elements.object());
1749 1750 1751 1752
  }

  // Compute the elements to store first (might have effects).
  ZoneVector<Node*> elements_values(elements_length, zone());
1753 1754
  if (elements_map.instance_type() == FIXED_DOUBLE_ARRAY_TYPE) {
    FixedDoubleArrayRef elements = boilerplate_elements.AsFixedDoubleArray();
1755
    for (int i = 0; i < elements_length; ++i) {
1756 1757
      Float64 value = elements.get(i);
      if (value.is_hole_nan()) {
1758
        elements_values[i] = jsgraph()->TheHoleConstant();
1759
      } else {
1760
        elements_values[i] = jsgraph()->Constant(value.get_scalar());
1761 1762 1763
      }
    }
  } else {
1764
    FixedArrayRef elements = boilerplate_elements.AsFixedArray();
1765
    for (int i = 0; i < elements_length; ++i) {
1766 1767 1768
      ObjectRef element_value = elements.get(i);
      if (element_value.IsJSObject()) {
        elements_values[i] = effect = AllocateFastLiteral(
1769
            effect, control, element_value.AsJSObject(), allocation);
1770
      } else {
1771
        elements_values[i] = jsgraph()->Constant(element_value);
1772 1773 1774 1775 1776
      }
    }
  }

  // Allocate the backing store array and store the elements.
1777
  AllocationBuilder builder(jsgraph(), effect, control);
1778
  builder.AllocateArray(elements_length, elements_map, allocation);
1779
  ElementAccess const access =
1780
      (elements_map.instance_type() == FIXED_DOUBLE_ARRAY_TYPE)
1781 1782 1783 1784 1785 1786 1787 1788
          ? AccessBuilder::ForFixedDoubleArrayElement()
          : AccessBuilder::ForFixedArrayElement();
  for (int i = 0; i < elements_length; ++i) {
    builder.Store(access, jsgraph()->Constant(i), elements_values[i]);
  }
  return builder.Finish();
}

1789 1790 1791
Node* JSCreateLowering::AllocateLiteralRegExp(
    Node* effect, Node* control, RegExpBoilerplateDescriptionRef boilerplate) {
  MapRef initial_map = native_context().regexp_function().initial_map();
1792 1793

  // Sanity check that JSRegExp object layout hasn't changed.
1794
  STATIC_ASSERT(JSRegExp::kDataOffset == JSObject::kHeaderSize);
1795
  STATIC_ASSERT(JSRegExp::kSourceOffset == JSRegExp::kDataOffset + kTaggedSize);
1796
  STATIC_ASSERT(JSRegExp::kFlagsOffset ==
1797
                JSRegExp::kSourceOffset + kTaggedSize);
1798 1799
  STATIC_ASSERT(JSRegExp::kHeaderSize == JSRegExp::kFlagsOffset + kTaggedSize);
  STATIC_ASSERT(JSRegExp::kLastIndexOffset == JSRegExp::kHeaderSize);
1800
  DCHECK_EQ(JSRegExp::Size(), JSRegExp::kLastIndexOffset + kTaggedSize);
1801

1802
  AllocationBuilder builder(jsgraph(), effect, control);
1803 1804 1805
  builder.Allocate(JSRegExp::Size(), AllocationType::kYoung,
                   Type::For(initial_map));
  builder.Store(AccessBuilder::ForMap(), initial_map);
1806
  builder.Store(AccessBuilder::ForJSObjectPropertiesOrHash(),
1807 1808 1809
                jsgraph()->EmptyFixedArrayConstant());
  builder.Store(AccessBuilder::ForJSObjectElements(),
                jsgraph()->EmptyFixedArrayConstant());
1810 1811 1812

  builder.Store(AccessBuilder::ForJSRegExpData(), boilerplate.data());
  builder.Store(AccessBuilder::ForJSRegExpSource(), boilerplate.source());
1813 1814
  builder.Store(AccessBuilder::ForJSRegExpFlags(),
                jsgraph()->SmiConstant(boilerplate.flags()));
1815
  builder.Store(AccessBuilder::ForJSRegExpLastIndex(),
1816
                jsgraph()->SmiConstant(JSRegExp::kInitialLastIndexValue));
1817 1818 1819 1820

  return builder.Finish();
}

1821 1822 1823
Factory* JSCreateLowering::factory() const {
  return jsgraph()->isolate()->factory();
}
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834

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

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

SimplifiedOperatorBuilder* JSCreateLowering::simplified() const {
  return jsgraph()->simplified();
}

1835
NativeContextRef JSCreateLowering::native_context() const {
1836
  return broker()->target_native_context();
1837 1838
}

1839 1840 1841
}  // namespace compiler
}  // namespace internal
}  // namespace v8