2011-04-25 Geoffrey Garen <ggaren@apple.com>
[WebKit-https.git] / Source / JavaScriptCore / runtime / Structure.cpp
1 /*
2  * Copyright (C) 2008, 2009 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 "Identifier.h"
30 #include "JSObject.h"
31 #include "JSPropertyNameIterator.h"
32 #include "Lookup.h"
33 #include "PropertyNameArray.h"
34 #include "StructureChain.h"
35 #include <wtf/RefCountedLeakCounter.h>
36 #include <wtf/RefPtr.h>
37
38 #if ENABLE(JSC_MULTIPLE_THREADS)
39 #include <wtf/Threading.h>
40 #endif
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()->contains(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::remove(Structure* structure)
87 {
88     if (isUsingSingleSlot()) {
89         // If more than one transition had been added, then we wouldn't be in
90         // single slot mode (even despecifying a from a specific value triggers
91         // map mode).
92         // As such, the passed structure *must* be the existing transition.
93         ASSERT(singleTransition() == structure);
94         clearSingleTransition();
95     } else {
96         // Check whether a mapping exists for structure's key, and whether the
97         // entry is structure (the latter check may fail if we initially had a
98         // transition with a specific value, and this has been despecified).
99         TransitionMap::iterator entry = map()->find(make_pair(structure->m_nameInPrevious, structure->m_attributesInPrevious));
100         if (entry != map()->end() && structure == entry.get().second)
101             map()->remove(entry);
102     }
103 }
104
105 inline void StructureTransitionTable::add(JSGlobalData& globalData, Structure* structure)
106 {
107     if (isUsingSingleSlot()) {
108         Structure* existingTransition = singleTransition();
109
110         // This handles the first transition being added.
111         if (!existingTransition) {
112             setSingleTransition(globalData, structure);
113             return;
114         }
115
116         // This handles the second transition being added
117         // (or the first transition being despecified!)
118         setMap(new TransitionMap());
119         add(globalData, existingTransition);
120     }
121
122     // Add the structure to the map.
123     std::pair<TransitionMap::iterator, bool> result = map()->add(globalData, make_pair(structure->m_nameInPrevious, structure->m_attributesInPrevious), structure);
124     if (!result.second) {
125         // There already is an entry! - we should only hit this when despecifying.
126         ASSERT(result.first.get().second->m_specificValueInPrevious);
127         ASSERT(!structure->m_specificValueInPrevious);
128         map()->set(result.first, structure);
129     }
130 }
131
132 void Structure::dumpStatistics()
133 {
134 #if DUMP_STRUCTURE_ID_STATISTICS
135     unsigned numberLeaf = 0;
136     unsigned numberUsingSingleSlot = 0;
137     unsigned numberSingletons = 0;
138     unsigned numberWithPropertyMaps = 0;
139     unsigned totalPropertyMapsSize = 0;
140
141     HashSet<Structure*>::const_iterator end = liveStructureSet.end();
142     for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
143         Structure* structure = *it;
144
145         switch (structure->m_transitionTable.size()) {
146             case 0:
147                 ++numberLeaf;
148                if (!structure->m_previous)
149                     ++numberSingletons;
150                 break;
151
152             case 1:
153                 ++numberUsingSingleSlot;
154                 break;
155         }
156
157         if (structure->m_propertyTable) {
158             ++numberWithPropertyMaps;
159             totalPropertyMapsSize += structure->m_propertyTable->sizeInMemory();
160         }
161     }
162
163     printf("Number of live Structures: %d\n", liveStructureSet.size());
164     printf("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
165     printf("Number of Structures that are leaf nodes: %d\n", numberLeaf);
166     printf("Number of Structures that singletons: %d\n", numberSingletons);
167     printf("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);
168
169     printf("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
170     printf("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
171     printf("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
172 #else
173     printf("Dumping Structure statistics is not enabled.\n");
174 #endif
175 }
176
177 Structure::Structure(JSGlobalData& globalData, JSValue prototype, const TypeInfo& typeInfo, unsigned anonymousSlotCount, const ClassInfo* classInfo)
178     : JSCell(globalData, globalData.structureStructure.get())
179     , m_typeInfo(typeInfo)
180     , m_prototype(globalData, this, prototype)
181     , m_classInfo(classInfo)
182     , m_propertyStorageCapacity(typeInfo.isFinal() ? JSFinalObject_inlineStorageCapacity : JSNonFinalObject_inlineStorageCapacity)
183     , m_offset(noOffset)
184     , m_dictionaryKind(NoneDictionaryKind)
185     , m_isPinnedPropertyTable(false)
186     , m_hasGetterSetterProperties(false)
187     , m_hasNonEnumerableProperties(false)
188     , m_attributesInPrevious(0)
189     , m_specificFunctionThrashCount(0)
190     , m_anonymousSlotCount(anonymousSlotCount)
191     , m_preventExtensions(false)
192     , m_didTransition(false)
193 {
194     ASSERT(m_prototype);
195     ASSERT(m_prototype.isObject() || m_prototype.isNull());
196 }
197
198 const ClassInfo Structure::s_info = { "Structure", 0, 0, 0 };
199
200 Structure::Structure(JSGlobalData& globalData)
201     : JSCell(globalData, this)
202     , m_typeInfo(CompoundType, OverridesVisitChildren)
203     , m_prototype(globalData, this, jsNull())
204     , m_classInfo(&s_info)
205     , m_propertyStorageCapacity(0)
206     , m_offset(noOffset)
207     , m_dictionaryKind(NoneDictionaryKind)
208     , m_isPinnedPropertyTable(false)
209     , m_hasGetterSetterProperties(false)
210     , m_hasNonEnumerableProperties(false)
211     , m_attributesInPrevious(0)
212     , m_specificFunctionThrashCount(0)
213     , m_anonymousSlotCount(0)
214     , m_preventExtensions(false)
215     , m_didTransition(false)
216 {
217     ASSERT(m_prototype);
218     ASSERT(m_prototype.isNull());
219     ASSERT(!globalData.structureStructure);
220 }
221
222 Structure::Structure(JSGlobalData& globalData, const Structure* previous)
223     : JSCell(globalData, globalData.structureStructure.get())
224     , m_typeInfo(previous->typeInfo())
225     , m_prototype(globalData, this, previous->storedPrototype())
226     , m_classInfo(previous->m_classInfo)
227     , m_propertyStorageCapacity(previous->m_propertyStorageCapacity)
228     , m_offset(noOffset)
229     , m_dictionaryKind(NoneDictionaryKind)
230     , m_isPinnedPropertyTable(false)
231     , m_hasGetterSetterProperties(previous->m_hasGetterSetterProperties)
232     , m_hasNonEnumerableProperties(previous->m_hasNonEnumerableProperties)
233     , m_attributesInPrevious(0)
234     , m_specificFunctionThrashCount(previous->m_specificFunctionThrashCount)
235     , m_anonymousSlotCount(previous->anonymousSlotCount())
236     , m_preventExtensions(previous->m_preventExtensions)
237     , m_didTransition(true)
238 {
239     ASSERT(m_prototype);
240     ASSERT(m_prototype.isObject() || m_prototype.isNull());
241 }
242
243 Structure::~Structure()
244 {
245 }
246
247 void Structure::materializePropertyMap(JSGlobalData& globalData)
248 {
249     ASSERT(!m_propertyTable);
250
251     Vector<Structure*, 8> structures;
252     structures.append(this);
253
254     Structure* structure = this;
255
256     // Search for the last Structure with a property table.
257     while ((structure = structure->previousID())) {
258         if (structure->m_isPinnedPropertyTable) {
259             ASSERT(structure->m_propertyTable);
260             ASSERT(!structure->m_previous);
261
262             m_propertyTable = structure->m_propertyTable->copy(globalData, 0, m_offset + 1);
263             break;
264         }
265
266         structures.append(structure);
267     }
268
269     if (!m_propertyTable)
270         createPropertyMap(m_offset + 1);
271
272     for (ptrdiff_t i = structures.size() - 2; i >= 0; --i) {
273         structure = structures[i];
274         PropertyMapEntry entry(globalData, this, structure->m_nameInPrevious.get(), m_anonymousSlotCount + structure->m_offset, structure->m_attributesInPrevious, structure->m_specificValueInPrevious.get());
275         m_propertyTable->add(entry);
276     }
277 }
278
279 void Structure::growPropertyStorageCapacity()
280 {
281     if (isUsingInlineStorage())
282         m_propertyStorageCapacity = JSObject::baseExternalStorageCapacity;
283     else
284         m_propertyStorageCapacity *= 2;
285 }
286
287 void Structure::despecifyDictionaryFunction(JSGlobalData& globalData, const Identifier& propertyName)
288 {
289     StringImpl* rep = propertyName.impl();
290
291     materializePropertyMapIfNecessary(globalData);
292
293     ASSERT(isDictionary());
294     ASSERT(m_propertyTable);
295
296     PropertyMapEntry* entry = m_propertyTable->find(rep).first;
297     ASSERT(entry);
298     entry->specificValue.clear();
299 }
300
301 Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, const Identifier& propertyName, unsigned attributes, JSCell* specificValue, size_t& offset)
302 {
303     ASSERT(!structure->isDictionary());
304     ASSERT(structure->typeInfo().type() == ObjectType);
305
306     if (Structure* existingTransition = structure->m_transitionTable.get(propertyName.impl(), attributes)) {
307         JSCell* specificValueInPrevious = existingTransition->m_specificValueInPrevious.get();
308         if (specificValueInPrevious && specificValueInPrevious != specificValue)
309             return 0;
310         ASSERT(existingTransition->m_offset != noOffset);
311         offset = existingTransition->m_offset + existingTransition->m_anonymousSlotCount;
312         ASSERT(offset >= structure->m_anonymousSlotCount);
313         ASSERT(structure->m_anonymousSlotCount == existingTransition->m_anonymousSlotCount);
314         return existingTransition;
315     }
316
317     return 0;
318 }
319
320 Structure* Structure::addPropertyTransition(JSGlobalData& globalData, Structure* structure, const Identifier& propertyName, unsigned attributes, JSCell* specificValue, size_t& offset)
321 {
322     // If we have a specific function, we may have got to this point if there is
323     // already a transition with the correct property name and attributes, but
324     // specialized to a different function.  In this case we just want to give up
325     // and despecialize the transition.
326     // In this case we clear the value of specificFunction which will result
327     // in us adding a non-specific transition, and any subsequent lookup in
328     // Structure::addPropertyTransitionToExistingStructure will just use that.
329     if (specificValue && structure->m_transitionTable.contains(propertyName.impl(), attributes))
330         specificValue = 0;
331
332     ASSERT(!structure->isDictionary());
333     ASSERT(structure->typeInfo().type() == ObjectType);
334     ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, specificValue, offset));
335     
336     if (structure->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
337         specificValue = 0;
338
339     if (structure->transitionCount() > s_maxTransitionLength) {
340         Structure* transition = toCacheableDictionaryTransition(globalData, structure);
341         ASSERT(structure != transition);
342         offset = transition->putSpecificValue(globalData, propertyName, attributes, specificValue);
343         ASSERT(offset >= structure->m_anonymousSlotCount);
344         ASSERT(structure->m_anonymousSlotCount == transition->m_anonymousSlotCount);
345         if (transition->propertyStorageSize() > transition->propertyStorageCapacity())
346             transition->growPropertyStorageCapacity();
347         return transition;
348     }
349
350     Structure* transition = create(globalData, structure);
351
352     transition->m_cachedPrototypeChain.set(globalData, transition, structure->m_cachedPrototypeChain.get());
353     transition->m_previous.set(globalData, transition, structure);
354     transition->m_nameInPrevious = propertyName.impl();
355     transition->m_attributesInPrevious = attributes;
356     transition->m_specificValueInPrevious.set(globalData, transition, specificValue);
357
358     if (structure->m_propertyTable) {
359         if (structure->m_isPinnedPropertyTable)
360             transition->m_propertyTable = structure->m_propertyTable->copy(globalData, 0, structure->m_propertyTable->size() + 1);
361         else
362             transition->m_propertyTable = structure->m_propertyTable.release();
363     } else {
364         if (structure->m_previous)
365             transition->materializePropertyMap(globalData);
366         else
367             transition->createPropertyMap();
368     }
369
370     offset = transition->putSpecificValue(globalData, propertyName, attributes, specificValue);
371     ASSERT(offset >= structure->m_anonymousSlotCount);
372     ASSERT(structure->m_anonymousSlotCount == transition->m_anonymousSlotCount);
373     if (transition->propertyStorageSize() > transition->propertyStorageCapacity())
374         transition->growPropertyStorageCapacity();
375
376     transition->m_offset = offset - structure->m_anonymousSlotCount;
377     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
378     structure->m_transitionTable.add(globalData, transition);
379     return transition;
380 }
381
382 Structure* Structure::removePropertyTransition(JSGlobalData& globalData, Structure* structure, const Identifier& propertyName, size_t& offset)
383 {
384     ASSERT(!structure->isUncacheableDictionary());
385
386     Structure* transition = toUncacheableDictionaryTransition(globalData, structure);
387
388     offset = transition->remove(propertyName);
389     ASSERT(offset >= structure->m_anonymousSlotCount);
390     ASSERT(structure->m_anonymousSlotCount == transition->m_anonymousSlotCount);
391
392     return transition;
393 }
394
395 Structure* Structure::changePrototypeTransition(JSGlobalData& globalData, Structure* structure, JSValue prototype)
396 {
397     Structure* transition = create(globalData, structure);
398
399     transition->m_prototype.set(globalData, transition, prototype);
400
401     // Don't set m_offset, as one can not transition to this.
402
403     structure->materializePropertyMapIfNecessary(globalData);
404     transition->m_propertyTable = structure->copyPropertyTable(globalData, transition);
405     transition->m_isPinnedPropertyTable = true;
406     
407     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
408     return transition;
409 }
410
411 Structure* Structure::despecifyFunctionTransition(JSGlobalData& globalData, Structure* structure, const Identifier& replaceFunction)
412 {
413     ASSERT(structure->m_specificFunctionThrashCount < maxSpecificFunctionThrashCount);
414     Structure* transition = create(globalData, structure);
415
416     ++transition->m_specificFunctionThrashCount;
417
418     // Don't set m_offset, as one can not transition to this.
419
420     structure->materializePropertyMapIfNecessary(globalData);
421     transition->m_propertyTable = structure->copyPropertyTable(globalData, transition);
422     transition->m_isPinnedPropertyTable = true;
423
424     if (transition->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
425         transition->despecifyAllFunctions(globalData);
426     else {
427         bool removed = transition->despecifyFunction(globalData, replaceFunction);
428         ASSERT_UNUSED(removed, removed);
429     }
430     
431     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
432     return transition;
433 }
434
435 Structure* Structure::getterSetterTransition(JSGlobalData& globalData, Structure* structure)
436 {
437     Structure* transition = create(globalData, structure);
438
439     // Don't set m_offset, as one can not transition to this.
440
441     structure->materializePropertyMapIfNecessary(globalData);
442     transition->m_propertyTable = structure->copyPropertyTable(globalData, transition);
443     transition->m_isPinnedPropertyTable = true;
444     
445     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
446     return transition;
447 }
448
449 Structure* Structure::toDictionaryTransition(JSGlobalData& globalData, Structure* structure, DictionaryKind kind)
450 {
451     ASSERT(!structure->isUncacheableDictionary());
452     
453     Structure* transition = create(globalData, structure);
454
455     structure->materializePropertyMapIfNecessary(globalData);
456     transition->m_propertyTable = structure->copyPropertyTable(globalData, transition);
457     transition->m_isPinnedPropertyTable = true;
458     transition->m_dictionaryKind = kind;
459     
460     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
461     return transition;
462 }
463
464 Structure* Structure::toCacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure)
465 {
466     return toDictionaryTransition(globalData, structure, CachedDictionaryKind);
467 }
468
469 Structure* Structure::toUncacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure)
470 {
471     return toDictionaryTransition(globalData, structure, UncachedDictionaryKind);
472 }
473
474 // In future we may want to cache this transition.
475 Structure* Structure::sealTransition(JSGlobalData& globalData, Structure* structure)
476 {
477     Structure* transition = preventExtensionsTransition(globalData, structure);
478
479     if (transition->m_propertyTable) {
480         PropertyTable::iterator end = transition->m_propertyTable->end();
481         for (PropertyTable::iterator iter = transition->m_propertyTable->begin(); iter != end; ++iter)
482             iter->attributes |= DontDelete;
483     }
484
485     return transition;
486 }
487
488 // In future we may want to cache this transition.
489 Structure* Structure::freezeTransition(JSGlobalData& globalData, Structure* structure)
490 {
491     Structure* transition = preventExtensionsTransition(globalData, structure);
492
493     if (transition->m_propertyTable) {
494         PropertyTable::iterator end = transition->m_propertyTable->end();
495         for (PropertyTable::iterator iter = transition->m_propertyTable->begin(); iter != end; ++iter)
496             iter->attributes |= (DontDelete | ReadOnly);
497     }
498
499     return transition;
500 }
501
502 // In future we may want to cache this transition.
503 Structure* Structure::preventExtensionsTransition(JSGlobalData& globalData, Structure* structure)
504 {
505     Structure* transition = create(globalData, structure);
506
507     // Don't set m_offset, as one can not transition to this.
508
509     structure->materializePropertyMapIfNecessary(globalData);
510     transition->m_propertyTable = structure->copyPropertyTable(globalData, transition);
511     transition->m_isPinnedPropertyTable = true;
512     transition->m_preventExtensions = true;
513
514     ASSERT(structure->anonymousSlotCount() == transition->anonymousSlotCount());
515     return transition;
516 }
517
518 // In future we may want to cache this property.
519 bool Structure::isSealed(JSGlobalData& globalData)
520 {
521     if (isExtensible())
522         return false;
523
524     materializePropertyMapIfNecessary(globalData);
525     if (!m_propertyTable)
526         return true;
527
528     PropertyTable::iterator end = m_propertyTable->end();
529     for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter) {
530         if ((iter->attributes & DontDelete) != DontDelete)
531             return false;
532     }
533     return true;
534 }
535
536 // In future we may want to cache this property.
537 bool Structure::isFrozen(JSGlobalData& globalData)
538 {
539     if (isExtensible())
540         return false;
541
542     materializePropertyMapIfNecessary(globalData);
543     if (!m_propertyTable)
544         return true;
545
546     PropertyTable::iterator end = m_propertyTable->end();
547     for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter) {
548         if ((iter->attributes & (DontDelete | ReadOnly)) != (DontDelete | ReadOnly))
549             return false;
550     }
551     return true;
552 }
553
554 Structure* Structure::flattenDictionaryStructure(JSGlobalData& globalData, JSObject* object)
555 {
556     ASSERT(isDictionary());
557     if (isUncacheableDictionary()) {
558         ASSERT(m_propertyTable);
559
560         unsigned anonymousSlotCount = m_anonymousSlotCount;
561         size_t propertyCount = m_propertyTable->size();
562         Vector<JSValue> values(propertyCount);
563
564         unsigned i = 0;
565         PropertyTable::iterator end = m_propertyTable->end();
566         for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter, ++i) {
567             values[i] = object->getDirectOffset(iter->offset);
568             // Update property table to have the new property offsets
569             iter->offset = anonymousSlotCount + i;
570         }
571         
572         // Copy the original property values into their final locations
573         for (unsigned i = 0; i < propertyCount; i++)
574             object->putDirectOffset(globalData, anonymousSlotCount + i, values[i]);
575
576         m_propertyTable->clearDeletedOffsets();
577     }
578
579     m_dictionaryKind = NoneDictionaryKind;
580     return this;
581 }
582
583 size_t Structure::addPropertyWithoutTransition(JSGlobalData& globalData, const Identifier& propertyName, unsigned attributes, JSCell* specificValue)
584 {
585     ASSERT(!m_enumerationCache);
586
587     if (m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
588         specificValue = 0;
589
590     materializePropertyMapIfNecessary(globalData);
591
592     m_isPinnedPropertyTable = true;
593
594     size_t offset = putSpecificValue(globalData, propertyName, attributes, specificValue);
595     ASSERT(offset >= m_anonymousSlotCount);
596     if (propertyStorageSize() > propertyStorageCapacity())
597         growPropertyStorageCapacity();
598     return offset;
599 }
600
601 size_t Structure::removePropertyWithoutTransition(JSGlobalData& globalData, const Identifier& propertyName)
602 {
603     ASSERT(isUncacheableDictionary());
604     ASSERT(!m_enumerationCache);
605
606     materializePropertyMapIfNecessary(globalData);
607
608     m_isPinnedPropertyTable = true;
609     size_t offset = remove(propertyName);
610     ASSERT(offset >= m_anonymousSlotCount);
611     return offset;
612 }
613
614 #if DUMP_PROPERTYMAP_STATS
615
616 struct PropertyMapStatisticsExitLogger {
617     ~PropertyMapStatisticsExitLogger();
618 };
619
620 static PropertyMapStatisticsExitLogger logger;
621
622 PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
623 {
624     printf("\nJSC::PropertyMap statistics\n\n");
625     printf("%d probes\n", numProbes);
626     printf("%d collisions (%.1f%%)\n", numCollisions, 100.0 * numCollisions / numProbes);
627     printf("%d rehashes\n", numRehashes);
628     printf("%d removes\n", numRemoves);
629 }
630
631 #endif
632
633 #if !DO_PROPERTYMAP_CONSTENCY_CHECK
634
635 inline void Structure::checkConsistency()
636 {
637 }
638
639 #endif
640
641 PassOwnPtr<PropertyTable> Structure::copyPropertyTable(JSGlobalData& globalData, Structure* owner)
642 {
643     return adoptPtr(m_propertyTable ? new PropertyTable(globalData, owner, *m_propertyTable) : 0);
644 }
645
646 size_t Structure::get(JSGlobalData& globalData, StringImpl* propertyName, unsigned& attributes, JSCell*& specificValue)
647 {
648     materializePropertyMapIfNecessary(globalData);
649     if (!m_propertyTable)
650         return WTF::notFound;
651
652     PropertyMapEntry* entry = m_propertyTable->find(propertyName).first;
653     if (!entry)
654         return WTF::notFound;
655
656     attributes = entry->attributes;
657     specificValue = entry->specificValue.get();
658     ASSERT(entry->offset >= m_anonymousSlotCount);
659     return entry->offset;
660 }
661
662 bool Structure::despecifyFunction(JSGlobalData& globalData, const Identifier& propertyName)
663 {
664     materializePropertyMapIfNecessary(globalData);
665     if (!m_propertyTable)
666         return false;
667
668     ASSERT(!propertyName.isNull());
669     PropertyMapEntry* entry = m_propertyTable->find(propertyName.impl()).first;
670     if (!entry)
671         return false;
672
673     ASSERT(entry->specificValue);
674     entry->specificValue.clear();
675     return true;
676 }
677
678 void Structure::despecifyAllFunctions(JSGlobalData& globalData)
679 {
680     materializePropertyMapIfNecessary(globalData);
681     if (!m_propertyTable)
682         return;
683
684     PropertyTable::iterator end = m_propertyTable->end();
685     for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter)
686         iter->specificValue.clear();
687 }
688
689 size_t Structure::putSpecificValue(JSGlobalData& globalData, const Identifier& propertyName, unsigned attributes, JSCell* specificValue)
690 {
691     ASSERT(!propertyName.isNull());
692     ASSERT(get(globalData, propertyName) == notFound);
693
694     checkConsistency();
695     if (attributes & DontEnum)
696         m_hasNonEnumerableProperties = true;
697
698     StringImpl* rep = propertyName.impl();
699
700     if (!m_propertyTable)
701         createPropertyMap();
702
703     unsigned newOffset;
704
705     if (m_propertyTable->hasDeletedOffset())
706         newOffset = m_propertyTable->getDeletedOffset();
707     else
708         newOffset = m_propertyTable->size() + m_anonymousSlotCount;
709     ASSERT(newOffset >= m_anonymousSlotCount);
710
711     m_propertyTable->add(PropertyMapEntry(globalData, this, rep, newOffset, attributes, specificValue));
712
713     checkConsistency();
714     return newOffset;
715 }
716
717 size_t Structure::remove(const Identifier& propertyName)
718 {
719     ASSERT(!propertyName.isNull());
720
721     checkConsistency();
722
723     StringImpl* rep = propertyName.impl();
724
725     if (!m_propertyTable)
726         return notFound;
727
728     PropertyTable::find_iterator position = m_propertyTable->find(rep);
729     if (!position.first)
730         return notFound;
731
732     size_t offset = position.first->offset;
733     ASSERT(offset >= m_anonymousSlotCount);
734
735     m_propertyTable->remove(position);
736     m_propertyTable->addDeletedOffset(offset);
737
738     checkConsistency();
739     return offset;
740 }
741
742 void Structure::createPropertyMap(unsigned capacity)
743 {
744     ASSERT(!m_propertyTable);
745
746     checkConsistency();
747     m_propertyTable = adoptPtr(new PropertyTable(capacity));
748     checkConsistency();
749 }
750
751 void Structure::getPropertyNames(JSGlobalData& globalData, PropertyNameArray& propertyNames, EnumerationMode mode)
752 {
753     materializePropertyMapIfNecessary(globalData);
754     if (!m_propertyTable)
755         return;
756
757     bool knownUnique = !propertyNames.size();
758
759     PropertyTable::iterator end = m_propertyTable->end();
760     for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter) {
761         ASSERT(m_hasNonEnumerableProperties || !(iter->attributes & DontEnum));
762         if (!(iter->attributes & DontEnum) || (mode == IncludeDontEnumProperties)) {
763             if (knownUnique)
764                 propertyNames.addKnownUnique(iter->key);
765             else
766                 propertyNames.add(iter->key);
767         }
768     }
769 }
770
771 void Structure::visitChildren(SlotVisitor& visitor)
772 {
773     JSCell::visitChildren(visitor);
774     if (m_prototype)
775         visitor.append(&m_prototype);
776     if (m_cachedPrototypeChain)
777         visitor.append(&m_cachedPrototypeChain);
778     if (m_previous)
779         visitor.append(&m_previous);
780     if (m_specificValueInPrevious)
781         visitor.append(&m_specificValueInPrevious);
782     if (m_enumerationCache)
783         visitor.append(&m_enumerationCache);
784     if (m_propertyTable) {
785         PropertyTable::iterator end = m_propertyTable->end();
786         for (PropertyTable::iterator ptr = m_propertyTable->begin(); ptr != end; ++ptr) {
787             if (ptr->specificValue)
788                 visitor.append(&ptr->specificValue);
789         }
790     }
791 }
792
793 #if DO_PROPERTYMAP_CONSTENCY_CHECK
794
795 void PropertyTable::checkConsistency()
796 {
797     ASSERT(m_indexSize >= PropertyTable::MinimumTableSize);
798     ASSERT(m_indexMask);
799     ASSERT(m_indexSize == m_indexMask + 1);
800     ASSERT(!(m_indexSize & m_indexMask));
801
802     ASSERT(m_keyCount <= m_indexSize / 2);
803     ASSERT(m_keyCount + m_deletedCount <= m_indexSize / 2);
804     ASSERT(m_deletedCount <= m_indexSize / 4);
805
806     unsigned indexCount = 0;
807     unsigned deletedIndexCount = 0;
808     for (unsigned a = 0; a != m_indexSize; ++a) {
809         unsigned entryIndex = m_index[a];
810         if (entryIndex == PropertyTable::EmptyEntryIndex)
811             continue;
812         if (entryIndex == deletedEntryIndex()) {
813             ++deletedIndexCount;
814             continue;
815         }
816         ASSERT(entryIndex < deletedEntryIndex());
817         ASSERT(entryIndex - 1 <= usedCount());
818         ++indexCount;
819
820         for (unsigned b = a + 1; b != m_indexSize; ++b)
821             ASSERT(m_index[b] != entryIndex);
822     }
823     ASSERT(indexCount == m_keyCount);
824     ASSERT(deletedIndexCount == m_deletedCount);
825
826     ASSERT(!table()[deletedEntryIndex() - 1].key);
827
828     unsigned nonEmptyEntryCount = 0;
829     for (unsigned c = 0; c < usedCount(); ++c) {
830         StringImpl* rep = table()[c].key;
831         if (rep == PROPERTY_MAP_DELETED_ENTRY_KEY)
832             continue;
833         ++nonEmptyEntryCount;
834         unsigned i = rep->existingHash();
835         unsigned k = 0;
836         unsigned entryIndex;
837         while (1) {
838             entryIndex = m_index[i & m_indexMask];
839             ASSERT(entryIndex != PropertyTable::EmptyEntryIndex);
840             if (rep == table()[entryIndex - 1].key)
841                 break;
842             if (k == 0)
843                 k = 1 | doubleHash(rep->existingHash());
844             i += k;
845         }
846         ASSERT(entryIndex == c + 1);
847     }
848
849     ASSERT(nonEmptyEntryCount == m_keyCount);
850 }
851
852 void Structure::checkConsistency()
853 {
854     if (!m_propertyTable)
855         return;
856
857     if (!m_hasNonEnumerableProperties) {
858         PropertyTable::iterator end = m_propertyTable->end();
859         for (PropertyTable::iterator iter = m_propertyTable->begin(); iter != end; ++iter) {
860             ASSERT(!(iter->attributes & DontEnum));
861             ASSERT(iter->offset >= m_anonymousSlotCount);
862         }
863     }
864
865     m_propertyTable->checkConsistency();
866 }
867
868 #endif // DO_PROPERTYMAP_CONSTENCY_CHECK
869
870 } // namespace JSC