map.h 45 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_OBJECTS_MAP_H_
#define V8_OBJECTS_MAP_H_

8
#include "src/base/bit-field.h"
9
#include "src/common/globals.h"
10
#include "src/objects/code.h"
11
#include "src/objects/heap-object.h"
12
#include "src/objects/internal-index.h"
13
#include "src/objects/objects.h"
14 15
#include "torque-generated/bit-fields.h"
#include "torque-generated/field-offsets.h"
16 17 18 19 20 21 22

// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"

namespace v8 {
namespace internal {

23 24
class WasmTypeInfo;

25 26
enum InstanceType : uint16_t;

27 28 29
#define DATA_ONLY_VISITOR_ID_LIST(V) \
  V(BigInt)                          \
  V(ByteArray)                       \
30
  V(CoverageInfo)                    \
31
  V(DataObject)                      \
32
  V(FeedbackMetadata)                \
33
  V(FixedDoubleArray)
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#define POINTER_VISITOR_ID_LIST(V)      \
  V(AllocationSite)                     \
  V(BytecodeArray)                      \
  V(Cell)                               \
  V(Code)                               \
  V(CodeDataContainer)                  \
  V(DataHandler)                        \
  V(EmbedderDataArray)                  \
  V(EphemeronHashTable)                 \
  V(FeedbackCell)                       \
  V(FreeSpace)                          \
  V(JSApiObject)                        \
  V(JSArrayBuffer)                      \
  V(JSDataView)                         \
  V(JSFunction)                         \
  V(JSObject)                           \
  V(JSObjectFast)                       \
  V(JSTypedArray)                       \
  V(JSWeakRef)                          \
  V(JSWeakCollection)                   \
  V(Map)                                \
  V(NativeContext)                      \
  V(PreparseData)                       \
  V(PropertyArray)                      \
  V(PropertyCell)                       \
  V(PrototypeInfo)                      \
  V(ShortcutCandidate)                  \
  V(SmallOrderedHashMap)                \
  V(SmallOrderedHashSet)                \
  V(SmallOrderedNameDictionary)         \
  V(SourceTextModule)                   \
  V(Struct)                             \
  V(SwissNameDictionary)                \
  V(Symbol)                             \
  V(SyntheticModule)                    \
  V(TransitionArray)                    \
71
  IF_WASM(V, WasmArray)                 \
72
  IF_WASM(V, WasmCapiFunctionData)      \
73 74
  IF_WASM(V, WasmExportedFunctionData)  \
  IF_WASM(V, WasmFunctionData)          \
75 76
  IF_WASM(V, WasmIndirectFunctionTable) \
  IF_WASM(V, WasmInstanceObject)        \
77
  IF_WASM(V, WasmJSFunctionData)        \
78 79
  IF_WASM(V, WasmStruct)                \
  IF_WASM(V, WasmTypeInfo)              \
80
  V(WeakCell)
81

82 83 84
#define TORQUE_VISITOR_ID_LIST(V)     \
  TORQUE_DATA_ONLY_VISITOR_ID_LIST(V) \
  TORQUE_POINTER_VISITOR_ID_LIST(V)
85

86 87 88 89
// Objects with the same visitor id are processed in the same way by
// the heap visitors. The visitor ids for data only objects must precede
// other visitor ids. We rely on kDataOnlyVisitorIdCount for quick check
// of whether an object contains only data or may contain pointers.
90 91
enum VisitorId {
#define VISITOR_ID_ENUM_DECL(id) kVisit##id,
92 93 94
  DATA_ONLY_VISITOR_ID_LIST(VISITOR_ID_ENUM_DECL)
      TORQUE_DATA_ONLY_VISITOR_ID_LIST(VISITOR_ID_ENUM_DECL)
          kDataOnlyVisitorIdCount,
95
  POINTER_VISITOR_ID_LIST(VISITOR_ID_ENUM_DECL)
96
      TORQUE_POINTER_VISITOR_ID_LIST(VISITOR_ID_ENUM_DECL)
97
#undef VISITOR_ID_ENUM_DECL
98
          kVisitorIdCount
99 100
};

101 102 103 104 105
enum class ObjectFields {
  kDataOnly,
  kMaybePointers,
};

106
using MapHandles = std::vector<Handle<Map>>;
107

108 109
#include "torque-generated/src/objects/map-tq.inc"

110 111 112 113
// All heap objects have a Map that describes their structure.
//  A Map contains information about:
//  - Size information about the object
//  - How to iterate over an object (for garbage collection)
114 115
//
// Map layout:
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
// +---------------+-------------------------------------------------+
// |   _ Type _    | _ Description _                                 |
// +---------------+-------------------------------------------------+
// | TaggedPointer | map - Always a pointer to the MetaMap root      |
// +---------------+-------------------------------------------------+
// | Int           | The first int field                             |
//  `---+----------+-------------------------------------------------+
//      | Byte     | [instance_size]                                 |
//      +----------+-------------------------------------------------+
//      | Byte     | If Map for a primitive type:                    |
//      |          |   native context index for constructor fn       |
//      |          | If Map for an Object type:                      |
//      |          |   inobject properties start offset in words     |
//      +----------+-------------------------------------------------+
//      | Byte     | [used_or_unused_instance_size_in_words]         |
//      |          | For JSObject in fast mode this byte encodes     |
//      |          | the size of the object that includes only       |
//      |          | the used property fields or the slack size      |
//      |          | in properties backing store.                    |
//      +----------+-------------------------------------------------+
//      | Byte     | [visitor_id]                                    |
// +----+----------+-------------------------------------------------+
// | Int           | The second int field                            |
//  `---+----------+-------------------------------------------------+
//      | Short    | [instance_type]                                 |
//      +----------+-------------------------------------------------+
//      | Byte     | [bit_field]                                     |
//      |          |   - has_non_instance_prototype (bit 0)          |
//      |          |   - is_callable (bit 1)                         |
//      |          |   - has_named_interceptor (bit 2)               |
//      |          |   - has_indexed_interceptor (bit 3)             |
//      |          |   - is_undetectable (bit 4)                     |
//      |          |   - is_access_check_needed (bit 5)              |
//      |          |   - is_constructor (bit 6)                      |
//      |          |   - has_prototype_slot (bit 7)                  |
//      +----------+-------------------------------------------------+
//      | Byte     | [bit_field2]                                    |
//      |          |   - new_target_is_base (bit 0)                  |
//      |          |   - is_immutable_proto (bit 1)                  |
155
//      |          |   - elements_kind (bits 2..7)                   |
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
// +----+----------+-------------------------------------------------+
// | Int           | [bit_field3]                                    |
// |               |   - enum_length (bit 0..9)                      |
// |               |   - number_of_own_descriptors (bit 10..19)      |
// |               |   - is_prototype_map (bit 20)                   |
// |               |   - is_dictionary_map (bit 21)                  |
// |               |   - owns_descriptors (bit 22)                   |
// |               |   - is_in_retained_map_list (bit 23)            |
// |               |   - is_deprecated (bit 24)                      |
// |               |   - is_unstable (bit 25)                        |
// |               |   - is_migration_target (bit 26)                |
// |               |   - is_extensible (bit 28)                      |
// |               |   - may_have_interesting_symbols (bit 28)       |
// |               |   - construction_counter (bit 29..31)           |
// |               |                                                 |
// +*****************************************************************+
// | Int           | On systems with 64bit pointer types, there      |
// |               | is an unused 32bits after bit_field3            |
// +*****************************************************************+
// | TaggedPointer | [prototype]                                     |
// +---------------+-------------------------------------------------+
// | TaggedPointer | [constructor_or_back_pointer_or_native_context] |
// +---------------+-------------------------------------------------+
// | TaggedPointer | [instance_descriptors]                          |
// +*****************************************************************+
// | TaggedPointer | [dependent_code]                                |
// +---------------+-------------------------------------------------+
// | TaggedPointer | [prototype_validity_cell]                       |
// +---------------+-------------------------------------------------+
// | TaggedPointer | If Map is a prototype map:                      |
// |               |   [prototype_info]                              |
// |               | Else:                                           |
// |               |   [raw_transitions]                             |
// +---------------+-------------------------------------------------+
190

191
class Map : public TorqueGeneratedMap<Map, HeapObject> {
192 193 194 195
 public:
  // Instance size.
  // Size in bytes or kVariableSizeSentinel if instances do not have
  // a fixed size.
196
  DECL_INT_ACCESSORS(instance_size)
197 198 199
  // Size in words or kVariableSizeSentinel if instances do not have
  // a fixed size.
  DECL_INT_ACCESSORS(instance_size_in_words)
200

201 202 203 204
  // [inobject_properties_start_or_constructor_function_index]:
  // Provides access to the inobject properties start offset in words in case of
  // JSObject maps, or the constructor function index in case of primitive maps.
  DECL_INT_ACCESSORS(inobject_properties_start_or_constructor_function_index)
205

206 207 208
  // Get/set the in-object property area start offset in words in the object.
  inline int GetInObjectPropertiesStartInWords() const;
  inline void SetInObjectPropertiesStartInWords(int value);
209
  // Count of properties allocated in the object (JSObject only).
210
  inline int GetInObjectProperties() const;
211 212 213 214
  // Index of the constructor function in the native context (primitives only),
  // or the special sentinel value to indicate that there is no object wrapper
  // for the primitive (i.e. in case of null or undefined).
  static const int kNoConstructorFunctionIndex = 0;
215
  inline int GetConstructorFunctionIndex() const;
216
  inline void SetConstructorFunctionIndex(int value);
217 218
  static base::Optional<JSFunction> GetConstructorFunction(
      Map map, Context native_context);
219 220

  // Retrieve interceptors.
221 222
  DECL_GETTER(GetNamedInterceptor, InterceptorInfo)
  DECL_GETTER(GetIndexedInterceptor, InterceptorInfo)
223 224

  // Instance type.
225
  DECL_PRIMITIVE_ACCESSORS(instance_type, InstanceType)
226

227 228 229
  // Returns the size of the used in-object area including object header
  // (only used for JSObject in fast mode, for the other kinds of objects it
  // is equal to the instance size).
230
  inline int UsedInstanceSize() const;
231

232 233
  // Tells how many unused property fields (in-object or out-of object) are
  // available in the instance (only used for JSObject in fast mode).
234
  inline int UnusedPropertyFields() const;
235 236
  // Tells how many unused in-object property words are present.
  inline int UnusedInObjectProperties() const;
237 238 239 240
  // Updates the counters tracking unused fields in the object.
  inline void SetInObjectUnusedPropertyFields(int unused_property_fields);
  // Updates the counters tracking unused fields in the property array.
  inline void SetOutOfObjectUnusedPropertyFields(int unused_property_fields);
241 242
  inline void CopyUnusedPropertyFields(Map map);
  inline void CopyUnusedPropertyFieldsAdjustedForInstanceSize(Map map);
243 244 245 246
  inline void AccountAddedPropertyField();
  inline void AccountAddedOutOfObjectPropertyField(
      int unused_in_property_array);

247
  //
248
  // Bit field.
249
  //
250 251 252 253
  // The setter in this pair calls the relaxed setter if concurrent marking is
  // on, or performs the write non-atomically if it's off. The read is always
  // non-atomically. This is done to have wider TSAN coverage on the cases where
  // it's possible.
254
  DECL_PRIMITIVE_ACCESSORS(bit_field, byte)
255

256 257
  // Atomic accessors, used for allowlisting legitimate concurrent accesses.
  DECL_PRIMITIVE_ACCESSORS(relaxed_bit_field, byte)
258

259
  // Bit positions for |bit_field|.
260 261 262
  struct Bits1 {
    DEFINE_TORQUE_GENERATED_MAP_BIT_FIELDS1()
  };
263

264
  //
265
  // Bit field 2.
266 267
  //
  DECL_PRIMITIVE_ACCESSORS(bit_field2, byte)
268

269
  // Bit positions for |bit_field2|.
270 271 272
  struct Bits2 {
    DEFINE_TORQUE_GENERATED_MAP_BIT_FIELDS2()
  };
273 274

  //
275
  // Bit field 3.
276
  //
277 278 279
  // {bit_field3} calls the relaxed accessors if concurrent marking is on, or
  // performs the read/write non-atomically if it's off. This is done to have
  // wider TSAN coverage on the cases where it's possible.
280
  DECL_PRIMITIVE_ACCESSORS(bit_field3, uint32_t)
281

282 283
  DECL_PRIMITIVE_ACCESSORS(relaxed_bit_field3, uint32_t)
  DECL_PRIMITIVE_ACCESSORS(release_acquire_bit_field3, uint32_t)
284

285 286 287 288
  // Clear uninitialized padding space. This ensures that the snapshot content
  // is deterministic. Depending on the V8 build mode there could be no padding.
  V8_INLINE void clear_padding();

289
  // Bit positions for |bit_field3|.
290 291 292
  struct Bits3 {
    DEFINE_TORQUE_GENERATED_MAP_BIT_FIELDS3()
  };
293

294 295 296 297
  // Ensure that Torque-defined bit widths for |bit_field3| are as expected.
  STATIC_ASSERT(Bits3::EnumLengthBits::kSize == kDescriptorIndexBitCount);
  STATIC_ASSERT(Bits3::NumberOfOwnDescriptorsBits::kSize ==
                kDescriptorIndexBitCount);
298

299 300
  STATIC_ASSERT(Bits3::NumberOfOwnDescriptorsBits::kMax >=
                kMaxNumberOfDescriptors);
301

302 303 304
  static const int kSlackTrackingCounterStart = 7;
  static const int kSlackTrackingCounterEnd = 1;
  static const int kNoSlackTracking = 0;
305 306
  STATIC_ASSERT(kSlackTrackingCounterStart <=
                Bits3::ConstructionCounterBits::kMax);
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

  // Inobject slack tracking is the way to reclaim unused inobject space.
  //
  // The instance size is initially determined by adding some slack to
  // expected_nof_properties (to allow for a few extra properties added
  // after the constructor). There is no guarantee that the extra space
  // will not be wasted.
  //
  // Here is the algorithm to reclaim the unused inobject space:
  // - Detect the first constructor call for this JSFunction.
  //   When it happens enter the "in progress" state: initialize construction
  //   counter in the initial_map.
  // - While the tracking is in progress initialize unused properties of a new
  //   object with one_pointer_filler_map instead of undefined_value (the "used"
  //   part is initialized with undefined_value as usual). This way they can
  //   be resized quickly and safely.
  // - Once enough objects have been created  compute the 'slack'
  //   (traverse the map transition tree starting from the
  //   initial_map and find the lowest value of unused_property_fields).
  // - Traverse the transition tree again and decrease the instance size
  //   of every map. Existing objects will resize automatically (they are
  //   filled with one_pointer_filler_map). All further allocations will
  //   use the adjusted instance size.
  // - SharedFunctionInfo's expected_nof_properties left unmodified since
  //   allocations made using different closures could actually create different
  //   kind of objects (see prototype inheritance pattern).
  //
  //  Important: inobject slack tracking is not attempted during the snapshot
  //  creation.

  static const int kGenerousAllocationCount =
      kSlackTrackingCounterStart - kSlackTrackingCounterEnd + 1;

  // Starts the tracking by initializing object constructions countdown counter.
  void StartInobjectSlackTracking();

  // True if the object constructions countdown counter is a range
  // [kSlackTrackingCounterEnd, kSlackTrackingCounterStart].
345
  inline bool IsInobjectSlackTrackingInProgress() const;
346 347

  // Does the tracking step.
348
  inline void InobjectSlackTrackingStep(Isolate* isolate);
349

350 351 352 353 354
  // Computes inobject slack for the transition tree starting at this initial
  // map.
  int ComputeMinObjectSlack(Isolate* isolate);
  inline int InstanceSizeFromSlack(int slack) const;

355 356
  // Completes inobject slack tracking for the transition tree starting at this
  // initial map.
357
  V8_EXPORT_PRIVATE void CompleteInobjectSlackTracking(Isolate* isolate);
358 359 360 361 362 363

  // Tells whether the object in the prototype property will be used
  // for instances created from this function.  If the prototype
  // property is set to a value that is not a JSObject, the prototype
  // property will not be used to create instances of the function.
  // See ECMA-262, 13.2.2.
364
  DECL_BOOLEAN_ACCESSORS(has_non_instance_prototype)
365 366 367

  // Tells whether the instance has a [[Construct]] internal method.
  // This property is implemented according to ES6, section 7.2.4.
368
  DECL_BOOLEAN_ACCESSORS(is_constructor)
369

370 371 372 373
  // Tells whether the instance with this map may have properties for
  // interesting symbols on it.
  // An "interesting symbol" is one for which Name::IsInterestingSymbol()
  // returns true, i.e. a well-known symbol like @@toStringTag.
374
  DECL_BOOLEAN_ACCESSORS(may_have_interesting_symbols)
375

376 377
  DECL_BOOLEAN_ACCESSORS(has_prototype_slot)

378
  // Records and queries whether the instance has a named interceptor.
379
  DECL_BOOLEAN_ACCESSORS(has_named_interceptor)
380 381

  // Records and queries whether the instance has an indexed interceptor.
382
  DECL_BOOLEAN_ACCESSORS(has_indexed_interceptor)
383 384 385 386 387 388 389

  // Tells whether the instance is undetectable.
  // An undetectable object is a special class of JSObject: 'typeof' operator
  // returns undefined, ToBoolean returns false. Otherwise it behaves like
  // a normal JS object.  It is useful for implementing undetectable
  // document.all in Firefox & Safari.
  // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
390
  DECL_BOOLEAN_ACCESSORS(is_undetectable)
391 392 393

  // Tells whether the instance has a [[Call]] internal method.
  // This property is implemented according to ES6, section 7.2.3.
394
  DECL_BOOLEAN_ACCESSORS(is_callable)
395

396 397 398
  DECL_BOOLEAN_ACCESSORS(new_target_is_base)
  DECL_BOOLEAN_ACCESSORS(is_extensible)
  DECL_BOOLEAN_ACCESSORS(is_prototype_map)
399
  inline bool is_abandoned_prototype_map() const;
400

401 402 403 404
  // Whether the instance has been added to the retained map list by
  // Heap::AddRetainedMap.
  DECL_BOOLEAN_ACCESSORS(is_in_retained_map_list)

405
  DECL_PRIMITIVE_ACCESSORS(elements_kind, ElementsKind)
406 407

  // Tells whether the instance has fast elements that are only Smis.
408
  inline bool has_fast_smi_elements() const;
409 410

  // Tells whether the instance has fast elements.
411 412 413 414 415 416 417
  inline bool has_fast_object_elements() const;
  inline bool has_fast_smi_or_object_elements() const;
  inline bool has_fast_double_elements() const;
  inline bool has_fast_elements() const;
  inline bool has_sloppy_arguments_elements() const;
  inline bool has_fast_sloppy_arguments_elements() const;
  inline bool has_fast_string_wrapper_elements() const;
418
  inline bool has_typed_array_elements() const;
419 420
  inline bool has_rab_gsab_typed_array_elements() const;
  inline bool has_typed_array_or_rab_gsab_typed_array_elements() const;
421
  inline bool has_any_typed_array_or_wasm_array_elements() const;
422
  inline bool has_dictionary_elements() const;
423 424
  inline bool has_any_nonextensible_elements() const;
  inline bool has_nonextensible_elements() const;
425 426
  inline bool has_sealed_elements() const;
  inline bool has_frozen_elements() const;
427

428 429 430 431 432
  // Weakly checks whether a map is detached from all transition trees. If this
  // returns true, the map is guaranteed to be detached. If it returns false,
  // there is no guarantee it is attached.
  inline bool IsDetached(Isolate* isolate) const;

433 434 435 436 437
  // Returns true if there is an object with potentially read-only elements
  // in the prototype chain. It could be a Proxy, a string wrapper,
  // an object with DICTIONARY_ELEMENTS potentially containing read-only
  // elements or an object with any frozen elements, or a slow arguments object.
  bool MayHaveReadOnlyElementsInPrototypeChain(Isolate* isolate);
438

439
  inline Map ElementsTransitionMap(Isolate* isolate, ConcurrencyMode cmode);
440

441
  inline FixedArrayBase GetInitialElements() const;
442 443 444 445

  // [raw_transitions]: Provides access to the transitions storage field.
  // Don't call set_raw_transitions() directly to overwrite transitions, use
  // the TransitionArray::ReplaceTransitions() wrapper instead!
446
  DECL_ACCESSORS(raw_transitions, MaybeObject)
447
  DECL_RELEASE_ACQUIRE_WEAK_ACCESSORS(raw_transitions)
448 449
  // [prototype_info]: Per-prototype metadata. Aliased with transitions
  // (which prototype maps don't have).
450 451
  DECL_GETTER(prototype_info, Object)
  DECL_RELEASE_ACQUIRE_ACCESSORS(prototype_info, Object)
452 453 454 455 456 457 458 459 460 461 462
  // PrototypeInfo is created lazily using this helper (which installs it on
  // the given prototype's map).
  static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
      Handle<JSObject> prototype, Isolate* isolate);
  static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
      Handle<Map> prototype_map, Isolate* isolate);
  inline bool should_be_fast_prototype_map() const;
  static void SetShouldBeFastPrototypeMap(Handle<Map> map, bool value,
                                          Isolate* isolate);

  // [prototype chain validity cell]: Associated with a prototype object,
463 464 465 466 467 468 469
  // stored in that object's map, indicates that prototype chains through this
  // object are currently valid. The cell will be invalidated and replaced when
  // the prototype chain changes. When there's nothing to guard (for example,
  // when direct prototype is null or Proxy) this function returns Smi with
  // |kPrototypeChainValid| sentinel value.
  static Handle<Object> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
                                                              Isolate* isolate);
470 471 472
  static const int kPrototypeChainValid = 0;
  static const int kPrototypeChainInvalid = 1;

473
  static bool IsPrototypeChainInvalidated(Map map);
474

475
  // Return the map of the root of object's prototype chain.
476
  Map GetPrototypeChainRootMap(Isolate* isolate) const;
477

478
  V8_EXPORT_PRIVATE Map FindRootMap(Isolate* isolate) const;
479 480
  V8_EXPORT_PRIVATE Map FindFieldOwner(Isolate* isolate,
                                       InternalIndex descriptor) const;
481

482
  inline int GetInObjectPropertyOffset(int index) const;
483

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  class FieldCounts {
   public:
    FieldCounts(int mutable_count, int const_count)
        : mutable_count_(mutable_count), const_count_(const_count) {}

    int GetTotal() const { return mutable_count() + const_count(); }

    int mutable_count() const { return mutable_count_; }
    int const_count() const { return const_count_; }

   private:
    int mutable_count_;
    int const_count_;
  };

  FieldCounts GetFieldCounts() const;
500
  int NumberOfFields(ConcurrencyMode cmode) const;
501

502 503
  bool HasOutOfObjectProperties() const;

504
  // TODO(ishell): candidate with JSObject::MigrateToMap().
505
  bool InstancesNeedRewriting(Map target, ConcurrencyMode cmode) const;
506
  bool InstancesNeedRewriting(Map target, int target_number_of_fields,
507
                              int target_inobject, int target_unused,
508 509
                              int* old_number_of_fields,
                              ConcurrencyMode cmode) const;
510 511 512 513
  // Returns true if the |field_type| is the most general one for
  // given |representation|.
  static inline bool IsMostGeneralFieldType(Representation representation,
                                            FieldType field_type);
514
  static inline bool FieldTypeIsCleared(Representation rep, FieldType type);
515

516 517 518
  // Generalizes representation and field_type if objects with given
  // instance type can have fast elements that can be transitioned by
  // stubs or optimized code to more general elements kind.
519 520
  // This generalization is necessary in order to ensure that elements kind
  // transitions performed by stubs / optimized code don't silently transition
521
  // fields with representation "Tagged" back to "Smi" or "HeapObject" or
522
  // fields with HeapObject representation and "Any" type back to "Class" type.
523 524
  static inline void GeneralizeIfCanHaveTransitionableFastElementsKind(
      Isolate* isolate, InstanceType instance_type,
525
      Representation* representation, Handle<FieldType>* field_type);
526

527
  V8_EXPORT_PRIVATE static Handle<Map> PrepareForDataProperty(
528
      Isolate* isolate, Handle<Map> old_map, InternalIndex descriptor_number,
529
      PropertyConstness constness, Handle<Object> value);
530

531 532
  V8_EXPORT_PRIVATE static Handle<Map> Normalize(Isolate* isolate,
                                                 Handle<Map> map,
533
                                                 ElementsKind new_elements_kind,
534 535
                                                 PropertyNormalizationMode mode,
                                                 const char* reason);
536

537 538 539 540
  inline static Handle<Map> Normalize(Isolate* isolate, Handle<Map> fast_map,
                                      PropertyNormalizationMode mode,
                                      const char* reason);

541 542 543 544
  // Tells whether the map is used for JSObjects in dictionary mode (ie
  // normalized objects, ie objects for which HasFastProperties returns false).
  // A map can never be used for both dictionary mode and fast mode JSObjects.
  // False by default and for HeapObjects that are not JSObjects.
545
  DECL_BOOLEAN_ACCESSORS(is_dictionary_map)
546 547 548

  // Tells whether the instance needs security checks when accessing its
  // properties.
549
  DECL_BOOLEAN_ACCESSORS(is_access_check_needed)
550 551

  // [prototype]: implicit prototype object.
552
  DECL_ACCESSORS(prototype, HeapObject)
553
  // TODO(jkummerow): make set_prototype private.
554 555 556
  V8_EXPORT_PRIVATE static void SetPrototype(
      Isolate* isolate, Handle<Map> map, Handle<HeapObject> prototype,
      bool enable_prototype_setup_mode = true);
557 558 559 560 561 562 563 564

  // [constructor]: points back to the function or FunctionTemplateInfo
  // responsible for this map.
  // The field overlaps with the back pointer. All maps in a transition tree
  // have the same constructor, so maps with back pointers can walk the
  // back pointer chain until they find the map holding their constructor.
  // Returns null_value if there's neither a constructor function nor a
  // FunctionTemplateInfo available.
565 566
  // The field also overlaps with the native context pointer for context maps,
  // and with the Wasm type info for WebAssembly object maps.
567
  DECL_ACCESSORS(constructor_or_back_pointer, Object)
568
  DECL_RELAXED_ACCESSORS(constructor_or_back_pointer, Object)
569
  DECL_ACCESSORS(native_context, NativeContext)
570
  DECL_ACCESSORS(native_context_or_null, Object)
571
  DECL_ACCESSORS(wasm_type_info, WasmTypeInfo)
572 573
  DECL_GETTER(GetConstructor, Object)
  DECL_GETTER(GetFunctionTemplateInfo, FunctionTemplateInfo)
574
  inline void SetConstructor(Object constructor,
575
                             WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
576 577 578 579
  // Constructor getter that performs at most the given number of steps
  // in the transition tree. Returns either the constructor or the map at
  // which the walk has stopped.
  inline Object TryGetConstructor(Isolate* isolate, int max_steps);
580 581
  // [back pointer]: points back to the parent map from which a transition
  // leads to this map. The field overlaps with the constructor (see above).
582 583
  DECL_GETTER(GetBackPointer, HeapObject)
  inline void SetBackPointer(HeapObject value,
584 585 586
                             WriteBarrierMode mode = UPDATE_WRITE_BARRIER);

  // [instance descriptors]: describes the object.
587
  DECL_ACCESSORS(instance_descriptors, DescriptorArray)
588
  DECL_RELAXED_ACCESSORS(instance_descriptors, DescriptorArray)
589
  DECL_ACQUIRE_GETTER(instance_descriptors, DescriptorArray)
590 591 592
  V8_EXPORT_PRIVATE void SetInstanceDescriptors(Isolate* isolate,
                                                DescriptorArray descriptors,
                                                int number_of_own_descriptors);
593

594 595 596
  inline void UpdateDescriptors(Isolate* isolate, DescriptorArray descriptors,
                                int number_of_own_descriptors);
  inline void InitializeDescriptors(Isolate* isolate,
597
                                    DescriptorArray descriptors);
598 599

  // [dependent code]: list of optimized codes that weakly embed this map.
600
  DECL_ACCESSORS(dependent_code, DependentCode)
601

602 603 604 605 606 607 608 609 610 611 612 613 614 615
  // [prototype_validity_cell]: Cell containing the validity bit for prototype
  // chains or Smi(0) if uninitialized.
  // The meaning of this validity cell is different for prototype maps and
  // non-prototype maps.
  // For prototype maps the validity bit "guards" modifications of prototype
  // chains going through this object. When a prototype object changes, both its
  // own validity cell and those of all "downstream" prototypes are invalidated;
  // handlers for a given receiver embed the currently valid cell for that
  // receiver's prototype during their creation and check it on execution.
  // For non-prototype maps which are used as transitioning store handlers this
  // field contains the validity cell which guards modifications of this map's
  // prototype.
  DECL_ACCESSORS(prototype_validity_cell, Object)

616 617 618 619
  // Returns true if prototype validity cell value represents "valid" prototype
  // chain state.
  inline bool IsPrototypeValidityCellValid() const;

620
  inline Name GetLastDescriptorName(Isolate* isolate) const;
621
  inline PropertyDetails GetLastDescriptorDetails(Isolate* isolate) const;
622

623
  inline InternalIndex LastAdded() const;
624

625
  inline int NumberOfOwnDescriptors() const;
626
  inline void SetNumberOfOwnDescriptors(int number);
627
  inline InternalIndex::Range IterateOwnDescriptors() const;
628

629
  inline Cell RetrieveDescriptorsPointer();
630 631 632 633

  // Checks whether all properties are stored either in the map or on the object
  // (inobject, properties, or elements backing store), requiring no special
  // checks.
634 635
  bool OnlyHasSimpleProperties() const;
  inline int EnumLength() const;
636 637
  inline void SetEnumLength(int length);

638
  DECL_BOOLEAN_ACCESSORS(owns_descriptors)
639

640
  inline void mark_unstable();
641
  inline bool is_stable() const;
642 643 644 645 646 647 648 649 650 651 652 653

  DECL_BOOLEAN_ACCESSORS(is_migration_target)

  DECL_BOOLEAN_ACCESSORS(is_immutable_proto)

  // This counter is used for in-object slack tracking.
  // The in-object slack tracking is considered enabled when the counter is
  // non zero. The counter only has a valid count for initial maps. For
  // transitioned maps only kNoSlackTracking has a meaning, namely that inobject
  // slack tracking already finished for the transition tree. Any other value
  // indicates that either inobject slack tracking is still in progress, or that
  // the map isn't part of the transition tree anymore.
654
  DECL_INT_ACCESSORS(construction_counter)
655 656

  DECL_BOOLEAN_ACCESSORS(is_deprecated)
657
  inline bool CanBeDeprecated() const;
658

659 660 661 662 663
  // Returns a non-deprecated version of the input. If the input was not
  // deprecated, it is directly returned. Otherwise, the non-deprecated version
  // is found by re-transitioning from the root of the transition tree using the
  // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
  // is found.
664 665
  V8_EXPORT_PRIVATE static MaybeHandle<Map> TryUpdate(
      Isolate* isolate, Handle<Map> map) V8_WARN_UNUSED_RESULT;
666 667 668 669

  // Returns a non-deprecated version of the input. This method may deprecate
  // existing maps along the way if encodings conflict. Not for use while
  // gathering type feedback. Use TryUpdate in those cases instead.
670 671
  V8_EXPORT_PRIVATE static Handle<Map> Update(Isolate* isolate,
                                              Handle<Map> map);
672

673
  static inline Handle<Map> CopyInitialMap(Isolate* isolate, Handle<Map> map);
674 675 676
  V8_EXPORT_PRIVATE static Handle<Map> CopyInitialMap(
      Isolate* isolate, Handle<Map> map, int instance_size,
      int in_object_properties, int unused_property_fields);
677
  static Handle<Map> CopyInitialMapNormalized(
678
      Isolate* isolate, Handle<Map> map,
679
      PropertyNormalizationMode mode = CLEAR_INOBJECT_PROPERTIES);
680
  static Handle<Map> CopyDropDescriptors(Isolate* isolate, Handle<Map> map);
681 682 683
  V8_EXPORT_PRIVATE static Handle<Map> CopyInsertDescriptor(
      Isolate* isolate, Handle<Map> map, Descriptor* descriptor,
      TransitionFlag flag);
684

685 686
  static MaybeObjectHandle WrapFieldType(Isolate* isolate,
                                         Handle<FieldType> type);
687
  V8_EXPORT_PRIVATE static FieldType UnwrapFieldType(MaybeObject wrapped_type);
688

689
  V8_EXPORT_PRIVATE V8_WARN_UNUSED_RESULT static MaybeHandle<Map> CopyWithField(
690 691 692 693
      Isolate* isolate, Handle<Map> map, Handle<Name> name,
      Handle<FieldType> type, PropertyAttributes attributes,
      PropertyConstness constness, Representation representation,
      TransitionFlag flag);
694

695 696 697 698
  V8_EXPORT_PRIVATE V8_WARN_UNUSED_RESULT static MaybeHandle<Map>
  CopyWithConstant(Isolate* isolate, Handle<Map> map, Handle<Name> name,
                   Handle<Object> constant, PropertyAttributes attributes,
                   TransitionFlag flag);
699 700 701

  // Returns a new map with all transitions dropped from the given map and
  // the ElementsKind set.
702
  static Handle<Map> TransitionElementsTo(Isolate* isolate, Handle<Map> map,
703 704
                                          ElementsKind to_kind);

705 706 707 708
  static base::Optional<Map> TryAsElementsKind(Isolate* isolate,
                                               Handle<Map> map,
                                               ElementsKind kind,
                                               ConcurrencyMode cmode);
709 710 711
  V8_EXPORT_PRIVATE static Handle<Map> AsElementsKind(Isolate* isolate,
                                                      Handle<Map> map,
                                                      ElementsKind kind);
712

713 714
  static Handle<Map> CopyAsElementsKind(Isolate* isolate, Handle<Map> map,
                                        ElementsKind kind, TransitionFlag flag);
715

716
  static Handle<Map> AsLanguageMode(Isolate* isolate, Handle<Map> initial_map,
717
                                    Handle<SharedFunctionInfo> shared_info);
718

719 720
  V8_EXPORT_PRIVATE static Handle<Map> CopyForPreventExtensions(
      Isolate* isolate, Handle<Map> map, PropertyAttributes attrs_to_add,
721
      Handle<Symbol> transition_marker, const char* reason,
722
      bool old_map_is_dictionary_elements_kind = false);
723 724 725 726

  // Maximal number of fast properties. Used to restrict the number of map
  // transitions to avoid an explosion in the number of maps for objects used as
  // dictionaries.
727
  inline bool TooManyFastProperties(StoreOrigin store_origin) const;
728 729 730 731 732
  V8_EXPORT_PRIVATE static Handle<Map> TransitionToDataProperty(
      Isolate* isolate, Handle<Map> map, Handle<Name> name,
      Handle<Object> value, PropertyAttributes attributes,
      PropertyConstness constness, StoreOrigin store_origin);
  V8_EXPORT_PRIVATE static Handle<Map> TransitionToAccessorProperty(
733 734
      Isolate* isolate, Handle<Map> map, Handle<Name> name,
      InternalIndex descriptor, Handle<Object> getter, Handle<Object> setter,
735 736
      PropertyAttributes attributes);

737
  inline void AppendDescriptor(Isolate* isolate, Descriptor* desc);
738 739 740 741

  // Returns a copy of the map, prepared for inserting into the transition
  // tree (if the |map| owns descriptors then the new one will share
  // descriptors with |map|).
742 743
  static Handle<Map> CopyForElementsTransition(Isolate* isolate,
                                               Handle<Map> map);
744 745 746

  // Returns a copy of the map, with all transitions dropped from the
  // instance descriptors.
747 748
  static Handle<Map> Copy(Isolate* isolate, Handle<Map> map,
                          const char* reason);
749 750
  V8_EXPORT_PRIVATE static Handle<Map> Create(Isolate* isolate,
                                              int inobject_properties);
751 752

  // Returns the next free property index (only valid for FAST MODE).
753
  int NextFreePropertyIndex() const;
754

755
  // Returns the number of enumerable properties.
756
  int NumberOfEnumerableProperties() const;
757 758 759

  static inline int SlackForArraySize(int old_size, int size_limit);

760 761 762
  V8_EXPORT_PRIVATE static void EnsureDescriptorSlack(Isolate* isolate,
                                                      Handle<Map> map,
                                                      int slack);
763

764 765
  // Returns the map to be used for instances when the given {prototype} is
  // passed to an Object.create call. Might transition the given {prototype}.
766 767
  static Handle<Map> GetObjectCreateMap(Isolate* isolate,
                                        Handle<HeapObject> prototype);
768

769 770 771 772 773 774
  // Computes a hash value for this map, to be used in HashTables and such.
  int Hash();

  // Returns the transitioned map for this map with the most generic
  // elements_kind that's found in |candidates|, or |nullptr| if no match is
  // found at all.
775
  V8_EXPORT_PRIVATE Map FindElementsKindTransitionedMap(
776
      Isolate* isolate, MapHandles const& candidates, ConcurrencyMode cmode);
777

778
  inline bool CanTransition() const;
779

780
  static Map GetInstanceTypeMap(ReadOnlyRoots roots, InstanceType type);
781

782 783 784
#define DECL_TESTER(Type, ...) inline bool Is##Type##Map() const;
  INSTANCE_TYPE_CHECKERS(DECL_TESTER)
#undef DECL_TESTER
785
  inline bool IsBooleanMap() const;
786
  inline bool IsNullOrUndefinedMap() const;
787 788
  inline bool IsPrimitiveMap() const;
  inline bool IsSpecialReceiverMap() const;
789 790
  inline bool IsCustomElementsReceiverMap() const;

791
  bool IsMapInArrayPrototypeChain(Isolate* isolate) const;
792 793

  // Dispatched behavior.
794
  void MapPrint(std::ostream& os);
795
  DECL_VERIFIER(Map)
796 797

#ifdef VERIFY_HEAP
798
  void DictionaryMapVerify(Isolate* isolate);
799 800
#endif

801
  DECL_PRIMITIVE_ACCESSORS(visitor_id, VisitorId)
802

803 804 805 806 807 808
  static ObjectFields ObjectFieldsFrom(VisitorId visitor_id) {
    return (visitor_id < kDataOnlyVisitorIdCount)
               ? ObjectFields::kDataOnly
               : ObjectFields::kMaybePointers;
  }

809 810
  V8_EXPORT_PRIVATE static Handle<Map> TransitionToPrototype(
      Isolate* isolate, Handle<Map> map, Handle<HeapObject> prototype);
811

812 813
  static Handle<Map> TransitionToImmutableProto(Isolate* isolate,
                                                Handle<Map> map);
814 815 816

  static const int kMaxPreAllocatedPropertyFields = 255;

817
  STATIC_ASSERT(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
818

819
  class BodyDescriptor;
820

821 822
  // Compares this map to another to see if they describe equivalent objects,
  // up to the given |elements_kind|.
823 824 825
  // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
  // it had exactly zero inobject properties.
  // The "shared" flags of both this map and |other| are ignored.
826
  bool EquivalentToForNormalization(const Map other, ElementsKind elements_kind,
827
                                    PropertyNormalizationMode mode) const;
828 829
  inline bool EquivalentToForNormalization(
      const Map other, PropertyNormalizationMode mode) const;
830

831
  void PrintMapDetails(std::ostream& os);
832 833

  static inline Handle<Map> AddMissingTransitionsForTesting(
834
      Isolate* isolate, Handle<Map> split_map,
835
      Handle<DescriptorArray> descriptors);
836 837 838 839

  // Fires when the layout of an object with a leaf map changes.
  // This includes adding transitions to the leaf map or changing
  // the descriptor array.
840
  inline void NotifyLeafMapLayoutChange(Isolate* isolate);
841

842
  V8_EXPORT_PRIVATE static VisitorId GetVisitorId(Map map);
843

844 845 846 847 848 849 850 851 852 853
  // Returns true if objects with given instance type are allowed to have
  // fast transitionable elements kinds. This predicate is used to ensure
  // that objects that can have transitionable fast elements kind will not
  // get in-place generalizable fields because the elements kind transition
  // performed by stubs or optimized code can't properly generalize such
  // fields.
  static inline bool CanHaveFastTransitionableElementsKind(
      InstanceType instance_type);
  inline bool CanHaveFastTransitionableElementsKind() const;

854 855 856 857 858 859
  // Maps for Wasm objects can use certain fields for other purposes.
  inline uint8_t WasmByte1() const;
  inline uint8_t WasmByte2() const;
  inline void SetWasmByte1(uint8_t value);
  inline void SetWasmByte2(uint8_t value);

860
 private:
861 862
  // This byte encodes either the instance size without the in-object slack or
  // the slack size in properties backing store.
863
  // Let H be JSObject::kHeaderSize / kTaggedSize.
864 865 866
  // If value >= H then:
  //     - all field properties are stored in the object.
  //     - there is no property array.
867
  //     - value * kTaggedSize is the actual object size without the slack.
868 869 870 871 872 873
  // Otherwise:
  //     - there is no slack in the object.
  //     - the property array has value slack slots.
  // Note that this encoding requires that H = JSObject::kFieldsAdded.
  DECL_INT_ACCESSORS(used_or_unused_instance_size_in_words)

874 875
  // Returns the map that this (root) map transitions to if its elements_kind
  // is changed to |elements_kind|, or |nullptr| if no such map is cached yet.
876 877
  Map LookupElementsTransitionMap(Isolate* isolate, ElementsKind elements_kind,
                                  ConcurrencyMode cmode);
878 879 880 881 882 883

  // Tries to replay property transitions starting from this (root) map using
  // the descriptor array of the |map|. The |root_map| is expected to have
  // proper elements kind and therefore elements kinds transitions are not
  // taken by this function. Returns |nullptr| if matching transition map is
  // not found.
884 885
  Map TryReplayPropertyTransitions(Isolate* isolate, Map map,
                                   ConcurrencyMode cmode);
886

887 888 889
  static void ConnectTransition(Isolate* isolate, Handle<Map> parent,
                                Handle<Map> child, Handle<Name> name,
                                SimpleTransitionFlag flag);
890

891 892 893
  bool EquivalentToForTransition(const Map other, ConcurrencyMode cmode) const;
  bool EquivalentToForElementsKindTransition(const Map other,
                                             ConcurrencyMode cmode) const;
894 895
  static Handle<Map> RawCopy(Isolate* isolate, Handle<Map> map,
                             int instance_size, int inobject_properties);
896
  static Handle<Map> ShareDescriptor(Isolate* isolate, Handle<Map> map,
897 898
                                     Handle<DescriptorArray> descriptors,
                                     Descriptor* descriptor);
899
  V8_EXPORT_PRIVATE static Handle<Map> AddMissingTransitions(
900 901 902 903 904
      Isolate* isolate, Handle<Map> map, Handle<DescriptorArray> descriptors);
  static void InstallDescriptors(Isolate* isolate, Handle<Map> parent_map,
                                 Handle<Map> child_map,
                                 InternalIndex new_descriptor,
                                 Handle<DescriptorArray> descriptors);
905 906
  static Handle<Map> CopyAddDescriptor(Isolate* isolate, Handle<Map> map,
                                       Descriptor* descriptor,
907
                                       TransitionFlag flag);
908 909 910 911 912 913
  static Handle<Map> CopyReplaceDescriptors(Isolate* isolate, Handle<Map> map,
                                            Handle<DescriptorArray> descriptors,
                                            TransitionFlag flag,
                                            MaybeHandle<Name> maybe_name,
                                            const char* reason,
                                            SimpleTransitionFlag simple_flag);
914

915
  static Handle<Map> CopyReplaceDescriptor(Isolate* isolate, Handle<Map> map,
916
                                           Handle<DescriptorArray> descriptors,
917 918
                                           Descriptor* descriptor,
                                           InternalIndex index,
919
                                           TransitionFlag flag);
920
  static Handle<Map> CopyNormalized(Isolate* isolate, Handle<Map> map,
921 922
                                    PropertyNormalizationMode mode);

923
  void DeprecateTransitionTree(Isolate* isolate);
924

925
  void ReplaceDescriptors(Isolate* isolate, DescriptorArray new_descriptors);
926

927 928
  // This is the equivalent of IsMap() but avoids reading the instance type so
  // it can be used concurrently without acquire load.
929
  V8_INLINE bool ConcurrentIsMap(PtrComprCageBase cage_base,
930 931
                                 const Object& object) const;

932 933 934
  // Use the high-level instance_descriptors/SetInstanceDescriptors instead.
  DECL_RELEASE_SETTER(instance_descriptors, DescriptorArray)

935 936 937 938
  // Hide inherited accessors from the generated superclass.
  DECL_ACCESSORS(constructor_or_back_pointer_or_native_context, Object)
  DECL_ACCESSORS(transitions_or_prototype_info, Object)

939 940 941 942
  static const int kFastPropertiesSoftLimit = 12;
  static const int kMaxFastProperties = 128;

  friend class MapUpdater;
943 944
  template <typename ConcreteVisitor, typename MarkingState>
  friend class MarkingVisitorBase;
945

946
  TQ_OBJECT_CONSTRUCTORS(Map)
947 948 949 950 951
};

// The cache for maps used by normalized (dictionary mode) objects.
// Such maps do not have property descriptors, so a typical program
// needs very limited number of distinct normalized maps.
952
class NormalizedMapCache : public WeakFixedArray {
953
 public:
954
  NEVER_READ_ONLY_SPACE
955 956
  static Handle<NormalizedMapCache> New(Isolate* isolate);

957
  V8_WARN_UNUSED_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
958
                                             ElementsKind elements_kind,
959
                                             PropertyNormalizationMode mode);
960
  void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
961

962
  DECL_CAST(NormalizedMapCache)
963
  DECL_VERIFIER(NormalizedMapCache)
964

965
 private:
966 967
  friend bool HeapObject::IsNormalizedMapCache(
      PtrComprCageBase cage_base) const;
968

969 970 971 972 973
  static const int kEntries = 64;

  static inline int GetIndex(Handle<Map> map);

  // The following declarations hide base class methods.
974 975
  Object get(int index);
  void set(int index, Object value);
976

977
  OBJECT_CONSTRUCTORS(NormalizedMapCache, WeakFixedArray);
978 979 980 981 982 983 984 985
};

}  // namespace internal
}  // namespace v8

#include "src/objects/object-macros-undef.h"

#endif  // V8_OBJECTS_MAP_H_