Object properties added using dot syntax (o.f = ...) from code that isn't in eval...
[WebKit-https.git] / Source / JavaScriptCore / runtime / Structure.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2013 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "Structure.h"
28
29 #include "CodeBlock.h"
30 #include "DumpContext.h"
31 #include "JSObject.h"
32 #include "JSPropertyNameIterator.h"
33 #include "Lookup.h"
34 #include "PropertyNameArray.h"
35 #include "StructureChain.h"
36 #include "StructureRareDataInlines.h"
37 #include <wtf/CommaPrinter.h>
38 #include <wtf/RefCountedLeakCounter.h>
39 #include <wtf/RefPtr.h>
40 #include <wtf/Threading.h>
41
42 #define DUMP_STRUCTURE_ID_STATISTICS 0
43
44 #ifndef NDEBUG
45 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
46 #else
47 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
48 #endif
49
50 using namespace std;
51 using namespace WTF;
52
53 #if DUMP_PROPERTYMAP_STATS
54
55 int numProbes;
56 int numCollisions;
57 int numRehashes;
58 int numRemoves;
59
60 #endif
61
62 namespace JSC {
63
64 #if DUMP_STRUCTURE_ID_STATISTICS
65 static HashSet<Structure*>& liveStructureSet = *(new HashSet<Structure*>);
66 #endif
67
68 bool StructureTransitionTable::contains(StringImpl* rep, unsigned attributes) const
69 {
70     if (isUsingSingleSlot()) {
71         Structure* transition = singleTransition();
72         return transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes;
73     }
74     return map()->get(make_pair(rep, attributes));
75 }
76
77 inline Structure* StructureTransitionTable::get(StringImpl* rep, unsigned attributes) const
78 {
79     if (isUsingSingleSlot()) {
80         Structure* transition = singleTransition();
81         return (transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes) ? transition : 0;
82     }
83     return map()->get(make_pair(rep, attributes));
84 }
85
86 inline void StructureTransitionTable::add(VM& vm, Structure* structure)
87 {
88     if (isUsingSingleSlot()) {
89         Structure* existingTransition = singleTransition();
90
91         // This handles the first transition being added.
92         if (!existingTransition) {
93             setSingleTransition(vm, structure);
94             return;
95         }
96
97         // This handles the second transition being added
98         // (or the first transition being despecified!)
99         setMap(new TransitionMap());
100         add(vm, existingTransition);
101     }
102
103     // Add the structure to the map.
104
105     // Newer versions of the STL have an std::make_pair function that takes rvalue references.
106     // When either of the parameters are bitfields, the C++ compiler will try to bind them as lvalues, which is invalid. To work around this, use unary "+" to make the parameter an rvalue.
107     // See https://bugs.webkit.org/show_bug.cgi?id=59261 for more details
108     map()->set(make_pair(structure->m_nameInPrevious.get(), +structure->m_attributesInPrevious), structure);
109 }
110
111 void Structure::dumpStatistics()
112 {
113 #if DUMP_STRUCTURE_ID_STATISTICS
114     unsigned numberLeaf = 0;
115     unsigned numberUsingSingleSlot = 0;
116     unsigned numberSingletons = 0;
117     unsigned numberWithPropertyMaps = 0;
118     unsigned totalPropertyMapsSize = 0;
119
120     HashSet<Structure*>::const_iterator end = liveStructureSet.end();
121     for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
122         Structure* structure = *it;
123
124         switch (structure->m_transitionTable.size()) {
125             case 0:
126                 ++numberLeaf;
127                 if (!structure->previousID())
128                     ++numberSingletons;
129                 break;
130
131             case 1:
132                 ++numberUsingSingleSlot;
133                 break;
134         }
135
136         if (structure->propertyTable()) {
137             ++numberWithPropertyMaps;
138             totalPropertyMapsSize += structure->propertyTable()->sizeInMemory();
139         }
140     }
141
142     dataLogF("Number of live Structures: %d\n", liveStructureSet.size());
143     dataLogF("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
144     dataLogF("Number of Structures that are leaf nodes: %d\n", numberLeaf);
145     dataLogF("Number of Structures that singletons: %d\n", numberSingletons);
146     dataLogF("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);
147
148     dataLogF("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
149     dataLogF("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
150     dataLogF("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
151 #else
152     dataLogF("Dumping Structure statistics is not enabled.\n");
153 #endif
154 }
155
156 Structure::Structure(VM& vm, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
157     : JSCell(vm, vm.structureStructure.get())
158     , m_globalObject(vm, this, globalObject, WriteBarrier<JSGlobalObject>::MayBeNull)
159     , m_prototype(vm, this, prototype)
160     , m_classInfo(classInfo)
161     , m_transitionWatchpointSet(InitializedWatching)
162     , m_offset(invalidOffset)
163     , m_typeInfo(typeInfo)
164     , m_indexingType(indexingType)
165     , m_inlineCapacity(inlineCapacity)
166     , m_dictionaryKind(NoneDictionaryKind)
167     , m_isPinnedPropertyTable(false)
168     , m_hasGetterSetterProperties(false)
169     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
170     , m_hasNonEnumerableProperties(false)
171     , m_attributesInPrevious(0)
172     , m_specificFunctionThrashCount(0)
173     , m_preventExtensions(false)
174     , m_didTransition(false)
175     , m_staticFunctionReified(false)
176 {
177     ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity());
178     ASSERT(static_cast<PropertyOffset>(inlineCapacity) < firstOutOfLineOffset);
179     ASSERT(!typeInfo.structureHasRareData());
180 }
181
182 const ClassInfo Structure::s_info = { "Structure", 0, 0, 0, CREATE_METHOD_TABLE(Structure) };
183
184 Structure::Structure(VM& vm)
185     : JSCell(CreatingEarlyCell)
186     , m_prototype(vm, this, jsNull())
187     , m_classInfo(info())
188     , m_transitionWatchpointSet(InitializedWatching)
189     , m_offset(invalidOffset)
190     , m_typeInfo(CompoundType, OverridesVisitChildren)
191     , m_indexingType(0)
192     , m_inlineCapacity(0)
193     , m_dictionaryKind(NoneDictionaryKind)
194     , m_isPinnedPropertyTable(false)
195     , m_hasGetterSetterProperties(false)
196     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
197     , m_hasNonEnumerableProperties(false)
198     , m_attributesInPrevious(0)
199     , m_specificFunctionThrashCount(0)
200     , m_preventExtensions(false)
201     , m_didTransition(false)
202     , m_staticFunctionReified(false)
203 {
204 }
205
206 Structure::Structure(VM& vm, const Structure* previous)
207     : JSCell(vm, vm.structureStructure.get())
208     , m_prototype(vm, this, previous->storedPrototype())
209     , m_classInfo(previous->m_classInfo)
210     , m_transitionWatchpointSet(InitializedWatching)
211     , m_offset(invalidOffset)
212     , m_typeInfo(previous->typeInfo().type(), previous->typeInfo().flags() & ~StructureHasRareData)
213     , m_indexingType(previous->indexingTypeIncludingHistory())
214     , m_inlineCapacity(previous->m_inlineCapacity)
215     , m_dictionaryKind(previous->m_dictionaryKind)
216     , m_isPinnedPropertyTable(false)
217     , m_hasGetterSetterProperties(previous->m_hasGetterSetterProperties)
218     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto)
219     , m_hasNonEnumerableProperties(previous->m_hasNonEnumerableProperties)
220     , m_attributesInPrevious(0)
221     , m_specificFunctionThrashCount(previous->m_specificFunctionThrashCount)
222     , m_preventExtensions(previous->m_preventExtensions)
223     , m_didTransition(true)
224     , m_staticFunctionReified(previous->m_staticFunctionReified)
225 {
226     if (previous->typeInfo().structureHasRareData() && previous->rareData()->needsCloning())
227         cloneRareDataFrom(vm, previous);
228     else if (previous->previousID())
229         m_previousOrRareData.set(vm, this, previous->previousID());
230
231     previous->notifyTransitionFromThisStructure();
232     if (previous->m_globalObject)
233         m_globalObject.set(vm, this, previous->m_globalObject.get());
234 }
235
236 void Structure::destroy(JSCell* cell)
237 {
238     static_cast<Structure*>(cell)->Structure::~Structure();
239 }
240
241 void Structure::findStructuresAndMapForMaterialization(Vector<Structure*, 8>& structures, Structure*& structure, PropertyTable*& table)
242 {
243     ASSERT(structures.isEmpty());
244     table = 0;
245
246     for (structure = this; structure; structure = structure->previousID()) {
247         structure->m_lock.lock();
248         
249         table = structure->propertyTable().get();
250         if (table) {
251             // Leave the structure locked, so that the caller can do things to it atomically
252             // before it loses its property table.
253             return;
254         }
255         
256         structures.append(structure);
257         structure->m_lock.unlock();
258     }
259     
260     ASSERT(!structure);
261     ASSERT(!table);
262 }
263
264 void Structure::materializePropertyMap(VM& vm)
265 {
266     ASSERT(structure()->classInfo() == info());
267     ASSERT(!propertyTable());
268
269     Vector<Structure*, 8> structures;
270     Structure* structure;
271     PropertyTable* table;
272     
273     findStructuresAndMapForMaterialization(structures, structure, table);
274     
275     if (table) {
276         table = table->copy(vm, 0, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
277         structure->m_lock.unlock();
278     }
279     
280     // Must hold the lock on this structure, since we will be modifying this structure's
281     // property map. We don't want getConcurrently() to see the property map in a half-baked
282     // state.
283     ConcurrentJITLocker locker(m_lock);
284     if (!table)
285         createPropertyMap(locker, vm, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
286     else
287         propertyTable().set(vm, this, table);
288
289     for (size_t i = structures.size(); i--;) {
290         structure = structures[i];
291         if (!structure->m_nameInPrevious)
292             continue;
293         PropertyMapEntry entry(vm, this, structure->m_nameInPrevious.get(), structure->m_offset, structure->m_attributesInPrevious, structure->m_specificValueInPrevious.get());
294         propertyTable()->add(entry, m_offset, PropertyTable::PropertyOffsetMustNotChange);
295     }
296     
297     checkOffsetConsistency();
298 }
299
300 inline size_t nextOutOfLineStorageCapacity(size_t currentCapacity)
301 {
302     if (!currentCapacity)
303         return initialOutOfLineCapacity;
304     return currentCapacity * outOfLineGrowthFactor;
305 }
306
307 size_t Structure::suggestedNewOutOfLineStorageCapacity()
308 {
309     return nextOutOfLineStorageCapacity(outOfLineCapacity());
310 }
311  
312 void Structure::despecifyDictionaryFunction(VM& vm, PropertyName propertyName)
313 {
314     StringImpl* rep = propertyName.uid();
315
316     materializePropertyMapIfNecessary(vm);
317
318     ASSERT(isDictionary());
319     ASSERT(propertyTable());
320
321     PropertyMapEntry* entry = propertyTable()->find(rep).first;
322     ASSERT(entry);
323     entry->specificValue.clear();
324 }
325
326 Structure* Structure::addPropertyTransitionToExistingStructureImpl(Structure* structure, StringImpl* uid, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
327 {
328     ASSERT(!structure->isDictionary());
329     ASSERT(structure->isObject());
330
331     if (Structure* existingTransition = structure->m_transitionTable.get(uid, attributes)) {
332         JSCell* specificValueInPrevious = existingTransition->m_specificValueInPrevious.get();
333         if (specificValueInPrevious && specificValueInPrevious != specificValue)
334             return 0;
335         validateOffset(existingTransition->m_offset, existingTransition->inlineCapacity());
336         offset = existingTransition->m_offset;
337         return existingTransition;
338     }
339
340     return 0;
341 }
342
343 Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
344 {
345     ASSERT(!isCompilationThread());
346     return addPropertyTransitionToExistingStructureImpl(structure, propertyName.uid(), attributes, specificValue, offset);
347 }
348
349 Structure* Structure::addPropertyTransitionToExistingStructureConcurrently(Structure* structure, StringImpl* uid, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
350 {
351     ConcurrentJITLocker locker(structure->m_lock);
352     return addPropertyTransitionToExistingStructureImpl(structure, uid, attributes, specificValue, offset);
353 }
354
355 bool Structure::anyObjectInChainMayInterceptIndexedAccesses() const
356 {
357     for (const Structure* current = this; ;) {
358         if (current->mayInterceptIndexedAccesses())
359             return true;
360         
361         JSValue prototype = current->storedPrototype();
362         if (prototype.isNull())
363             return false;
364         
365         current = asObject(prototype)->structure();
366     }
367 }
368
369 bool Structure::needsSlowPutIndexing() const
370 {
371     return anyObjectInChainMayInterceptIndexedAccesses()
372         || globalObject()->isHavingABadTime();
373 }
374
375 NonPropertyTransition Structure::suggestedArrayStorageTransition() const
376 {
377     if (needsSlowPutIndexing())
378         return AllocateSlowPutArrayStorage;
379     
380     return AllocateArrayStorage;
381 }
382
383 Structure* Structure::addPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset, PutPropertySlot::Context context)
384 {
385     // If we have a specific function, we may have got to this point if there is
386     // already a transition with the correct property name and attributes, but
387     // specialized to a different function.  In this case we just want to give up
388     // and despecialize the transition.
389     // In this case we clear the value of specificFunction which will result
390     // in us adding a non-specific transition, and any subsequent lookup in
391     // Structure::addPropertyTransitionToExistingStructure will just use that.
392     if (specificValue && structure->m_transitionTable.contains(propertyName.uid(), attributes))
393         specificValue = 0;
394
395     ASSERT(!structure->isDictionary());
396     ASSERT(structure->isObject());
397     ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, specificValue, offset));
398     
399     if (structure->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
400         specificValue = 0;
401
402     int maxTransitionLength;
403     if (context == PutPropertySlot::PutById)
404         maxTransitionLength = s_maxTransitionLengthForNonEvalPutById;
405     else
406         maxTransitionLength = s_maxTransitionLength;
407     if (structure->transitionCount() > maxTransitionLength) {
408         Structure* transition = toCacheableDictionaryTransition(vm, structure);
409         ASSERT(structure != transition);
410         offset = transition->putSpecificValue(vm, propertyName, attributes, specificValue);
411         return transition;
412     }
413     
414     Structure* transition = create(vm, structure);
415
416     transition->m_cachedPrototypeChain.setMayBeNull(vm, transition, structure->m_cachedPrototypeChain.get());
417     transition->setPreviousID(vm, transition, structure);
418     transition->m_nameInPrevious = propertyName.uid();
419     transition->m_attributesInPrevious = attributes;
420     transition->m_specificValueInPrevious.setMayBeNull(vm, transition, specificValue);
421     transition->propertyTable().set(vm, transition, structure->takePropertyTableOrCloneIfPinned(vm, transition));
422     transition->m_offset = structure->m_offset;
423
424     offset = transition->putSpecificValue(vm, propertyName, attributes, specificValue);
425
426     checkOffset(transition->m_offset, transition->inlineCapacity());
427     {
428         ConcurrentJITLocker locker(structure->m_lock);
429         structure->m_transitionTable.add(vm, transition);
430     }
431     transition->checkOffsetConsistency();
432     structure->checkOffsetConsistency();
433     return transition;
434 }
435
436 Structure* Structure::removePropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, PropertyOffset& offset)
437 {
438     ASSERT(!structure->isUncacheableDictionary());
439
440     Structure* transition = toUncacheableDictionaryTransition(vm, structure);
441
442     offset = transition->remove(propertyName);
443
444     transition->checkOffsetConsistency();
445     return transition;
446 }
447
448 Structure* Structure::changePrototypeTransition(VM& vm, Structure* structure, JSValue prototype)
449 {
450     Structure* transition = create(vm, structure);
451
452     transition->m_prototype.set(vm, transition, prototype);
453
454     structure->materializePropertyMapIfNecessary(vm);
455     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
456     transition->m_offset = structure->m_offset;
457     transition->pin();
458
459     transition->checkOffsetConsistency();
460     return transition;
461 }
462
463 Structure* Structure::despecifyFunctionTransition(VM& vm, Structure* structure, PropertyName replaceFunction)
464 {
465     ASSERT(structure->m_specificFunctionThrashCount < maxSpecificFunctionThrashCount);
466     Structure* transition = create(vm, structure);
467
468     ++transition->m_specificFunctionThrashCount;
469
470     structure->materializePropertyMapIfNecessary(vm);
471     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
472     transition->m_offset = structure->m_offset;
473     transition->pin();
474
475     if (transition->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
476         transition->despecifyAllFunctions(vm);
477     else {
478         bool removed = transition->despecifyFunction(vm, replaceFunction);
479         ASSERT_UNUSED(removed, removed);
480     }
481
482     transition->checkOffsetConsistency();
483     return transition;
484 }
485
486 Structure* Structure::attributeChangeTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes)
487 {
488     if (!structure->isUncacheableDictionary()) {
489         Structure* transition = create(vm, structure);
490
491         structure->materializePropertyMapIfNecessary(vm);
492         transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
493         transition->m_offset = structure->m_offset;
494         transition->pin();
495         
496         structure = transition;
497     }
498
499     ASSERT(structure->propertyTable());
500     PropertyMapEntry* entry = structure->propertyTable()->find(propertyName.uid()).first;
501     ASSERT(entry);
502     entry->attributes = attributes;
503
504     structure->checkOffsetConsistency();
505     return structure;
506 }
507
508 Structure* Structure::toDictionaryTransition(VM& vm, Structure* structure, DictionaryKind kind)
509 {
510     ASSERT(!structure->isUncacheableDictionary());
511     
512     Structure* transition = create(vm, structure);
513
514     structure->materializePropertyMapIfNecessary(vm);
515     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
516     transition->m_offset = structure->m_offset;
517     transition->m_dictionaryKind = kind;
518     transition->pin();
519
520     transition->checkOffsetConsistency();
521     return transition;
522 }
523
524 Structure* Structure::toCacheableDictionaryTransition(VM& vm, Structure* structure)
525 {
526     return toDictionaryTransition(vm, structure, CachedDictionaryKind);
527 }
528
529 Structure* Structure::toUncacheableDictionaryTransition(VM& vm, Structure* structure)
530 {
531     return toDictionaryTransition(vm, structure, UncachedDictionaryKind);
532 }
533
534 // In future we may want to cache this transition.
535 Structure* Structure::sealTransition(VM& vm, Structure* structure)
536 {
537     Structure* transition = preventExtensionsTransition(vm, structure);
538
539     if (transition->propertyTable()) {
540         PropertyTable::iterator end = transition->propertyTable()->end();
541         for (PropertyTable::iterator iter = transition->propertyTable()->begin(); iter != end; ++iter)
542             iter->attributes |= DontDelete;
543     }
544
545     transition->checkOffsetConsistency();
546     return transition;
547 }
548
549 // In future we may want to cache this transition.
550 Structure* Structure::freezeTransition(VM& vm, Structure* structure)
551 {
552     Structure* transition = preventExtensionsTransition(vm, structure);
553
554     if (transition->propertyTable()) {
555         PropertyTable::iterator iter = transition->propertyTable()->begin();
556         PropertyTable::iterator end = transition->propertyTable()->end();
557         if (iter != end)
558             transition->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto = true;
559         for (; iter != end; ++iter)
560             iter->attributes |= iter->attributes & Accessor ? DontDelete : (DontDelete | ReadOnly);
561     }
562
563     transition->checkOffsetConsistency();
564     return transition;
565 }
566
567 // In future we may want to cache this transition.
568 Structure* Structure::preventExtensionsTransition(VM& vm, Structure* structure)
569 {
570     Structure* transition = create(vm, structure);
571
572     // Don't set m_offset, as one can not transition to this.
573
574     structure->materializePropertyMapIfNecessary(vm);
575     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
576     transition->m_offset = structure->m_offset;
577     transition->m_preventExtensions = true;
578     transition->pin();
579
580     transition->checkOffsetConsistency();
581     return transition;
582 }
583
584 PropertyTable* Structure::takePropertyTableOrCloneIfPinned(VM& vm, Structure* owner)
585 {
586     materializePropertyMapIfNecessaryForPinning(vm);
587     
588     if (m_isPinnedPropertyTable)
589         return propertyTable()->copy(vm, owner, propertyTable()->size() + 1);
590     
591     // Hold the lock while stealing the table - so that getConcurrently() on another thread
592     // will either have to bypass this structure, or will get to use the property table
593     // before it is stolen.
594     ConcurrentJITLocker locker(m_lock);
595     PropertyTable* takenPropertyTable = propertyTable().get();
596     propertyTable().clear();
597     return takenPropertyTable;
598 }
599
600 Structure* Structure::nonPropertyTransition(VM& vm, Structure* structure, NonPropertyTransition transitionKind)
601 {
602     unsigned attributes = toAttributes(transitionKind);
603     IndexingType indexingType = newIndexingType(structure->indexingTypeIncludingHistory(), transitionKind);
604     
605     if (JSGlobalObject* globalObject = structure->m_globalObject.get()) {
606         if (globalObject->isOriginalArrayStructure(structure)) {
607             Structure* result = globalObject->originalArrayStructureForIndexingType(indexingType);
608             if (result->indexingTypeIncludingHistory() == indexingType) {
609                 structure->notifyTransitionFromThisStructure();
610                 return result;
611             }
612         }
613     }
614     
615     if (Structure* existingTransition = structure->m_transitionTable.get(0, attributes)) {
616         ASSERT(existingTransition->m_attributesInPrevious == attributes);
617         ASSERT(existingTransition->indexingTypeIncludingHistory() == indexingType);
618         return existingTransition;
619     }
620     
621     Structure* transition = create(vm, structure);
622     transition->setPreviousID(vm, transition, structure);
623     transition->m_attributesInPrevious = attributes;
624     transition->m_indexingType = indexingType;
625     transition->propertyTable().set(vm, transition, structure->takePropertyTableOrCloneIfPinned(vm, transition));
626     transition->m_offset = structure->m_offset;
627     checkOffset(transition->m_offset, transition->inlineCapacity());
628     
629     {
630         ConcurrentJITLocker locker(structure->m_lock);
631         structure->m_transitionTable.add(vm, transition);
632     }
633     transition->checkOffsetConsistency();
634     return transition;
635 }
636
637 // In future we may want to cache this property.
638 bool Structure::isSealed(VM& vm)
639 {
640     if (isExtensible())
641         return false;
642
643     materializePropertyMapIfNecessary(vm);
644     if (!propertyTable())
645         return true;
646
647     PropertyTable::iterator end = propertyTable()->end();
648     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
649         if ((iter->attributes & DontDelete) != DontDelete)
650             return false;
651     }
652     return true;
653 }
654
655 // In future we may want to cache this property.
656 bool Structure::isFrozen(VM& vm)
657 {
658     if (isExtensible())
659         return false;
660
661     materializePropertyMapIfNecessary(vm);
662     if (!propertyTable())
663         return true;
664
665     PropertyTable::iterator end = propertyTable()->end();
666     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
667         if (!(iter->attributes & DontDelete))
668             return false;
669         if (!(iter->attributes & (ReadOnly | Accessor)))
670             return false;
671     }
672     return true;
673 }
674
675 Structure* Structure::flattenDictionaryStructure(VM& vm, JSObject* object)
676 {
677     checkOffsetConsistency();
678     ASSERT(isDictionary());
679     if (isUncacheableDictionary()) {
680         ASSERT(propertyTable());
681
682         size_t propertyCount = propertyTable()->size();
683
684         // Holds our values compacted by insertion order.
685         Vector<JSValue> values(propertyCount);
686
687         // Copies out our values from their hashed locations, compacting property table offsets as we go.
688         unsigned i = 0;
689         PropertyTable::iterator end = propertyTable()->end();
690         m_offset = invalidOffset;
691         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter, ++i) {
692             values[i] = object->getDirect(iter->offset);
693             m_offset = iter->offset = offsetForPropertyNumber(i, m_inlineCapacity);
694         }
695         
696         // Copies in our values to their compacted locations.
697         for (unsigned i = 0; i < propertyCount; i++)
698             object->putDirect(vm, offsetForPropertyNumber(i, m_inlineCapacity), values[i]);
699
700         propertyTable()->clearDeletedOffsets();
701         checkOffsetConsistency();
702     }
703
704     m_dictionaryKind = NoneDictionaryKind;
705     return this;
706 }
707
708 PropertyOffset Structure::addPropertyWithoutTransition(VM& vm, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
709 {
710     ASSERT(!enumerationCache());
711
712     if (m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
713         specificValue = 0;
714
715     materializePropertyMapIfNecessaryForPinning(vm);
716     
717     pin();
718
719     return putSpecificValue(vm, propertyName, attributes, specificValue);
720 }
721
722 PropertyOffset Structure::removePropertyWithoutTransition(VM& vm, PropertyName propertyName)
723 {
724     ASSERT(isUncacheableDictionary());
725     ASSERT(!enumerationCache());
726
727     materializePropertyMapIfNecessaryForPinning(vm);
728
729     pin();
730     return remove(propertyName);
731 }
732
733 void Structure::pin()
734 {
735     ASSERT(propertyTable());
736     m_isPinnedPropertyTable = true;
737     clearPreviousID();
738     m_nameInPrevious.clear();
739 }
740
741 void Structure::allocateRareData(VM& vm)
742 {
743     ASSERT(!typeInfo().structureHasRareData());
744     StructureRareData* rareData = StructureRareData::create(vm, previous());
745     m_typeInfo = TypeInfo(typeInfo().type(), typeInfo().flags() | StructureHasRareData);
746     m_previousOrRareData.set(vm, this, rareData);
747 }
748
749 void Structure::cloneRareDataFrom(VM& vm, const Structure* other)
750 {
751     ASSERT(other->typeInfo().structureHasRareData());
752     StructureRareData* newRareData = StructureRareData::clone(vm, other->rareData());
753     m_typeInfo = TypeInfo(typeInfo().type(), typeInfo().flags() | StructureHasRareData);
754     m_previousOrRareData.set(vm, this, newRareData);
755 }
756
757 #if DUMP_PROPERTYMAP_STATS
758
759 struct PropertyMapStatisticsExitLogger {
760     ~PropertyMapStatisticsExitLogger();
761 };
762
763 static PropertyMapStatisticsExitLogger logger;
764
765 PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
766 {
767     dataLogF("\nJSC::PropertyMap statistics\n\n");
768     dataLogF("%d probes\n", numProbes);
769     dataLogF("%d collisions (%.1f%%)\n", numCollisions, 100.0 * numCollisions / numProbes);
770     dataLogF("%d rehashes\n", numRehashes);
771     dataLogF("%d removes\n", numRemoves);
772 }
773
774 #endif
775
776 #if !DO_PROPERTYMAP_CONSTENCY_CHECK
777
778 inline void Structure::checkConsistency()
779 {
780     checkOffsetConsistency();
781 }
782
783 #endif
784
785 PropertyTable* Structure::copyPropertyTable(VM& vm, Structure* owner)
786 {
787     if (!propertyTable())
788         return 0;
789     return PropertyTable::clone(vm, owner, *propertyTable().get());
790 }
791
792 PropertyTable* Structure::copyPropertyTableForPinning(VM& vm, Structure* owner)
793 {
794     if (propertyTable())
795         return PropertyTable::clone(vm, owner, *propertyTable().get());
796     return PropertyTable::create(vm, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
797 }
798
799 PropertyOffset Structure::getConcurrently(VM&, StringImpl* uid, unsigned& attributes, JSCell*& specificValue)
800 {
801     Vector<Structure*, 8> structures;
802     Structure* structure;
803     PropertyTable* table;
804     
805     findStructuresAndMapForMaterialization(structures, structure, table);
806     
807     if (table) {
808         PropertyMapEntry* entry = table->find(uid).first;
809         if (entry) {
810             attributes = entry->attributes;
811             specificValue = entry->specificValue.get();
812             PropertyOffset result = entry->offset;
813             structure->m_lock.unlock();
814             return result;
815         }
816         structure->m_lock.unlock();
817     }
818     
819     for (unsigned i = structures.size(); i--;) {
820         structure = structures[i];
821         if (structure->m_nameInPrevious.get() != uid)
822             continue;
823         
824         attributes = structure->m_attributesInPrevious;
825         specificValue = structure->m_specificValueInPrevious.get();
826         return structure->m_offset;
827     }
828     
829     return invalidOffset;
830 }
831
832 PropertyOffset Structure::get(VM& vm, PropertyName propertyName, unsigned& attributes, JSCell*& specificValue)
833 {
834     ASSERT(!isCompilationThread());
835     ASSERT(structure()->classInfo() == info());
836
837     materializePropertyMapIfNecessary(vm);
838     if (!propertyTable())
839         return invalidOffset;
840
841     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
842     if (!entry)
843         return invalidOffset;
844
845     attributes = entry->attributes;
846     specificValue = entry->specificValue.get();
847     return entry->offset;
848 }
849
850 bool Structure::despecifyFunction(VM& vm, PropertyName propertyName)
851 {
852     materializePropertyMapIfNecessary(vm);
853     if (!propertyTable())
854         return false;
855
856     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
857     if (!entry)
858         return false;
859
860     ASSERT(entry->specificValue);
861     entry->specificValue.clear();
862     return true;
863 }
864
865 void Structure::despecifyAllFunctions(VM& vm)
866 {
867     materializePropertyMapIfNecessary(vm);
868     if (!propertyTable())
869         return;
870
871     PropertyTable::iterator end = propertyTable()->end();
872     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter)
873         iter->specificValue.clear();
874 }
875
876 PropertyOffset Structure::putSpecificValue(VM& vm, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
877 {
878     ConcurrentJITLocker locker(m_lock);
879     
880     ASSERT(!JSC::isValidOffset(get(vm, propertyName)));
881
882     checkConsistency();
883     if (attributes & DontEnum)
884         m_hasNonEnumerableProperties = true;
885
886     StringImpl* rep = propertyName.uid();
887
888     if (!propertyTable())
889         createPropertyMap(locker, vm);
890
891     PropertyOffset newOffset = propertyTable()->nextOffset(m_inlineCapacity);
892
893     propertyTable()->add(PropertyMapEntry(vm, this, rep, newOffset, attributes, specificValue), m_offset, PropertyTable::PropertyOffsetMayChange);
894     
895     checkConsistency();
896     return newOffset;
897 }
898
899 PropertyOffset Structure::remove(PropertyName propertyName)
900 {
901     ConcurrentJITLocker locker(m_lock);
902     
903     checkConsistency();
904
905     StringImpl* rep = propertyName.uid();
906
907     if (!propertyTable())
908         return invalidOffset;
909
910     PropertyTable::find_iterator position = propertyTable()->find(rep);
911     if (!position.first)
912         return invalidOffset;
913
914     PropertyOffset offset = position.first->offset;
915
916     propertyTable()->remove(position);
917     propertyTable()->addDeletedOffset(offset);
918
919     checkConsistency();
920     return offset;
921 }
922
923 void Structure::createPropertyMap(const ConcurrentJITLocker&, VM& vm, unsigned capacity)
924 {
925     ASSERT(!propertyTable());
926
927     checkConsistency();
928     propertyTable().set(vm, this, PropertyTable::create(vm, capacity));
929 }
930
931 void Structure::getPropertyNamesFromStructure(VM& vm, PropertyNameArray& propertyNames, EnumerationMode mode)
932 {
933     materializePropertyMapIfNecessary(vm);
934     if (!propertyTable())
935         return;
936
937     bool knownUnique = !propertyNames.size();
938
939     PropertyTable::iterator end = propertyTable()->end();
940     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
941         ASSERT(m_hasNonEnumerableProperties || !(iter->attributes & DontEnum));
942         if (iter->key->isIdentifier() && (!(iter->attributes & DontEnum) || mode == IncludeDontEnumProperties)) {
943             if (knownUnique)
944                 propertyNames.addKnownUnique(iter->key);
945             else
946                 propertyNames.add(iter->key);
947         }
948     }
949 }
950
951 JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
952 {
953     return prototypeForLookup(codeBlock->globalObject());
954 }
955
956 void Structure::visitChildren(JSCell* cell, SlotVisitor& visitor)
957 {
958     Structure* thisObject = jsCast<Structure*>(cell);
959     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
960     ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());
961
962     JSCell::visitChildren(thisObject, visitor);
963     visitor.append(&thisObject->m_globalObject);
964     if (!thisObject->isObject())
965         thisObject->m_cachedPrototypeChain.clear();
966     else {
967         visitor.append(&thisObject->m_prototype);
968         visitor.append(&thisObject->m_cachedPrototypeChain);
969     }
970     visitor.append(&thisObject->m_previousOrRareData);
971     visitor.append(&thisObject->m_specificValueInPrevious);
972
973     if (thisObject->m_isPinnedPropertyTable) {
974         ASSERT(thisObject->m_propertyTableUnsafe);
975         visitor.append(&thisObject->m_propertyTableUnsafe);
976     } else if (thisObject->m_propertyTableUnsafe)
977         thisObject->m_propertyTableUnsafe.clear();
978 }
979
980 bool Structure::prototypeChainMayInterceptStoreTo(VM& vm, PropertyName propertyName)
981 {
982     unsigned i = propertyName.asIndex();
983     if (i != PropertyName::NotAnIndex)
984         return anyObjectInChainMayInterceptIndexedAccesses();
985     
986     for (Structure* current = this; ;) {
987         JSValue prototype = current->storedPrototype();
988         if (prototype.isNull())
989             return false;
990         
991         current = prototype.asCell()->structure();
992         
993         unsigned attributes;
994         JSCell* specificValue;
995         PropertyOffset offset = current->get(vm, propertyName, attributes, specificValue);
996         if (!JSC::isValidOffset(offset))
997             continue;
998         
999         if (attributes & (ReadOnly | Accessor))
1000             return true;
1001         
1002         return false;
1003     }
1004 }
1005
1006 void Structure::dump(PrintStream& out) const
1007 {
1008     out.print(RawPointer(this), ":[", classInfo()->className, ", {");
1009     
1010     Vector<Structure*, 8> structures;
1011     Structure* structure;
1012     PropertyTable* table;
1013     
1014     const_cast<Structure*>(this)->findStructuresAndMapForMaterialization(
1015         structures, structure, table);
1016     
1017     CommaPrinter comma;
1018     
1019     if (table) {
1020         PropertyTable::iterator iter = table->begin();
1021         PropertyTable::iterator end = table->end();
1022         for (; iter != end; ++iter)
1023             out.print(comma, iter->key, ":", static_cast<int>(iter->offset));
1024         
1025         structure->m_lock.unlock();
1026     }
1027     
1028     for (unsigned i = structures.size(); i--;) {
1029         Structure* structure = structures[i];
1030         if (!structure->m_nameInPrevious)
1031             continue;
1032         out.print(comma, structure->m_nameInPrevious.get(), ":", static_cast<int>(structure->m_offset));
1033     }
1034     
1035     out.print("}, ", IndexingTypeDump(indexingType()));
1036     
1037     if (m_prototype.get().isCell())
1038         out.print(", Proto:", RawPointer(m_prototype.get().asCell()));
1039     
1040     out.print("]");
1041 }
1042
1043 void Structure::dumpInContext(PrintStream& out, DumpContext* context) const
1044 {
1045     if (context)
1046         context->structures.dumpBrief(this, out);
1047     else
1048         dump(out);
1049 }
1050
1051 void Structure::dumpBrief(PrintStream& out, const CString& string) const
1052 {
1053     out.print("%", string, ":", classInfo()->className);
1054 }
1055
1056 void Structure::dumpContextHeader(PrintStream& out)
1057 {
1058     out.print("Structures:");
1059 }
1060
1061 #if DO_PROPERTYMAP_CONSTENCY_CHECK
1062
1063 void PropertyTable::checkConsistency()
1064 {
1065     checkOffsetConsistency();
1066     ASSERT(m_indexSize >= PropertyTable::MinimumTableSize);
1067     ASSERT(m_indexMask);
1068     ASSERT(m_indexSize == m_indexMask + 1);
1069     ASSERT(!(m_indexSize & m_indexMask));
1070
1071     ASSERT(m_keyCount <= m_indexSize / 2);
1072     ASSERT(m_keyCount + m_deletedCount <= m_indexSize / 2);
1073     ASSERT(m_deletedCount <= m_indexSize / 4);
1074
1075     unsigned indexCount = 0;
1076     unsigned deletedIndexCount = 0;
1077     for (unsigned a = 0; a != m_indexSize; ++a) {
1078         unsigned entryIndex = m_index[a];
1079         if (entryIndex == PropertyTable::EmptyEntryIndex)
1080             continue;
1081         if (entryIndex == deletedEntryIndex()) {
1082             ++deletedIndexCount;
1083             continue;
1084         }
1085         ASSERT(entryIndex < deletedEntryIndex());
1086         ASSERT(entryIndex - 1 <= usedCount());
1087         ++indexCount;
1088
1089         for (unsigned b = a + 1; b != m_indexSize; ++b)
1090             ASSERT(m_index[b] != entryIndex);
1091     }
1092     ASSERT(indexCount == m_keyCount);
1093     ASSERT(deletedIndexCount == m_deletedCount);
1094
1095     ASSERT(!table()[deletedEntryIndex() - 1].key);
1096
1097     unsigned nonEmptyEntryCount = 0;
1098     for (unsigned c = 0; c < usedCount(); ++c) {
1099         StringImpl* rep = table()[c].key;
1100         if (rep == PROPERTY_MAP_DELETED_ENTRY_KEY)
1101             continue;
1102         ++nonEmptyEntryCount;
1103         unsigned i = rep->existingHash();
1104         unsigned k = 0;
1105         unsigned entryIndex;
1106         while (1) {
1107             entryIndex = m_index[i & m_indexMask];
1108             ASSERT(entryIndex != PropertyTable::EmptyEntryIndex);
1109             if (rep == table()[entryIndex - 1].key)
1110                 break;
1111             if (k == 0)
1112                 k = 1 | doubleHash(rep->existingHash());
1113             i += k;
1114         }
1115         ASSERT(entryIndex == c + 1);
1116     }
1117
1118     ASSERT(nonEmptyEntryCount == m_keyCount);
1119 }
1120
1121 void Structure::checkConsistency()
1122 {
1123     if (!propertyTable())
1124         return;
1125
1126     if (!m_hasNonEnumerableProperties) {
1127         PropertyTable::iterator end = propertyTable()->end();
1128         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
1129             ASSERT(!(iter->attributes & DontEnum));
1130         }
1131     }
1132
1133     propertyTable()->checkConsistency();
1134 }
1135
1136 #endif // DO_PROPERTYMAP_CONSTENCY_CHECK
1137
1138 } // namespace JSC