Source file src/internal/runtime/maps/table.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package maps implements Go's builtin map type.
     6  package maps
     7  
     8  import (
     9  	"internal/abi"
    10  	"internal/goarch"
    11  	"unsafe"
    12  )
    13  
    14  // Maximum size of a table before it is split at the directory level.
    15  //
    16  // TODO: Completely made up value. This should be tuned for performance vs grow
    17  // latency.
    18  // TODO: This should likely be based on byte size, as copying costs will
    19  // dominate grow latency for large objects.
    20  const maxTableCapacity = 1024
    21  
    22  // Ensure the max capacity fits in uint16, used for capacity and growthLeft
    23  // below.
    24  var _ = uint16(maxTableCapacity)
    25  
    26  // table is a Swiss table hash table structure.
    27  //
    28  // Each table is a complete hash table implementation.
    29  //
    30  // Map uses one or more tables to store entries. Extendible hashing (hash
    31  // prefix) is used to select the table to use for a specific key. Using
    32  // multiple tables enables incremental growth by growing only one table at a
    33  // time.
    34  type table struct {
    35  	// The number of filled slots (i.e. the number of elements in the table).
    36  	used uint16
    37  
    38  	// The total number of slots (always 2^N). Equal to
    39  	// `(groups.lengthMask+1)*abi.SwissMapGroupSlots`.
    40  	capacity uint16
    41  
    42  	// The number of slots we can still fill without needing to rehash.
    43  	//
    44  	// We rehash when used + tombstones > loadFactor*capacity, including
    45  	// tombstones so the table doesn't overfill with tombstones. This field
    46  	// counts down remaining empty slots before the next rehash.
    47  	growthLeft uint16
    48  
    49  	// The number of bits used by directory lookups above this table. Note
    50  	// that this may be less then globalDepth, if the directory has grown
    51  	// but this table has not yet been split.
    52  	localDepth uint8
    53  
    54  	// Index of this table in the Map directory. This is the index of the
    55  	// _first_ location in the directory. The table may occur in multiple
    56  	// sequential indicies.
    57  	//
    58  	// index is -1 if the table is stale (no longer installed in the
    59  	// directory).
    60  	index int
    61  
    62  	// groups is an array of slot groups. Each group holds abi.SwissMapGroupSlots
    63  	// key/elem slots and their control bytes. A table has a fixed size
    64  	// groups array. The table is replaced (in rehash) when more space is
    65  	// required.
    66  	//
    67  	// TODO(prattmic): keys and elements are interleaved to maximize
    68  	// locality, but it comes at the expense of wasted space for some types
    69  	// (consider uint8 key, uint64 element). Consider placing all keys
    70  	// together in these cases to save space.
    71  	groups groupsReference
    72  }
    73  
    74  func newTable(typ *abi.SwissMapType, capacity uint64, index int, localDepth uint8) *table {
    75  	if capacity < abi.SwissMapGroupSlots {
    76  		capacity = abi.SwissMapGroupSlots
    77  	}
    78  
    79  	t := &table{
    80  		index:      index,
    81  		localDepth: localDepth,
    82  	}
    83  
    84  	if capacity > maxTableCapacity {
    85  		panic("initial table capacity too large")
    86  	}
    87  
    88  	// N.B. group count must be a power of two for probeSeq to visit every
    89  	// group.
    90  	capacity, overflow := alignUpPow2(capacity)
    91  	if overflow {
    92  		panic("rounded-up capacity overflows uint64")
    93  	}
    94  
    95  	t.reset(typ, uint16(capacity))
    96  
    97  	return t
    98  }
    99  
   100  // reset resets the table with new, empty groups with the specified new total
   101  // capacity.
   102  func (t *table) reset(typ *abi.SwissMapType, capacity uint16) {
   103  	groupCount := uint64(capacity) / abi.SwissMapGroupSlots
   104  	t.groups = newGroups(typ, groupCount)
   105  	t.capacity = capacity
   106  	t.resetGrowthLeft()
   107  
   108  	for i := uint64(0); i <= t.groups.lengthMask; i++ {
   109  		g := t.groups.group(typ, i)
   110  		g.ctrls().setEmpty()
   111  	}
   112  }
   113  
   114  // Preconditions: table must be empty.
   115  func (t *table) resetGrowthLeft() {
   116  	var growthLeft uint16
   117  	if t.capacity == 0 {
   118  		// No real reason to support zero capacity table, since an
   119  		// empty Map simply won't have a table.
   120  		panic("table must have positive capacity")
   121  	} else if t.capacity <= abi.SwissMapGroupSlots {
   122  		// If the map fits in a single group then we're able to fill all of
   123  		// the slots except 1 (an empty slot is needed to terminate find
   124  		// operations).
   125  		//
   126  		// TODO(go.dev/issue/54766): With a special case in probing for
   127  		// single-group tables, we could fill all slots.
   128  		growthLeft = t.capacity - 1
   129  	} else {
   130  		if t.capacity*maxAvgGroupLoad < t.capacity {
   131  			// TODO(prattmic): Do something cleaner.
   132  			panic("overflow")
   133  		}
   134  		growthLeft = (t.capacity * maxAvgGroupLoad) / abi.SwissMapGroupSlots
   135  	}
   136  	t.growthLeft = growthLeft
   137  }
   138  
   139  func (t *table) Used() uint64 {
   140  	return uint64(t.used)
   141  }
   142  
   143  // Get performs a lookup of the key that key points to. It returns a pointer to
   144  // the element, or false if the key doesn't exist.
   145  func (t *table) Get(typ *abi.SwissMapType, m *Map, key unsafe.Pointer) (unsafe.Pointer, bool) {
   146  	// TODO(prattmic): We could avoid hashing in a variety of special
   147  	// cases.
   148  	//
   149  	// - One entry maps could just directly compare the single entry
   150  	//   without hashing.
   151  	// - String keys could do quick checks of a few bytes before hashing.
   152  	hash := typ.Hasher(key, m.seed)
   153  	_, elem, ok := t.getWithKey(typ, hash, key)
   154  	return elem, ok
   155  }
   156  
   157  // getWithKey performs a lookup of key, returning a pointer to the version of
   158  // the key in the map in addition to the element.
   159  //
   160  // This is relevant when multiple different key values compare equal (e.g.,
   161  // +0.0 and -0.0). When a grow occurs during iteration, iteration perform a
   162  // lookup of keys from the old group in the new group in order to correctly
   163  // expose updated elements. For NeedsKeyUpdate keys, iteration also must return
   164  // the new key value, not the old key value.
   165  // hash must be the hash of the key.
   166  func (t *table) getWithKey(typ *abi.SwissMapType, hash uintptr, key unsafe.Pointer) (unsafe.Pointer, unsafe.Pointer, bool) {
   167  	// To find the location of a key in the table, we compute hash(key). From
   168  	// h1(hash(key)) and the capacity, we construct a probeSeq that visits
   169  	// every group of slots in some interesting order. See [probeSeq].
   170  	//
   171  	// We walk through these indices. At each index, we select the entire
   172  	// group starting with that index and extract potential candidates:
   173  	// occupied slots with a control byte equal to h2(hash(key)). The key
   174  	// at candidate slot i is compared with key; if key == g.slot(i).key
   175  	// we are done and return the slot; if there is an empty slot in the
   176  	// group, we stop and return an error; otherwise we continue to the
   177  	// next probe index. Tombstones (ctrlDeleted) effectively behave like
   178  	// full slots that never match the value we're looking for.
   179  	//
   180  	// The h2 bits ensure when we compare a key we are likely to have
   181  	// actually found the object. That is, the chance is low that keys
   182  	// compare false. Thus, when we search for an object, we are unlikely
   183  	// to call Equal many times. This likelihood can be analyzed as follows
   184  	// (assuming that h2 is a random enough hash function).
   185  	//
   186  	// Let's assume that there are k "wrong" objects that must be examined
   187  	// in a probe sequence. For example, when doing a find on an object
   188  	// that is in the table, k is the number of objects between the start
   189  	// of the probe sequence and the final found object (not including the
   190  	// final found object). The expected number of objects with an h2 match
   191  	// is then k/128. Measurements and analysis indicate that even at high
   192  	// load factors, k is less than 32, meaning that the number of false
   193  	// positive comparisons we must perform is less than 1/8 per find.
   194  	seq := makeProbeSeq(h1(hash), t.groups.lengthMask)
   195  	for ; ; seq = seq.next() {
   196  		g := t.groups.group(typ, seq.offset)
   197  
   198  		match := g.ctrls().matchH2(h2(hash))
   199  
   200  		for match != 0 {
   201  			i := match.first()
   202  
   203  			slotKey := g.key(typ, i)
   204  			if typ.IndirectKey() {
   205  				slotKey = *((*unsafe.Pointer)(slotKey))
   206  			}
   207  			if typ.Key.Equal(key, slotKey) {
   208  				slotElem := g.elem(typ, i)
   209  				if typ.IndirectElem() {
   210  					slotElem = *((*unsafe.Pointer)(slotElem))
   211  				}
   212  				return slotKey, slotElem, true
   213  			}
   214  			match = match.removeFirst()
   215  		}
   216  
   217  		match = g.ctrls().matchEmpty()
   218  		if match != 0 {
   219  			// Finding an empty slot means we've reached the end of
   220  			// the probe sequence.
   221  			return nil, nil, false
   222  		}
   223  	}
   224  }
   225  
   226  func (t *table) getWithoutKey(typ *abi.SwissMapType, hash uintptr, key unsafe.Pointer) (unsafe.Pointer, bool) {
   227  	seq := makeProbeSeq(h1(hash), t.groups.lengthMask)
   228  	for ; ; seq = seq.next() {
   229  		g := t.groups.group(typ, seq.offset)
   230  
   231  		match := g.ctrls().matchH2(h2(hash))
   232  
   233  		for match != 0 {
   234  			i := match.first()
   235  
   236  			slotKey := g.key(typ, i)
   237  			if typ.IndirectKey() {
   238  				slotKey = *((*unsafe.Pointer)(slotKey))
   239  			}
   240  			if typ.Key.Equal(key, slotKey) {
   241  				slotElem := g.elem(typ, i)
   242  				if typ.IndirectElem() {
   243  					slotElem = *((*unsafe.Pointer)(slotElem))
   244  				}
   245  				return slotElem, true
   246  			}
   247  			match = match.removeFirst()
   248  		}
   249  
   250  		match = g.ctrls().matchEmpty()
   251  		if match != 0 {
   252  			// Finding an empty slot means we've reached the end of
   253  			// the probe sequence.
   254  			return nil, false
   255  		}
   256  	}
   257  }
   258  
   259  // PutSlot returns a pointer to the element slot where an inserted element
   260  // should be written, and ok if it returned a valid slot.
   261  //
   262  // PutSlot returns ok false if the table was split and the Map needs to find
   263  // the new table.
   264  //
   265  // hash must be the hash of key.
   266  func (t *table) PutSlot(typ *abi.SwissMapType, m *Map, hash uintptr, key unsafe.Pointer) (unsafe.Pointer, bool) {
   267  	seq := makeProbeSeq(h1(hash), t.groups.lengthMask)
   268  
   269  	// As we look for a match, keep track of the first deleted slot we
   270  	// find, which we'll use to insert the new entry if necessary.
   271  	var firstDeletedGroup groupReference
   272  	var firstDeletedSlot uintptr
   273  
   274  	for ; ; seq = seq.next() {
   275  		g := t.groups.group(typ, seq.offset)
   276  		match := g.ctrls().matchH2(h2(hash))
   277  
   278  		// Look for an existing slot containing this key.
   279  		for match != 0 {
   280  			i := match.first()
   281  
   282  			slotKey := g.key(typ, i)
   283  			if typ.IndirectKey() {
   284  				slotKey = *((*unsafe.Pointer)(slotKey))
   285  			}
   286  			if typ.Key.Equal(key, slotKey) {
   287  				if typ.NeedKeyUpdate() {
   288  					typedmemmove(typ.Key, slotKey, key)
   289  				}
   290  
   291  				slotElem := g.elem(typ, i)
   292  				if typ.IndirectElem() {
   293  					slotElem = *((*unsafe.Pointer)(slotElem))
   294  				}
   295  
   296  				t.checkInvariants(typ, m)
   297  				return slotElem, true
   298  			}
   299  			match = match.removeFirst()
   300  		}
   301  
   302  		// No existing slot for this key in this group. Is this the end
   303  		// of the probe sequence?
   304  		match = g.ctrls().matchEmptyOrDeleted()
   305  		if match == 0 {
   306  			continue // nothing but filled slots. Keep probing.
   307  		}
   308  		i := match.first()
   309  		if g.ctrls().get(i) == ctrlDeleted {
   310  			// There are some deleted slots. Remember
   311  			// the first one, and keep probing.
   312  			if firstDeletedGroup.data == nil {
   313  				firstDeletedGroup = g
   314  				firstDeletedSlot = i
   315  			}
   316  			continue
   317  		}
   318  		// We've found an empty slot, which means we've reached the end of
   319  		// the probe sequence.
   320  
   321  		// If we found a deleted slot along the way, we can
   322  		// replace it without consuming growthLeft.
   323  		if firstDeletedGroup.data != nil {
   324  			g = firstDeletedGroup
   325  			i = firstDeletedSlot
   326  			t.growthLeft++ // will be decremented below to become a no-op.
   327  		}
   328  
   329  		// If there is room left to grow, just insert the new entry.
   330  		if t.growthLeft > 0 {
   331  			slotKey := g.key(typ, i)
   332  			if typ.IndirectKey() {
   333  				kmem := newobject(typ.Key)
   334  				*(*unsafe.Pointer)(slotKey) = kmem
   335  				slotKey = kmem
   336  			}
   337  			typedmemmove(typ.Key, slotKey, key)
   338  
   339  			slotElem := g.elem(typ, i)
   340  			if typ.IndirectElem() {
   341  				emem := newobject(typ.Elem)
   342  				*(*unsafe.Pointer)(slotElem) = emem
   343  				slotElem = emem
   344  			}
   345  
   346  			g.ctrls().set(i, ctrl(h2(hash)))
   347  			t.growthLeft--
   348  			t.used++
   349  			m.used++
   350  
   351  			t.checkInvariants(typ, m)
   352  			return slotElem, true
   353  		}
   354  
   355  		t.rehash(typ, m)
   356  		return nil, false
   357  	}
   358  }
   359  
   360  // uncheckedPutSlot inserts an entry known not to be in the table.
   361  // This is used for grow/split where we are making a new table from
   362  // entries in an existing table.
   363  //
   364  // Decrements growthLeft and increments used.
   365  //
   366  // Requires that the entry does not exist in the table, and that the table has
   367  // room for another element without rehashing.
   368  //
   369  // Requires that there are no deleted entries in the table.
   370  //
   371  // For indirect keys and/or elements, the key and elem pointers can be
   372  // put directly into the map, they do not need to be copied. This
   373  // requires the caller to ensure that the referenced memory never
   374  // changes (by sourcing those pointers from another indirect key/elem
   375  // map).
   376  func (t *table) uncheckedPutSlot(typ *abi.SwissMapType, hash uintptr, key, elem unsafe.Pointer) {
   377  	if t.growthLeft == 0 {
   378  		panic("invariant failed: growthLeft is unexpectedly 0")
   379  	}
   380  
   381  	// Given key and its hash hash(key), to insert it, we construct a
   382  	// probeSeq, and use it to find the first group with an unoccupied (empty
   383  	// or deleted) slot. We place the key/value into the first such slot in
   384  	// the group and mark it as full with key's H2.
   385  	seq := makeProbeSeq(h1(hash), t.groups.lengthMask)
   386  	for ; ; seq = seq.next() {
   387  		g := t.groups.group(typ, seq.offset)
   388  
   389  		match := g.ctrls().matchEmptyOrDeleted()
   390  		if match != 0 {
   391  			i := match.first()
   392  
   393  			slotKey := g.key(typ, i)
   394  			if typ.IndirectKey() {
   395  				*(*unsafe.Pointer)(slotKey) = key
   396  			} else {
   397  				typedmemmove(typ.Key, slotKey, key)
   398  			}
   399  
   400  			slotElem := g.elem(typ, i)
   401  			if typ.IndirectElem() {
   402  				*(*unsafe.Pointer)(slotElem) = elem
   403  			} else {
   404  				typedmemmove(typ.Elem, slotElem, elem)
   405  			}
   406  
   407  			t.growthLeft--
   408  			t.used++
   409  			g.ctrls().set(i, ctrl(h2(hash)))
   410  			return
   411  		}
   412  	}
   413  }
   414  
   415  func (t *table) Delete(typ *abi.SwissMapType, m *Map, hash uintptr, key unsafe.Pointer) {
   416  	seq := makeProbeSeq(h1(hash), t.groups.lengthMask)
   417  	for ; ; seq = seq.next() {
   418  		g := t.groups.group(typ, seq.offset)
   419  		match := g.ctrls().matchH2(h2(hash))
   420  
   421  		for match != 0 {
   422  			i := match.first()
   423  
   424  			slotKey := g.key(typ, i)
   425  			origSlotKey := slotKey
   426  			if typ.IndirectKey() {
   427  				slotKey = *((*unsafe.Pointer)(slotKey))
   428  			}
   429  
   430  			if typ.Key.Equal(key, slotKey) {
   431  				t.used--
   432  				m.used--
   433  
   434  				if typ.IndirectKey() {
   435  					// Clearing the pointer is sufficient.
   436  					*(*unsafe.Pointer)(origSlotKey) = nil
   437  				} else if typ.Key.Pointers() {
   438  					// Only bothing clear the key if there
   439  					// are pointers in it.
   440  					typedmemclr(typ.Key, slotKey)
   441  				}
   442  
   443  				slotElem := g.elem(typ, i)
   444  				if typ.IndirectElem() {
   445  					// Clearing the pointer is sufficient.
   446  					*(*unsafe.Pointer)(slotElem) = nil
   447  				} else {
   448  					// Unlike keys, always clear the elem (even if
   449  					// it contains no pointers), as compound
   450  					// assignment operations depend on cleared
   451  					// deleted values. See
   452  					// https://go.dev/issue/25936.
   453  					typedmemclr(typ.Elem, slotElem)
   454  				}
   455  
   456  				// Only a full group can appear in the middle
   457  				// of a probe sequence (a group with at least
   458  				// one empty slot terminates probing). Once a
   459  				// group becomes full, it stays full until
   460  				// rehashing/resizing. So if the group isn't
   461  				// full now, we can simply remove the element.
   462  				// Otherwise, we create a tombstone to mark the
   463  				// slot as deleted.
   464  				if g.ctrls().matchEmpty() != 0 {
   465  					g.ctrls().set(i, ctrlEmpty)
   466  					t.growthLeft++
   467  				} else {
   468  					g.ctrls().set(i, ctrlDeleted)
   469  				}
   470  
   471  				t.checkInvariants(typ, m)
   472  				return
   473  			}
   474  			match = match.removeFirst()
   475  		}
   476  
   477  		match = g.ctrls().matchEmpty()
   478  		if match != 0 {
   479  			// Finding an empty slot means we've reached the end of
   480  			// the probe sequence.
   481  			return
   482  		}
   483  	}
   484  }
   485  
   486  // tombstones returns the number of deleted (tombstone) entries in the table. A
   487  // tombstone is a slot that has been deleted but is still considered occupied
   488  // so as not to violate the probing invariant.
   489  func (t *table) tombstones() uint16 {
   490  	return (t.capacity*maxAvgGroupLoad)/abi.SwissMapGroupSlots - t.used - t.growthLeft
   491  }
   492  
   493  // Clear deletes all entries from the map resulting in an empty map.
   494  func (t *table) Clear(typ *abi.SwissMapType) {
   495  	for i := uint64(0); i <= t.groups.lengthMask; i++ {
   496  		g := t.groups.group(typ, i)
   497  		typedmemclr(typ.Group, g.data)
   498  		g.ctrls().setEmpty()
   499  	}
   500  
   501  	t.used = 0
   502  	t.resetGrowthLeft()
   503  }
   504  
   505  type Iter struct {
   506  	key  unsafe.Pointer // Must be in first position.  Write nil to indicate iteration end (see cmd/compile/internal/walk/range.go).
   507  	elem unsafe.Pointer // Must be in second position (see cmd/compile/internal/walk/range.go).
   508  	typ  *abi.SwissMapType
   509  	m    *Map
   510  
   511  	// Randomize iteration order by starting iteration at a random slot
   512  	// offset. The offset into the directory uses a separate offset, as it
   513  	// must adjust when the directory grows.
   514  	entryOffset uint64
   515  	dirOffset   uint64
   516  
   517  	// Snapshot of Map.clearSeq at iteration initialization time. Used to
   518  	// detect clear during iteration.
   519  	clearSeq uint64
   520  
   521  	// Value of Map.globalDepth during the last call to Next. Used to
   522  	// detect directory grow during iteration.
   523  	globalDepth uint8
   524  
   525  	// dirIdx is the current directory index, prior to adjustment by
   526  	// dirOffset.
   527  	dirIdx int
   528  
   529  	// tab is the table at dirIdx during the previous call to Next.
   530  	tab *table
   531  
   532  	// group is the group at entryIdx during the previous call to Next.
   533  	group groupReference
   534  
   535  	// entryIdx is the current entry index, prior to adjustment by entryOffset.
   536  	// The lower 3 bits of the index are the slot index, and the upper bits
   537  	// are the group index.
   538  	entryIdx uint64
   539  }
   540  
   541  // Init initializes Iter for iteration.
   542  func (it *Iter) Init(typ *abi.SwissMapType, m *Map) {
   543  	it.typ = typ
   544  
   545  	if m == nil || m.used == 0 {
   546  		return
   547  	}
   548  
   549  	dirIdx := 0
   550  	var groupSmall groupReference
   551  	if m.dirLen <= 0 {
   552  		// Use dirIdx == -1 as sentinel for small maps.
   553  		dirIdx = -1
   554  		groupSmall.data = m.dirPtr
   555  	}
   556  
   557  	it.m = m
   558  	it.entryOffset = rand()
   559  	it.dirOffset = rand()
   560  	it.globalDepth = m.globalDepth
   561  	it.dirIdx = dirIdx
   562  	it.group = groupSmall
   563  	it.clearSeq = m.clearSeq
   564  }
   565  
   566  func (it *Iter) Initialized() bool {
   567  	return it.typ != nil
   568  }
   569  
   570  // Map returns the map this iterator is iterating over.
   571  func (it *Iter) Map() *Map {
   572  	return it.m
   573  }
   574  
   575  // Key returns a pointer to the current key. nil indicates end of iteration.
   576  //
   577  // Must not be called prior to Next.
   578  func (it *Iter) Key() unsafe.Pointer {
   579  	return it.key
   580  }
   581  
   582  // Key returns a pointer to the current element. nil indicates end of
   583  // iteration.
   584  //
   585  // Must not be called prior to Next.
   586  func (it *Iter) Elem() unsafe.Pointer {
   587  	return it.elem
   588  }
   589  
   590  func (it *Iter) nextDirIdx() {
   591  	// Skip other entries in the directory that refer to the same
   592  	// logical table. There are two cases of this:
   593  	//
   594  	// Consider this directory:
   595  	//
   596  	// - 0: *t1
   597  	// - 1: *t1
   598  	// - 2: *t2a
   599  	// - 3: *t2b
   600  	//
   601  	// At some point, the directory grew to accommodate a split of
   602  	// t2. t1 did not split, so entries 0 and 1 both point to t1.
   603  	// t2 did split, so the two halves were installed in entries 2
   604  	// and 3.
   605  	//
   606  	// If dirIdx is 0 and it.tab is t1, then we should skip past
   607  	// entry 1 to avoid repeating t1.
   608  	//
   609  	// If dirIdx is 2 and it.tab is t2 (pre-split), then we should
   610  	// skip past entry 3 because our pre-split t2 already covers
   611  	// all keys from t2a and t2b (except for new insertions, which
   612  	// iteration need not return).
   613  	//
   614  	// We can achieve both of these by using to difference between
   615  	// the directory and table depth to compute how many entries
   616  	// the table covers.
   617  	entries := 1 << (it.m.globalDepth - it.tab.localDepth)
   618  	it.dirIdx += entries
   619  	it.tab = nil
   620  	it.group = groupReference{}
   621  	it.entryIdx = 0
   622  }
   623  
   624  // Return the appropriate key/elem for key at slotIdx index within it.group, if
   625  // any.
   626  func (it *Iter) grownKeyElem(key unsafe.Pointer, slotIdx uintptr) (unsafe.Pointer, unsafe.Pointer, bool) {
   627  	newKey, newElem, ok := it.m.getWithKey(it.typ, key)
   628  	if !ok {
   629  		// Key has likely been deleted, and
   630  		// should be skipped.
   631  		//
   632  		// One exception is keys that don't
   633  		// compare equal to themselves (e.g.,
   634  		// NaN). These keys cannot be looked
   635  		// up, so getWithKey will fail even if
   636  		// the key exists.
   637  		//
   638  		// However, we are in luck because such
   639  		// keys cannot be updated and they
   640  		// cannot be deleted except with clear.
   641  		// Thus if no clear has occurred, the
   642  		// key/elem must still exist exactly as
   643  		// in the old groups, so we can return
   644  		// them from there.
   645  		//
   646  		// TODO(prattmic): Consider checking
   647  		// clearSeq early. If a clear occurred,
   648  		// Next could always return
   649  		// immediately, as iteration doesn't
   650  		// need to return anything added after
   651  		// clear.
   652  		if it.clearSeq == it.m.clearSeq && !it.typ.Key.Equal(key, key) {
   653  			elem := it.group.elem(it.typ, slotIdx)
   654  			if it.typ.IndirectElem() {
   655  				elem = *((*unsafe.Pointer)(elem))
   656  			}
   657  			return key, elem, true
   658  		}
   659  
   660  		// This entry doesn't exist anymore.
   661  		return nil, nil, false
   662  	}
   663  
   664  	return newKey, newElem, true
   665  }
   666  
   667  // Next proceeds to the next element in iteration, which can be accessed via
   668  // the Key and Elem methods.
   669  //
   670  // The table can be mutated during iteration, though there is no guarantee that
   671  // the mutations will be visible to the iteration.
   672  //
   673  // Init must be called prior to Next.
   674  func (it *Iter) Next() {
   675  	if it.m == nil {
   676  		// Map was empty at Iter.Init.
   677  		it.key = nil
   678  		it.elem = nil
   679  		return
   680  	}
   681  
   682  	if it.m.writing != 0 {
   683  		fatal("concurrent map iteration and map write")
   684  		return
   685  	}
   686  
   687  	if it.dirIdx < 0 {
   688  		// Map was small at Init.
   689  		for ; it.entryIdx < abi.SwissMapGroupSlots; it.entryIdx++ {
   690  			k := uintptr(it.entryIdx+it.entryOffset) % abi.SwissMapGroupSlots
   691  
   692  			if (it.group.ctrls().get(k) & ctrlEmpty) == ctrlEmpty {
   693  				// Empty or deleted.
   694  				continue
   695  			}
   696  
   697  			key := it.group.key(it.typ, k)
   698  			if it.typ.IndirectKey() {
   699  				key = *((*unsafe.Pointer)(key))
   700  			}
   701  
   702  			// As below, if we have grown to a full map since Init,
   703  			// we continue to use the old group to decide the keys
   704  			// to return, but must look them up again in the new
   705  			// tables.
   706  			grown := it.m.dirLen > 0
   707  			var elem unsafe.Pointer
   708  			if grown {
   709  				var ok bool
   710  				newKey, newElem, ok := it.m.getWithKey(it.typ, key)
   711  				if !ok {
   712  					// See comment below.
   713  					if it.clearSeq == it.m.clearSeq && !it.typ.Key.Equal(key, key) {
   714  						elem = it.group.elem(it.typ, k)
   715  						if it.typ.IndirectElem() {
   716  							elem = *((*unsafe.Pointer)(elem))
   717  						}
   718  					} else {
   719  						continue
   720  					}
   721  				} else {
   722  					key = newKey
   723  					elem = newElem
   724  				}
   725  			} else {
   726  				elem = it.group.elem(it.typ, k)
   727  				if it.typ.IndirectElem() {
   728  					elem = *((*unsafe.Pointer)(elem))
   729  				}
   730  			}
   731  
   732  			it.entryIdx++
   733  			it.key = key
   734  			it.elem = elem
   735  			return
   736  		}
   737  		it.key = nil
   738  		it.elem = nil
   739  		return
   740  	}
   741  
   742  	if it.globalDepth != it.m.globalDepth {
   743  		// Directory has grown since the last call to Next. Adjust our
   744  		// directory index.
   745  		//
   746  		// Consider:
   747  		//
   748  		// Before:
   749  		// - 0: *t1
   750  		// - 1: *t2  <- dirIdx
   751  		//
   752  		// After:
   753  		// - 0: *t1a (split)
   754  		// - 1: *t1b (split)
   755  		// - 2: *t2  <- dirIdx
   756  		// - 3: *t2
   757  		//
   758  		// That is, we want to double the current index when the
   759  		// directory size doubles (or quadruple when the directory size
   760  		// quadruples, etc).
   761  		//
   762  		// The actual (randomized) dirIdx is computed below as:
   763  		//
   764  		// dirIdx := (it.dirIdx + it.dirOffset) % it.m.dirLen
   765  		//
   766  		// Multiplication is associative across modulo operations,
   767  		// A * (B % C) = (A * B) % (A * C),
   768  		// provided that A is positive.
   769  		//
   770  		// Thus we can achieve this by adjusting it.dirIdx,
   771  		// it.dirOffset, and it.m.dirLen individually.
   772  		orders := it.m.globalDepth - it.globalDepth
   773  		it.dirIdx <<= orders
   774  		it.dirOffset <<= orders
   775  		// it.m.dirLen was already adjusted when the directory grew.
   776  
   777  		it.globalDepth = it.m.globalDepth
   778  	}
   779  
   780  	// Continue iteration until we find a full slot.
   781  	for ; it.dirIdx < it.m.dirLen; it.nextDirIdx() {
   782  		// Resolve the table.
   783  		if it.tab == nil {
   784  			dirIdx := int((uint64(it.dirIdx) + it.dirOffset) & uint64(it.m.dirLen-1))
   785  			newTab := it.m.directoryAt(uintptr(dirIdx))
   786  			if newTab.index != dirIdx {
   787  				// Normally we skip past all duplicates of the
   788  				// same entry in the table (see updates to
   789  				// it.dirIdx at the end of the loop below), so
   790  				// this case wouldn't occur.
   791  				//
   792  				// But on the very first call, we have a
   793  				// completely randomized dirIdx that may refer
   794  				// to a middle of a run of tables in the
   795  				// directory. Do a one-time adjustment of the
   796  				// offset to ensure we start at first index for
   797  				// newTable.
   798  				diff := dirIdx - newTab.index
   799  				it.dirOffset -= uint64(diff)
   800  				dirIdx = newTab.index
   801  			}
   802  			it.tab = newTab
   803  		}
   804  
   805  		// N.B. Use it.tab, not newTab. It is important to use the old
   806  		// table for key selection if the table has grown. See comment
   807  		// on grown below.
   808  
   809  		entryMask := uint64(it.tab.capacity) - 1
   810  		if it.entryIdx > entryMask {
   811  			// Continue to next table.
   812  			continue
   813  		}
   814  
   815  		// Fast path: skip matching and directly check if entryIdx is a
   816  		// full slot.
   817  		//
   818  		// In the slow path below, we perform an 8-slot match check to
   819  		// look for full slots within the group.
   820  		//
   821  		// However, with a max load factor of 7/8, each slot in a
   822  		// mostly full map has a high probability of being full. Thus
   823  		// it is cheaper to check a single slot than do a full control
   824  		// match.
   825  
   826  		entryIdx := (it.entryIdx + it.entryOffset) & entryMask
   827  		slotIdx := uintptr(entryIdx & (abi.SwissMapGroupSlots - 1))
   828  		if slotIdx == 0 || it.group.data == nil {
   829  			// Only compute the group (a) when we switch
   830  			// groups (slotIdx rolls over) and (b) on the
   831  			// first iteration in this table (slotIdx may
   832  			// not be zero due to entryOffset).
   833  			groupIdx := entryIdx >> abi.SwissMapGroupSlotsBits
   834  			it.group = it.tab.groups.group(it.typ, groupIdx)
   835  		}
   836  
   837  		if (it.group.ctrls().get(slotIdx) & ctrlEmpty) == 0 {
   838  			// Slot full.
   839  
   840  			key := it.group.key(it.typ, slotIdx)
   841  			if it.typ.IndirectKey() {
   842  				key = *((*unsafe.Pointer)(key))
   843  			}
   844  
   845  			grown := it.tab.index == -1
   846  			var elem unsafe.Pointer
   847  			if grown {
   848  				newKey, newElem, ok := it.grownKeyElem(key, slotIdx)
   849  				if !ok {
   850  					// This entry doesn't exist
   851  					// anymore. Continue to the
   852  					// next one.
   853  					goto next
   854  				} else {
   855  					key = newKey
   856  					elem = newElem
   857  				}
   858  			} else {
   859  				elem = it.group.elem(it.typ, slotIdx)
   860  				if it.typ.IndirectElem() {
   861  					elem = *((*unsafe.Pointer)(elem))
   862  				}
   863  			}
   864  
   865  			it.entryIdx++
   866  			it.key = key
   867  			it.elem = elem
   868  			return
   869  		}
   870  
   871  	next:
   872  		it.entryIdx++
   873  
   874  		// Slow path: use a match on the control word to jump ahead to
   875  		// the next full slot.
   876  		//
   877  		// This is highly effective for maps with particularly low load
   878  		// (e.g., map allocated with large hint but few insertions).
   879  		//
   880  		// For maps with medium load (e.g., 3-4 empty slots per group)
   881  		// it also tends to work pretty well. Since slots within a
   882  		// group are filled in order, then if there have been no
   883  		// deletions, a match will allow skipping past all empty slots
   884  		// at once.
   885  		//
   886  		// Note: it is tempting to cache the group match result in the
   887  		// iterator to use across Next calls. However because entries
   888  		// may be deleted between calls later calls would still need to
   889  		// double-check the control value.
   890  
   891  		var groupMatch bitset
   892  		for it.entryIdx <= entryMask {
   893  			entryIdx := (it.entryIdx + it.entryOffset) & entryMask
   894  			slotIdx := uintptr(entryIdx & (abi.SwissMapGroupSlots - 1))
   895  
   896  			if slotIdx == 0 || it.group.data == nil {
   897  				// Only compute the group (a) when we switch
   898  				// groups (slotIdx rolls over) and (b) on the
   899  				// first iteration in this table (slotIdx may
   900  				// not be zero due to entryOffset).
   901  				groupIdx := entryIdx >> abi.SwissMapGroupSlotsBits
   902  				it.group = it.tab.groups.group(it.typ, groupIdx)
   903  			}
   904  
   905  			if groupMatch == 0 {
   906  				groupMatch = it.group.ctrls().matchFull()
   907  
   908  				if slotIdx != 0 {
   909  					// Starting in the middle of the group.
   910  					// Ignore earlier groups.
   911  					groupMatch = groupMatch.removeBelow(slotIdx)
   912  				}
   913  
   914  				// Skip over groups that are composed of only empty or
   915  				// deleted slots.
   916  				if groupMatch == 0 {
   917  					// Jump past remaining slots in this
   918  					// group.
   919  					it.entryIdx += abi.SwissMapGroupSlots - uint64(slotIdx)
   920  					continue
   921  				}
   922  
   923  				i := groupMatch.first()
   924  				it.entryIdx += uint64(i - slotIdx)
   925  				if it.entryIdx > entryMask {
   926  					// Past the end of this table's iteration.
   927  					continue
   928  				}
   929  				entryIdx += uint64(i - slotIdx)
   930  				slotIdx = i
   931  			}
   932  
   933  			key := it.group.key(it.typ, slotIdx)
   934  			if it.typ.IndirectKey() {
   935  				key = *((*unsafe.Pointer)(key))
   936  			}
   937  
   938  			// If the table has changed since the last
   939  			// call, then it has grown or split. In this
   940  			// case, further mutations (changes to
   941  			// key->elem or deletions) will not be visible
   942  			// in our snapshot table. Instead we must
   943  			// consult the new table by doing a full
   944  			// lookup.
   945  			//
   946  			// We still use our old table to decide which
   947  			// keys to lookup in order to avoid returning
   948  			// the same key twice.
   949  			grown := it.tab.index == -1
   950  			var elem unsafe.Pointer
   951  			if grown {
   952  				newKey, newElem, ok := it.grownKeyElem(key, slotIdx)
   953  				if !ok {
   954  					// This entry doesn't exist anymore.
   955  					// Continue to the next one.
   956  					groupMatch = groupMatch.removeFirst()
   957  					if groupMatch == 0 {
   958  						// No more entries in this
   959  						// group. Continue to next
   960  						// group.
   961  						it.entryIdx += abi.SwissMapGroupSlots - uint64(slotIdx)
   962  						continue
   963  					}
   964  
   965  					// Next full slot.
   966  					i := groupMatch.first()
   967  					it.entryIdx += uint64(i - slotIdx)
   968  					continue
   969  				} else {
   970  					key = newKey
   971  					elem = newElem
   972  				}
   973  			} else {
   974  				elem = it.group.elem(it.typ, slotIdx)
   975  				if it.typ.IndirectElem() {
   976  					elem = *((*unsafe.Pointer)(elem))
   977  				}
   978  			}
   979  
   980  			// Jump ahead to the next full slot or next group.
   981  			groupMatch = groupMatch.removeFirst()
   982  			if groupMatch == 0 {
   983  				// No more entries in
   984  				// this group. Continue
   985  				// to next group.
   986  				it.entryIdx += abi.SwissMapGroupSlots - uint64(slotIdx)
   987  			} else {
   988  				// Next full slot.
   989  				i := groupMatch.first()
   990  				it.entryIdx += uint64(i - slotIdx)
   991  			}
   992  
   993  			it.key = key
   994  			it.elem = elem
   995  			return
   996  		}
   997  
   998  		// Continue to next table.
   999  	}
  1000  
  1001  	it.key = nil
  1002  	it.elem = nil
  1003  	return
  1004  }
  1005  
  1006  // Replaces the table with one larger table or two split tables to fit more
  1007  // entries. Since the table is replaced, t is now stale and should not be
  1008  // modified.
  1009  func (t *table) rehash(typ *abi.SwissMapType, m *Map) {
  1010  	// TODO(prattmic): SwissTables typically perform a "rehash in place"
  1011  	// operation which recovers capacity consumed by tombstones without growing
  1012  	// the table by reordering slots as necessary to maintain the probe
  1013  	// invariant while eliminating all tombstones.
  1014  	//
  1015  	// However, it is unclear how to make rehash in place work with
  1016  	// iteration. Since iteration simply walks through all slots in order
  1017  	// (with random start offset), reordering the slots would break
  1018  	// iteration.
  1019  	//
  1020  	// As an alternative, we could do a "resize" to new groups allocation
  1021  	// of the same size. This would eliminate the tombstones, but using a
  1022  	// new allocation, so the existing grow support in iteration would
  1023  	// continue to work.
  1024  
  1025  	newCapacity := 2 * t.capacity
  1026  	if newCapacity <= maxTableCapacity {
  1027  		t.grow(typ, m, newCapacity)
  1028  		return
  1029  	}
  1030  
  1031  	t.split(typ, m)
  1032  }
  1033  
  1034  // Bitmask for the last selection bit at this depth.
  1035  func localDepthMask(localDepth uint8) uintptr {
  1036  	if goarch.PtrSize == 4 {
  1037  		return uintptr(1) << (32 - localDepth)
  1038  	}
  1039  	return uintptr(1) << (64 - localDepth)
  1040  }
  1041  
  1042  // split the table into two, installing the new tables in the map directory.
  1043  func (t *table) split(typ *abi.SwissMapType, m *Map) {
  1044  	localDepth := t.localDepth
  1045  	localDepth++
  1046  
  1047  	// TODO: is this the best capacity?
  1048  	left := newTable(typ, maxTableCapacity, -1, localDepth)
  1049  	right := newTable(typ, maxTableCapacity, -1, localDepth)
  1050  
  1051  	// Split in half at the localDepth bit from the top.
  1052  	mask := localDepthMask(localDepth)
  1053  
  1054  	for i := uint64(0); i <= t.groups.lengthMask; i++ {
  1055  		g := t.groups.group(typ, i)
  1056  		for j := uintptr(0); j < abi.SwissMapGroupSlots; j++ {
  1057  			if (g.ctrls().get(j) & ctrlEmpty) == ctrlEmpty {
  1058  				// Empty or deleted
  1059  				continue
  1060  			}
  1061  
  1062  			key := g.key(typ, j)
  1063  			if typ.IndirectKey() {
  1064  				key = *((*unsafe.Pointer)(key))
  1065  			}
  1066  
  1067  			elem := g.elem(typ, j)
  1068  			if typ.IndirectElem() {
  1069  				elem = *((*unsafe.Pointer)(elem))
  1070  			}
  1071  
  1072  			hash := typ.Hasher(key, m.seed)
  1073  			var newTable *table
  1074  			if hash&mask == 0 {
  1075  				newTable = left
  1076  			} else {
  1077  				newTable = right
  1078  			}
  1079  			newTable.uncheckedPutSlot(typ, hash, key, elem)
  1080  		}
  1081  	}
  1082  
  1083  	m.installTableSplit(t, left, right)
  1084  	t.index = -1
  1085  }
  1086  
  1087  // grow the capacity of the table by allocating a new table with a bigger array
  1088  // and uncheckedPutting each element of the table into the new table (we know
  1089  // that no insertion here will Put an already-present value), and discard the
  1090  // old table.
  1091  func (t *table) grow(typ *abi.SwissMapType, m *Map, newCapacity uint16) {
  1092  	newTable := newTable(typ, uint64(newCapacity), t.index, t.localDepth)
  1093  
  1094  	if t.capacity > 0 {
  1095  		for i := uint64(0); i <= t.groups.lengthMask; i++ {
  1096  			g := t.groups.group(typ, i)
  1097  			for j := uintptr(0); j < abi.SwissMapGroupSlots; j++ {
  1098  				if (g.ctrls().get(j) & ctrlEmpty) == ctrlEmpty {
  1099  					// Empty or deleted
  1100  					continue
  1101  				}
  1102  
  1103  				key := g.key(typ, j)
  1104  				if typ.IndirectKey() {
  1105  					key = *((*unsafe.Pointer)(key))
  1106  				}
  1107  
  1108  				elem := g.elem(typ, j)
  1109  				if typ.IndirectElem() {
  1110  					elem = *((*unsafe.Pointer)(elem))
  1111  				}
  1112  
  1113  				hash := typ.Hasher(key, m.seed)
  1114  
  1115  				newTable.uncheckedPutSlot(typ, hash, key, elem)
  1116  			}
  1117  		}
  1118  	}
  1119  
  1120  	newTable.checkInvariants(typ, m)
  1121  	m.replaceTable(newTable)
  1122  	t.index = -1
  1123  }
  1124  
  1125  // probeSeq maintains the state for a probe sequence that iterates through the
  1126  // groups in a table. The sequence is a triangular progression of the form
  1127  //
  1128  //	p(i) := (i^2 + i)/2 + hash (mod mask+1)
  1129  //
  1130  // The sequence effectively outputs the indexes of *groups*. The group
  1131  // machinery allows us to check an entire group with minimal branching.
  1132  //
  1133  // It turns out that this probe sequence visits every group exactly once if
  1134  // the number of groups is a power of two, since (i^2+i)/2 is a bijection in
  1135  // Z/(2^m). See https://en.wikipedia.org/wiki/Quadratic_probing
  1136  type probeSeq struct {
  1137  	mask   uint64
  1138  	offset uint64
  1139  	index  uint64
  1140  }
  1141  
  1142  func makeProbeSeq(hash uintptr, mask uint64) probeSeq {
  1143  	return probeSeq{
  1144  		mask:   mask,
  1145  		offset: uint64(hash) & mask,
  1146  		index:  0,
  1147  	}
  1148  }
  1149  
  1150  func (s probeSeq) next() probeSeq {
  1151  	s.index++
  1152  	s.offset = (s.offset + s.index) & s.mask
  1153  	return s
  1154  }
  1155  

View as plain text