Simpify (X - (X & mask)) to (X & ~mask)
[sbcl.git] / src / code / target-hash-table.lisp
blobba20dac53bb9b0792e6bef2394c8e647cebc0337
1 ;;;; that part of the implementation of HASH-TABLE which lives solely
2 ;;;; on the target system, not on the cross-compilation host
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!IMPL")
15 ;;;; utilities
17 (defun hash-table-weakness (ht)
18 "Return the WEAKNESS of HASH-TABLE which is one of NIL, :KEY,
19 :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE."
20 (aref weak-hash-table-kinds (hash-table-%weakness ht)))
22 (declaim (inline hash-table-weak-p))
23 (defun hash-table-weak-p (ht)
24 (not (zerop (hash-table-%weakness ht))))
26 ;;; Code for detecting concurrent accesses to the same table from
27 ;;; multiple threads. Only compiled in when the :SB-HASH-TABLE-DEBUG
28 ;;; feature is enabled. The main reason for the existence of this code
29 ;;; is to detect thread-unsafe uses of hash-tables in sbcl itself,
30 ;;; where debugging anythign can be impossible after an important
31 ;;; internal hash-table has been corrupted. It's plausible that this
32 ;;; could be useful for some user code too, but the runtime cost is
33 ;;; really too high to enable it by default.
34 (defmacro with-concurrent-access-check (hash-table operation &body body)
35 (declare (ignorable hash-table operation)
36 (type (member :read :write) operation))
37 #!-sb-hash-table-debug
38 `(progn ,@body)
39 #!+sb-hash-table-debug
40 (let ((thread-slot-accessor (if (eq operation :read)
41 'hash-table-reading-thread
42 'hash-table-writing-thread)))
43 (once-only ((hash-table hash-table))
44 `(progn
45 (flet ((body-fun ()
46 ,@body)
47 (error-fun ()
48 ;; Don't signal more errors for this table.
49 (setf (hash-table-signal-concurrent-access ,hash-table) nil)
50 (cerror "Ignore the concurrent access"
51 "Concurrent access to ~A" ,hash-table)))
52 (declare (inline body-fun))
53 (if (hash-table-signal-concurrent-access ,hash-table)
54 (unwind-protect
55 (progn
56 (unless (and (null (hash-table-writing-thread
57 ,hash-table))
58 ,@(when (eq operation :write)
59 `((null (hash-table-reading-thread
60 ,hash-table)))))
61 (error-fun))
62 (setf (,thread-slot-accessor ,hash-table)
63 sb!thread::*current-thread*)
64 (body-fun))
65 (unless (and ,@(when (eq operation :read)
66 `((null (hash-table-writing-thread
67 ,hash-table))))
68 ,@(when (eq operation :write)
69 ;; no readers are allowed while writing
70 `((null (hash-table-reading-thread
71 ,hash-table))
72 (eq (hash-table-writing-thread
73 ,hash-table)
74 sb!thread::*current-thread*))))
75 (error-fun))
76 (when (eq (,thread-slot-accessor ,hash-table)
77 sb!thread::*current-thread*)
78 ;; this is not 100% correct here and may hide
79 ;; concurrent access in rare circumstances.
80 (setf (,thread-slot-accessor ,hash-table) nil)))
81 (body-fun)))))))
83 #!-sb-fluid (declaim (inline eq-hash))
84 (defun eq-hash (key)
85 (declare (values hash (member t nil)))
86 (values (pointer-hash key)
87 (oddp (get-lisp-obj-address key))))
89 #!-sb-fluid (declaim (inline equal-hash))
90 (defun equal-hash (key)
91 (declare (values hash (member t nil)))
92 (typecase key
93 ;; For some types the definition of EQUAL implies a special hash
94 ((or string cons number bit-vector pathname)
95 (values (sxhash key) nil))
96 ;; Otherwise use an EQ hash, rather than SXHASH, since the values
97 ;; of SXHASH will be extremely badly distributed due to the
98 ;; requirements of the spec fitting badly with our implementation
99 ;; strategy.
101 (eq-hash key))))
103 #!-sb-fluid (declaim (inline eql-hash))
104 (defun eql-hash (key)
105 (declare (values hash (member t nil)))
106 (if (numberp key)
107 (equal-hash key)
108 (eq-hash key)))
110 (defun equalp-hash (key)
111 (declare (values hash (member t nil)))
112 (typecase key
113 ;; Types requiring special treatment. Note that PATHNAME and
114 ;; HASH-TABLE are caught by the STRUCTURE-OBJECT test.
115 ((or array cons number character structure-object)
116 (values (psxhash key) nil))
118 (eq-hash key))))
120 (declaim (inline index-for-hashing))
121 (defun index-for-hashing (hash length)
122 (declare (type hash hash length))
123 ;; We're using power of two tables which obviously are very
124 ;; sensitive to the exact values of the low bits in the hash
125 ;; value. Do a little shuffling of the value to mix the high bits in
126 ;; there too.
127 (truly-the index
128 (logand (1- length)
129 (+ (logxor #b11100101010001011010100111
130 hash)
131 (ash hash -3)
132 (ash hash -12)
133 (ash hash -20)))))
136 ;;;; user-defined hash table tests
138 (defvar *user-hash-table-tests* nil)
140 (defun register-hash-table-test (name hash-fun)
141 (declare (symbol name) (function hash-fun))
142 (unless (fboundp name)
143 (error "Cannot register ~S has a hash table test: undefined function."
144 name))
145 (with-single-package-locked-error
146 (:symbol name "defining ~S as a hash table test")
147 (let* ((test-fun (fdefinition name))
148 (this (list name test-fun hash-fun))
149 (spec (assoc name *user-hash-table-tests*)))
150 (cond (spec
151 (unless (and (eq (second spec) test-fun)
152 (eq (third spec) hash-fun))
153 (style-warn "Redefining hash table test ~S." name)
154 (setf (cdr spec) (cdr this))))
156 (push this *user-hash-table-tests*)))))
157 name)
159 (defmacro define-hash-table-test (name hash-function)
160 "Defines NAME as a new kind of hash table test for use with the :TEST
161 argument to MAKE-HASH-TABLE, and associates a default HASH-FUNCTION with it.
163 NAME must be a symbol naming a global two argument equivalence predicate.
164 Afterwards both 'NAME and #'NAME can be used with :TEST argument. In both
165 cases HASH-TABLE-TEST will return the symbol NAME.
167 HASH-FUNCTION must be a symbol naming a global hash function consistent with
168 the predicate, or be a LAMBDA form implementing one in the current lexical
169 environment. The hash function must compute the same hash code for any two
170 objects for which NAME returns true, and subsequent calls with already hashed
171 objects must always return the same hash code.
173 Note: The :HASH-FUNCTION keyword argument to MAKE-HASH-TABLE can be used to
174 override the specified default hash-function.
176 Attempting to define NAME in a locked package as hash-table test causes a
177 package lock violation.
179 Examples:
181 ;;; 1.
183 ;; We want to use objects of type FOO as keys (by their
184 ;; names.) EQUALP would work, but would make the names
185 ;; case-insensitive -- which we don't want.
186 (defstruct foo (name nil :type (or null string)))
188 ;; Define an equivalence test function and a hash function.
189 (defun foo-name= (f1 f2) (equal (foo-name f1) (foo-name f2)))
190 (defun sxhash-foo-name (f) (sxhash (foo-name f)))
192 (define-hash-table-test foo-name= sxhash-foo-name)
194 ;; #'foo-name would work too.
195 (defun make-foo-table () (make-hash-table :test 'foo-name=))
197 ;;; 2.
199 (defun == (x y) (= x y))
201 (define-hash-table-test ==
202 (lambda (x)
203 ;; Hash codes must be consistent with test, so
204 ;; not (SXHASH X), since
205 ;; (= 1 1.0) => T
206 ;; (= (SXHASH 1) (SXHASH 1.0)) => NIL
207 ;; Note: this doesn't deal with complex numbers or
208 ;; bignums too large to represent as double floats.
209 (sxhash (coerce x 'double-float))))
211 ;; #'== would work too
212 (defun make-number-table () (make-hash-table :test '==))
214 (check-type name symbol)
215 (if (member name '(eq eql equal equalp))
216 (error "Cannot redefine standard hash table test ~S." name)
217 (cond ((symbolp hash-function)
218 `(register-hash-table-test ',name (symbol-function ',hash-function)))
219 ((and (consp hash-function) (eq 'lambda (car hash-function)))
220 `(register-hash-table-test ',name #',hash-function))
222 (error "Malformed HASH-FUNCTION: ~S" hash-function)))))
224 ;;;; construction and simple accessors
226 (defconstant +min-hash-table-size+ 16)
227 (defconstant +min-hash-table-rehash-threshold+ (float 1/16 1.0))
229 (defun make-hash-table (&key
230 (test 'eql)
231 (size +min-hash-table-size+)
232 (rehash-size 1.5)
233 (rehash-threshold 1)
234 (hash-function nil)
235 (weakness nil)
236 (synchronized))
237 "Create and return a new hash table. The keywords are as follows:
239 :TEST
240 Determines how keys are compared. Must a designator for one of the
241 standard hash table tests, or a hash table test defined using
242 SB-EXT:DEFINE-HASH-TABLE-TEST. Additionally, when an explicit
243 HASH-FUNCTION is provided (see below), any two argument equivalence
244 predicate can be used as the TEST.
246 :SIZE
247 A hint as to how many elements will be put in this hash table.
249 :REHASH-SIZE
250 Indicates how to expand the table when it fills up. If an integer, add
251 space for that many elements. If a floating point number (which must be
252 greater than 1.0), multiply the size by that amount.
254 :REHASH-THRESHOLD
255 Indicates how dense the table can become before forcing a rehash. Can be
256 any positive number <=1, with density approaching zero as the threshold
257 approaches 0. Density 1 means an average of one entry per bucket.
259 :HASH-FUNCTION
260 If NIL (the default), a hash function based on the TEST argument is used,
261 which then must be one of the standardized hash table test functions, or
262 one for which a default hash function has been defined using
263 SB-EXT:DEFINE-HASH-TABLE-TEST. If HASH-FUNCTION is specified, the TEST
264 argument can be any two argument predicate consistent with it. The
265 HASH-FUNCTION is expected to return a non-negative fixnum hash code.
267 :WEAKNESS
268 When :WEAKNESS is not NIL, garbage collection may remove entries from the
269 hash table. The value of :WEAKNESS specifies how the presence of a key or
270 value in the hash table preserves their entries from garbage collection.
272 Valid values are:
274 :KEY means that the key of an entry must be live to guarantee that the
275 entry is preserved.
277 :VALUE means that the value of an entry must be live to guarantee that
278 the entry is preserved.
280 :KEY-AND-VALUE means that both the key and the value must be live to
281 guarantee that the entry is preserved.
283 :KEY-OR-VALUE means that either the key or the value must be live to
284 guarantee that the entry is preserved.
286 NIL (the default) means that entries are always preserved.
288 :SYNCHRONIZED
289 If NIL (the default), the hash-table may have multiple concurrent readers,
290 but results are undefined if a thread writes to the hash-table
291 concurrently with another reader or writer. If T, all concurrent accesses
292 are safe, but note that CLHS 3.6 (Traversal Rules and Side Effects)
293 remains in force. See also: SB-EXT:WITH-LOCKED-HASH-TABLE. This keyword
294 argument is experimental, and may change incompatibly or be removed in the
295 future."
296 (declare (type (or function symbol) test))
297 (declare (type unsigned-byte size))
298 (multiple-value-bind (test test-fun hash-fun)
299 (cond ((or (eq test #'eq) (eq test 'eq))
300 (values 'eq #'eq #'eq-hash))
301 ((or (eq test #'eql) (eq test 'eql))
302 (values 'eql #'eql #'eql-hash))
303 ((or (eq test #'equal) (eq test 'equal))
304 (values 'equal #'equal #'equal-hash))
305 ((or (eq test #'equalp) (eq test 'equalp))
306 (values 'equalp #'equalp #'equalp-hash))
308 ;; FIXME: It would be nice to have a compiler-macro
309 ;; that resolved this at compile time: we could grab
310 ;; the alist cell in a LOAD-TIME-VALUE, etc.
311 (dolist (info *user-hash-table-tests*
312 (if hash-function
313 (if (functionp test)
314 (values (%fun-name test) test nil)
315 (values test (%coerce-callable-to-fun test) nil))
316 (error "Unknown :TEST for MAKE-HASH-TABLE: ~S"
317 test)))
318 (destructuring-bind (test-name test-fun hash-fun) info
319 (when (or (eq test test-name) (eq test test-fun))
320 (return (values test-name test-fun hash-fun)))))))
321 (when hash-function
322 (setf hash-fun
323 ;; Quickly check if the function has return return type which
324 ;; guarantees that the secondary return value is always NIL:
325 ;; (VALUES * &OPTIONAL), (VALUES * NULL ...) or (VALUES *
326 ;; &OPTIONAL NULL ...)
327 (let* ((actual (%coerce-callable-to-fun hash-function))
328 (type-spec (%fun-type actual))
329 (return-spec (when (consp type-spec)
330 (caddr type-spec)))
331 (extra-vals (when (consp return-spec)
332 (cddr return-spec))))
333 (if (and (consp extra-vals)
334 (or (eq 'null (car extra-vals))
335 (and (eq '&optional (car extra-vals))
336 (or (not (cdr extra-vals))
337 (eq 'null (cadr extra-vals))))))
338 actual
339 ;; If there is a potential secondary value, make sure we
340 ;; don't accidentally claim EQ based hashing...
341 (lambda (object)
342 (declare (optimize (safety 0) (speed 3)))
343 (values (funcall actual object) nil))))))
344 (let* ((size (max +min-hash-table-size+
345 (min size
346 ;; SIZE is just a hint, so if the user asks
347 ;; for a SIZE which'd be too big for us to
348 ;; easily implement, we bump it down.
349 (floor array-dimension-limit 1024))))
350 (rehash-size (if (integerp rehash-size)
351 rehash-size
352 (float rehash-size 1.0)))
353 ;; FIXME: Original REHASH-THRESHOLD default should be 1.0,
354 ;; not 1, to make it easier for the compiler to avoid
355 ;; boxing.
356 (rehash-threshold (max +min-hash-table-rehash-threshold+
357 (float rehash-threshold 1.0)))
358 (size+1 (1+ size)) ; The first element is not usable.
359 ;; KLUDGE: The most natural way of expressing the below is
360 ;; (round (/ (float size+1) rehash-threshold)), and indeed
361 ;; it was expressed like that until 0.7.0. However,
362 ;; MAKE-HASH-TABLE is called very early in cold-init, and
363 ;; the SPARC has no primitive instructions for rounding,
364 ;; but only for truncating; therefore, we fudge this issue
365 ;; a little. The other uses of truncate, below, similarly
366 ;; used to be round. -- CSR, 2002-10-01
368 ;; Note that this has not yet been audited for
369 ;; correctness. It just seems to work. -- CSR, 2002-11-02
370 (scaled-size (truncate (/ (float size+1) rehash-threshold)))
371 (length (power-of-two-ceiling (max scaled-size
372 (1+ +min-hash-table-size+))))
373 (index-vector (make-array length
374 :element-type
375 '(unsigned-byte #.sb!vm:n-word-bits)
376 :initial-element 0))
377 ;; Needs to be the half the length of the KV vector to link
378 ;; KV entries - mapped to indeces at 2i and 2i+1 -
379 ;; together.
380 (next-vector (make-array size+1
381 :element-type
382 '(unsigned-byte #.sb!vm:n-word-bits)))
383 (kv-vector (make-array (* 2 size+1)
384 :initial-element +empty-ht-slot+))
385 (table (%make-hash-table
386 test
387 test-fun
388 hash-fun
389 rehash-size
390 rehash-threshold
391 size
392 kv-vector
393 (position weakness weak-hash-table-kinds :test #'eq)
394 index-vector
395 next-vector
396 (unless (eq test 'eq)
397 (make-array size+1
398 :element-type '(unsigned-byte
399 #.sb!vm:n-word-bits)
400 :initial-element +magic-hash-vector-value+))
401 synchronized)))
402 (declare (type index size+1 scaled-size length))
403 ;; Set up the free list, all free. These lists are 0 terminated.
404 (do ((i 1 (1+ i)))
405 ((>= i size))
406 (setf (aref next-vector i) (1+ i)))
407 (setf (aref next-vector size) 0)
408 (setf (hash-table-next-free-kv table) 1)
409 (setf (aref kv-vector 0) table)
410 table)))
412 (defun hash-table-count (hash-table)
413 "Return the number of entries in the given HASH-TABLE."
414 (declare (type hash-table hash-table)
415 (values index))
416 (hash-table-number-entries hash-table))
418 (setf (fdocumentation 'hash-table-rehash-size 'function)
419 "Return the rehash-size HASH-TABLE was created with.")
421 (setf (fdocumentation 'hash-table-rehash-threshold 'function)
422 "Return the rehash-threshold HASH-TABLE was created with.")
424 (setf (fdocumentation 'hash-table-synchronized-p 'function)
425 "Returns T if HASH-TABLE is synchronized.")
427 (defun hash-table-size (hash-table)
428 "Return a size that can be used with MAKE-HASH-TABLE to create a hash
429 table that can hold however many entries HASH-TABLE can hold without
430 having to be grown."
431 (hash-table-rehash-trigger hash-table))
433 (setf (fdocumentation 'hash-table-test 'function)
434 "Return the test HASH-TABLE was created with.")
436 ;;; Called when we detect circular chains in a hash-table.
437 (defun signal-corrupt-hash-table (hash-table)
438 (error "Corrupt NEXT-chain in ~A. This is probably caused by ~
439 multiple threads accessing the same hash-table without locking."
440 hash-table))
443 ;;;; accessing functions
445 ;;; Make new vectors for the table, extending the table based on the
446 ;;; rehash-size.
447 (defun rehash (table)
448 (declare (type hash-table table))
449 (aver *gc-inhibit*)
450 (let* ((old-kv-vector (hash-table-table table))
451 (old-next-vector (hash-table-next-vector table))
452 (old-hash-vector (hash-table-hash-vector table))
453 (old-size (length old-next-vector))
454 (new-size
455 (power-of-two-ceiling
456 (let ((rehash-size (hash-table-rehash-size table)))
457 (etypecase rehash-size
458 (fixnum
459 (+ rehash-size old-size))
460 (float
461 (the index (truncate (* rehash-size old-size))))))))
462 (new-kv-vector (make-array (* 2 new-size)
463 :initial-element +empty-ht-slot+))
464 (new-next-vector
465 (make-array new-size
466 :element-type '(unsigned-byte #.sb!vm:n-word-bits)
467 :initial-element 0))
468 (new-hash-vector
469 (when old-hash-vector
470 (make-array new-size
471 :element-type '(unsigned-byte #.sb!vm:n-word-bits)
472 :initial-element +magic-hash-vector-value+)))
473 (new-length new-size)
474 (new-index-vector
475 (make-array new-length
476 :element-type '(unsigned-byte #.sb!vm:n-word-bits)
477 :initial-element 0)))
478 (declare (type index new-size new-length old-size))
480 ;; Disable GC tricks on the OLD-KV-VECTOR.
481 (set-header-data old-kv-vector sb!vm:vector-normal-subtype)
483 ;; Non-empty weak hash tables always need GC support.
484 (when (and (hash-table-weak-p table) (plusp (hash-table-count table)))
485 (set-header-data new-kv-vector sb!vm:vector-valid-hashing-subtype))
487 ;; FIXME: here and in several other places in the hash table code,
488 ;; loops like this one are used when FILL or REPLACE would be
489 ;; appropriate. why are standard CL functions not used?
490 ;; Performance issues? General laziness? -- NJF, 2004-03-10
492 ;; Copy over the kv-vector. The element positions should not move
493 ;; in case there are active scans.
494 (dotimes (i (* old-size 2))
495 (declare (type index i))
496 (setf (aref new-kv-vector i) (aref old-kv-vector i)))
498 ;; Copy over the hash-vector.
499 (when old-hash-vector
500 (dotimes (i old-size)
501 (setf (aref new-hash-vector i) (aref old-hash-vector i))))
503 (setf (hash-table-next-free-kv table) 0)
504 ;; Rehash all the entries; last to first so that after the pushes
505 ;; the chains are first to last.
506 (do ((i (1- new-size) (1- i)))
507 ((zerop i))
508 (declare (type index/2 i))
509 (let ((key (aref new-kv-vector (* 2 i)))
510 (value (aref new-kv-vector (1+ (* 2 i)))))
511 (cond ((and (empty-ht-slot-p key) (empty-ht-slot-p value))
512 ;; Slot is empty, push it onto the free list.
513 (setf (aref new-next-vector i)
514 (hash-table-next-free-kv table))
515 (setf (hash-table-next-free-kv table) i))
516 ((and new-hash-vector
517 (not (= (aref new-hash-vector i)
518 +magic-hash-vector-value+)))
519 ;; Can use the existing hash value (not EQ based)
520 (let* ((hashing (aref new-hash-vector i))
521 (index (index-for-hashing hashing new-length))
522 (next (aref new-index-vector index)))
523 (declare (type index index)
524 (type hash hashing))
525 ;; Push this slot into the next chain.
526 (setf (aref new-next-vector i) next)
527 (setf (aref new-index-vector index) i)))
529 ;; EQ base hash.
530 ;; Enable GC tricks.
531 (set-header-data new-kv-vector
532 sb!vm:vector-valid-hashing-subtype)
533 (let* ((hashing (pointer-hash key))
534 (index (index-for-hashing hashing new-length))
535 (next (aref new-index-vector index)))
536 (declare (type index index)
537 (type hash hashing))
538 ;; Push this slot onto the next chain.
539 (setf (aref new-next-vector i) next)
540 (setf (aref new-index-vector index) i))))))
541 (setf (hash-table-table table) new-kv-vector)
542 (setf (hash-table-index-vector table) new-index-vector)
543 (setf (hash-table-next-vector table) new-next-vector)
544 (setf (hash-table-hash-vector table) new-hash-vector)
545 ;; Fill the old kv-vector with 0 to help the conservative GC. Even
546 ;; if nothing else were zeroed, it's important to clear the
547 ;; special first cells in old-kv-vector.
548 (fill old-kv-vector 0)
549 (setf (hash-table-rehash-trigger table) new-size)
550 (setf (hash-table-needs-rehash-p table) nil))
551 (values))
553 ;;; Use the same size as before, re-using the vectors.
554 (defun rehash-without-growing (table)
555 (declare (type hash-table table))
556 (aver *gc-inhibit*)
557 (let* ((kv-vector (hash-table-table table))
558 (next-vector (hash-table-next-vector table))
559 (hash-vector (hash-table-hash-vector table))
560 (size (length next-vector))
561 (index-vector (hash-table-index-vector table))
562 (length (length index-vector)))
563 (declare (type index size length))
565 ;; Non-empty weak hash tables always need GC support.
566 (unless (and (hash-table-weak-p table) (plusp (hash-table-count table)))
567 ;; Disable GC tricks, they will be re-enabled during the re-hash
568 ;; if necessary.
569 (set-header-data kv-vector sb!vm:vector-normal-subtype))
571 ;; Rehash all the entries.
572 (setf (hash-table-next-free-kv table) 0)
573 (dotimes (i size)
574 (setf (aref next-vector i) 0))
575 (dotimes (i length)
576 (setf (aref index-vector i) 0))
577 (do ((i (1- size) (1- i)))
578 ((zerop i))
579 (declare (type index/2 i))
580 (let ((key (aref kv-vector (* 2 i)))
581 (value (aref kv-vector (1+ (* 2 i)))))
582 (cond ((and (empty-ht-slot-p key) (empty-ht-slot-p value))
583 ;; Slot is empty, push it onto free list.
584 (setf (aref next-vector i) (hash-table-next-free-kv table))
585 (setf (hash-table-next-free-kv table) i))
586 ((and hash-vector (not (= (aref hash-vector i)
587 +magic-hash-vector-value+)))
588 ;; Can use the existing hash value (not EQ based)
589 (let* ((hashing (aref hash-vector i))
590 (index (index-for-hashing hashing length))
591 (next (aref index-vector index)))
592 (declare (type index index))
593 ;; Push this slot into the next chain.
594 (setf (aref next-vector i) next)
595 (setf (aref index-vector index) i)))
597 ;; EQ base hash.
598 ;; Enable GC tricks.
599 (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype)
600 (let* ((hashing (pointer-hash key))
601 (index (index-for-hashing hashing length))
602 (next (aref index-vector index)))
603 (declare (type index index)
604 (type hash hashing))
605 ;; Push this slot into the next chain.
606 (setf (aref next-vector i) next)
607 (setf (aref index-vector index) i)))))))
608 ;; Clear the rehash bit only at the very end, otherwise another thread
609 ;; might see a partially rehashed table as a normal one.
610 (setf (hash-table-needs-rehash-p table) nil)
611 (values))
613 (declaim (inline maybe-rehash))
614 (defun maybe-rehash (hash-table ensure-free-slot-p)
615 (when (hash-table-weak-p hash-table)
616 (aver *gc-inhibit*))
617 (flet ((rehash-p ()
618 (and ensure-free-slot-p
619 (zerop (hash-table-next-free-kv hash-table))))
620 (rehash-without-growing-p ()
621 (hash-table-needs-rehash-p hash-table)))
622 (declare (inline rehash-p rehash-without-growing-p))
623 (cond ((rehash-p)
624 ;; Use recursive locks since for weak tables the lock has
625 ;; already been acquired. GC must be inhibited to prevent
626 ;; the GC from seeing a rehash in progress.
627 (sb!thread::with-recursive-system-lock
628 ((hash-table-lock hash-table) :without-gcing t)
629 ;; Repeat the condition inside the lock to ensure that if
630 ;; two reader threads enter MAYBE-REHASH at the same time
631 ;; only one rehash is performed.
632 (when (rehash-p)
633 (rehash hash-table))))
634 ((rehash-without-growing-p)
635 (sb!thread::with-recursive-system-lock
636 ((hash-table-lock hash-table) :without-gcing t)
637 (when (rehash-without-growing-p)
638 (rehash-without-growing hash-table)))))))
640 (declaim (inline update-hash-table-cache))
641 (defun update-hash-table-cache (hash-table index)
642 (unless (hash-table-weak-p hash-table)
643 (setf (hash-table-cache hash-table) index)))
645 (defmacro with-hash-table-locks ((hash-table
646 &key (operation :write) inline pin
647 (synchronized `(hash-table-synchronized-p ,hash-table)))
648 &body body)
649 (declare (type (member :read :write) operation))
650 (with-unique-names (body-fun)
651 `(flet ((,body-fun ()
652 (with-concurrent-access-check ,hash-table ,operation
653 (locally (declare (inline ,@inline))
654 ,@body))))
655 (if (hash-table-weak-p ,hash-table)
656 (sb!thread::with-recursive-system-lock
657 ((hash-table-lock ,hash-table) :without-gcing t)
658 (,body-fun))
659 (with-pinned-objects ,pin
660 (if ,synchronized
661 ;; We use a "system" lock here because it is very
662 ;; slightly faster, as it doesn't re-enable
663 ;; interrupts.
664 (sb!thread::with-recursive-system-lock
665 ((hash-table-lock ,hash-table))
666 (,body-fun))
667 (,body-fun)))))))
669 (defun gethash (key hash-table &optional default)
670 "Finds the entry in HASH-TABLE whose key is KEY and returns the
671 associated value and T as multiple values, or returns DEFAULT and NIL
672 if there is no such entry. Entries can be added using SETF."
673 (declare (type hash-table hash-table)
674 (values t (member t nil)))
675 (gethash3 key hash-table default))
677 (declaim (maybe-inline %gethash3))
678 (defun %gethash3 (key hash-table default)
679 (declare (type hash-table hash-table)
680 (optimize speed)
681 (values t (member t nil)))
682 (tagbody
683 start
684 (let ((start-epoch sb!kernel::*gc-epoch*))
685 (macrolet ((result (value foundp)
686 ;; When the table has multiple concurrent readers,
687 ;; it's possible that there was a GC after this
688 ;; thread called MAYBE-REHASH from %GETHASH3, and
689 ;; some other thread then rehashed the table. If
690 ;; this happens, we might not find the key even if
691 ;; it's in the table. To protect against this,
692 ;; redo the lookup if the GC epoch counter has changed.
693 ;; -- JES, 2007-09-30
694 `(if (and (not ,foundp)
695 (not (eq start-epoch sb!kernel::*gc-epoch*)))
696 (go start)
697 (return-from %gethash3 (values ,value ,foundp))))
698 (overflow ()
699 ;; The next-vector chain is circular. This is caused
700 ;; caused by thread-unsafe mutations of the table.
701 `(signal-corrupt-hash-table hash-table)))
702 (maybe-rehash hash-table nil)
703 ;; Note that it's OK for a GC + a REHASH-WITHOUT-GROWING to
704 ;; be triggered by another thread after this point, since the
705 ;; GC epoch check will catch it.
706 (let ((cache (hash-table-cache hash-table))
707 (table (hash-table-table hash-table)))
708 ;; First check the cache. Use EQ here for speed.
709 (if (and cache
710 (< cache (length table))
711 (eq (aref table cache) key))
712 (let ((value (aref table (1+ cache))))
713 (result value t))
714 ;; Search for key in the hash table.
715 (multiple-value-bind (hashing eq-based)
716 (funcall (hash-table-hash-fun hash-table) key)
717 (declare (type hash hashing))
718 (let* ((index-vector (hash-table-index-vector hash-table))
719 (length (length index-vector))
720 (index (index-for-hashing hashing length))
721 (next (aref index-vector index))
722 (next-vector (hash-table-next-vector hash-table))
723 (hash-vector (hash-table-hash-vector hash-table))
724 (test-fun (hash-table-test-fun hash-table)))
725 (declare (type index index))
726 ;; Search next-vector chain for a matching key.
727 (if (or eq-based (not hash-vector))
728 (do ((next next (aref next-vector next))
729 (i 0 (1+ i)))
730 ((zerop next) (result default nil))
731 (declare (type index/2 next i))
732 (when (> i length)
733 (overflow))
734 (when (eq key (aref table (* 2 next)))
735 (update-hash-table-cache hash-table (* 2 next))
736 (let ((value (aref table (1+ (* 2 next)))))
737 (result value t))))
738 (do ((next next (aref next-vector next))
739 (i 0 (1+ i)))
740 ((zerop next) (result default nil))
741 (declare (type index/2 next i))
742 (when (> i length)
743 (overflow))
744 (when (and (= hashing (aref hash-vector next))
745 (funcall test-fun key
746 (aref table (* 2 next))))
747 ;; Found.
748 (update-hash-table-cache hash-table (* 2 next))
749 (let ((value (aref table (1+ (* 2 next)))))
750 (result value t)))))))))))))
751 ;;; Three argument version of GETHASH
752 (defun gethash3 (key hash-table default)
753 (declare (type hash-table hash-table))
754 (truly-the (values t boolean)
755 (with-hash-table-locks (hash-table :operation :read :inline (%gethash3)
756 :pin (key))
757 (%gethash3 key hash-table default))))
759 ;;; so people can call #'(SETF GETHASH)
760 ;;; FIXME: this function is not mandated. Why do we have it?
761 (defun (setf gethash) (new-value key table &optional default)
762 (declare (ignore default))
763 (%puthash key table new-value))
765 (declaim (maybe-inline %%puthash))
766 (defun %%puthash (key hash-table value)
767 (declare (optimize speed))
768 ;; We need to rehash here so that a current key can be found if it
769 ;; exists. Check that there is room for one more entry. May not be
770 ;; needed if the key is already present.
771 (maybe-rehash hash-table t)
772 ;; Search for key in the hash table.
773 (multiple-value-bind (hashing eq-based)
774 (funcall (hash-table-hash-fun hash-table) key)
775 (declare (type hash hashing))
776 (let* ((index-vector (hash-table-index-vector hash-table))
777 (length (length index-vector))
778 (index (index-for-hashing hashing length))
779 (next (aref index-vector index))
780 (kv-vector (hash-table-table hash-table))
781 (next-vector (hash-table-next-vector hash-table))
782 (hash-vector (hash-table-hash-vector hash-table))
783 (test-fun (hash-table-test-fun hash-table)))
784 (declare (type index index next))
785 (when (hash-table-weak-p hash-table)
786 (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype))
787 (cond ((or eq-based (not hash-vector))
788 (when eq-based
789 (set-header-data kv-vector
790 sb!vm:vector-valid-hashing-subtype))
791 ;; Search next-vector chain for a matching key.
792 (do ((next next (aref next-vector next))
793 (i 0 (1+ i)))
794 ((zerop next))
795 (declare (type index/2 next i))
796 (when (> i length)
797 (signal-corrupt-hash-table hash-table))
798 (when (eq key (aref kv-vector (* 2 next)))
799 ;; Found, just replace the value.
800 (update-hash-table-cache hash-table (* 2 next))
801 (setf (aref kv-vector (1+ (* 2 next))) value)
802 (return-from %%puthash value))))
804 ;; Search next-vector chain for a matching key.
805 (do ((next next (aref next-vector next))
806 (i 0 (1+ i)))
807 ((zerop next))
808 (declare (type index/2 next i))
809 (when (> i length)
810 (signal-corrupt-hash-table hash-table))
811 (when (and (= hashing (aref hash-vector next))
812 (funcall test-fun key
813 (aref kv-vector (* 2 next))))
814 ;; Found, just replace the value.
815 (update-hash-table-cache hash-table (* 2 next))
816 (setf (aref kv-vector (1+ (* 2 next))) value)
817 (return-from %%puthash value)))))
818 ;; Pop a KV slot off the free list
819 (let ((free-kv-slot (hash-table-next-free-kv hash-table)))
820 (declare (type index/2 free-kv-slot))
821 ;; Double-check for overflow.
822 (aver (not (zerop free-kv-slot)))
823 (setf (hash-table-next-free-kv hash-table)
824 (aref next-vector free-kv-slot))
825 (incf (hash-table-number-entries hash-table))
826 (update-hash-table-cache hash-table (* 2 free-kv-slot))
827 (setf (aref kv-vector (* 2 free-kv-slot)) key)
828 (setf (aref kv-vector (1+ (* 2 free-kv-slot))) value)
829 ;; Setup the hash-vector if necessary.
830 (when hash-vector
831 (if (not eq-based)
832 (setf (aref hash-vector free-kv-slot) hashing)
833 (aver (= (aref hash-vector free-kv-slot)
834 +magic-hash-vector-value+))))
835 ;; Push this slot into the next chain.
836 (setf (aref next-vector free-kv-slot) next)
837 (setf (aref index-vector index) free-kv-slot)))
838 value))
840 (defun %puthash (key hash-table value)
841 (declare (type hash-table hash-table))
842 (aver (hash-table-index-vector hash-table))
843 (macrolet ((put-it (lockedp)
844 `(let ((cache (hash-table-cache hash-table))
845 (kv-vector (hash-table-table hash-table)))
846 ;; Check the cache
847 (if (and cache
848 (< cache (length kv-vector))
849 (eq (aref kv-vector cache) key))
850 ;; If cached, just store here
851 (setf (aref kv-vector (1+ cache)) value)
852 ;; Otherwise do things the hard way
853 ,(if lockedp
854 '(%%puthash key hash-table value)
855 '(with-hash-table-locks
856 (hash-table :inline (%%puthash) :pin (key)
857 :synchronized nil)
858 (%%puthash key hash-table value)))))))
859 (if (hash-table-synchronized-p hash-table)
860 (with-hash-table-locks (hash-table :pin (key) :synchronized t)
861 (put-it t))
862 (put-it nil))))
864 (declaim (maybe-inline %remhash))
865 (defun %remhash (key hash-table)
866 ;; We need to rehash here so that a current key can be found if it
867 ;; exists.
869 ;; Note that if a GC happens after MAYBE-REHASH returns and another
870 ;; thread the accesses the table (triggering a rehash), we might not
871 ;; find the key even if it is in the table. But that's ok, since the
872 ;; only concurrent case that we safely allow is multiple readers
873 ;; with no writers.
874 (maybe-rehash hash-table nil)
875 ;; Search for key in the hash table.
876 (multiple-value-bind (hashing eq-based)
877 (funcall (hash-table-hash-fun hash-table) key)
878 (declare (type hash hashing))
879 (let* ((index-vector (hash-table-index-vector hash-table))
880 (length (length index-vector))
881 (index (index-for-hashing hashing length))
882 (next (aref index-vector index))
883 (table (hash-table-table hash-table))
884 (next-vector (hash-table-next-vector hash-table))
885 (hash-vector (hash-table-hash-vector hash-table))
886 (test-fun (hash-table-test-fun hash-table)))
887 (declare (type index index)
888 (type index/2 next))
889 (flet ((clear-slot (chain-vector prior-slot-location slot-location)
890 (declare (type index/2 slot-location))
891 ;; Mark slot as empty.
892 (setf (aref table (* 2 slot-location)) +empty-ht-slot+
893 (aref table (1+ (* 2 slot-location))) +empty-ht-slot+)
894 ;; Update the prior pointer in the chain to skip this.
895 (setf (aref chain-vector prior-slot-location)
896 (aref next-vector slot-location))
897 ;; Push KV slot onto free chain.
898 (setf (aref next-vector slot-location)
899 (hash-table-next-free-kv hash-table))
900 (setf (hash-table-next-free-kv hash-table) slot-location)
901 (when hash-vector
902 (setf (aref hash-vector slot-location)
903 +magic-hash-vector-value+))
904 ;; On parallel accesses this may turn out to be a
905 ;; type-error, so don't turn down the safety!
906 (decf (hash-table-number-entries hash-table))
908 (cond ((zerop next)
909 nil)
910 ((if (or eq-based (not hash-vector))
911 (eq key (aref table (* 2 next)))
912 (and (= hashing (aref hash-vector next))
913 (funcall test-fun key (aref table (* 2 next)))))
914 (clear-slot index-vector index next))
915 ;; Search next-vector chain for a matching key.
916 ((or eq-based (not hash-vector))
917 ;; EQ based
918 (do ((prior next next)
919 (i 0 (1+ i))
920 (next (aref next-vector next) (aref next-vector next)))
921 ((zerop next) nil)
922 (declare (type index next))
923 (when (> i length)
924 (signal-corrupt-hash-table hash-table))
925 (when (eq key (aref table (* 2 next)))
926 (return-from %remhash (clear-slot next-vector prior next)))))
928 ;; not EQ based
929 (do ((prior next next)
930 (i 0 (1+ i))
931 (next (aref next-vector next) (aref next-vector next)))
932 ((zerop next) nil)
933 (declare (type index/2 next))
934 (when (> i length)
935 (signal-corrupt-hash-table hash-table))
936 (when (and (= hashing (aref hash-vector next))
937 (funcall test-fun key (aref table (* 2 next))))
938 (return-from %remhash
939 (clear-slot next-vector prior next))))))))))
941 (defun remhash (key hash-table)
942 "Remove the entry in HASH-TABLE associated with KEY. Return T if
943 there was such an entry, or NIL if not."
944 (declare (type hash-table hash-table)
945 (values (member t nil)))
946 (with-hash-table-locks (hash-table :inline (%remhash) :pin (key))
947 ;; For now, just clear the cache
948 (setf (hash-table-cache hash-table) nil)
949 (%remhash key hash-table)))
951 (defun clrhash (hash-table)
952 "This removes all the entries from HASH-TABLE and returns the hash
953 table itself."
954 (when (plusp (hash-table-number-entries hash-table))
955 (with-hash-table-locks (hash-table)
956 (let* ((kv-vector (hash-table-table hash-table))
957 (next-vector (hash-table-next-vector hash-table))
958 (hash-vector (hash-table-hash-vector hash-table))
959 (size (length next-vector))
960 (index-vector (hash-table-index-vector hash-table)))
961 ;; Disable GC tricks.
962 (set-header-data kv-vector sb!vm:vector-normal-subtype)
963 ;; Mark all slots as empty by setting all keys and values to magic
964 ;; tag.
965 (aver (eq (aref kv-vector 0) hash-table))
966 (fill kv-vector +empty-ht-slot+ :start 2)
967 ;; Set up the free list, all free.
968 (do ((i 1 (1+ i)))
969 ((>= i (1- size)))
970 (setf (aref next-vector i) (1+ i)))
971 (setf (aref next-vector (1- size)) 0)
972 (setf (hash-table-next-free-kv hash-table) 1)
973 ;; Clear the index-vector.
974 (fill index-vector 0)
975 ;; Clear the hash-vector.
976 (when hash-vector
977 (fill hash-vector +magic-hash-vector-value+)))
978 (setf (hash-table-cache hash-table) nil)
979 (setf (hash-table-number-entries hash-table) 0)))
980 hash-table)
982 ;; Helper for atomic read/update of a synchronized table
983 ;; in a limited sort of way using a double-checked lock.
984 ;; You don't get to see the old value first.
985 ;; It wouldn't be too hard to add that feature.
986 (defun puthash-if-absent (key table constructor)
987 (or (gethash key table)
988 (let ((val (funcall constructor)))
989 (with-locked-system-table (table)
990 ;; VAL is discarded if KEY is found this time.
991 (or (gethash key table) (setf (gethash key table) val))))))
993 ;;;; methods on HASH-TABLE
995 ;;; Return a list of keyword args and values to use for MAKE-HASH-TABLE
996 ;;; when reconstructing HASH-TABLE.
997 (defun %hash-table-ctor-args (hash-table)
998 `(:test ',(hash-table-test hash-table)
999 :size ',(hash-table-size hash-table)
1000 :rehash-size ',(hash-table-rehash-size hash-table)
1001 :rehash-threshold ',(hash-table-rehash-threshold hash-table)
1002 :weakness ',(hash-table-weakness hash-table)))
1004 ;;; Stuff an association list into HASH-TABLE. Return the hash table,
1005 ;;; so that we can use this for the *PRINT-READABLY* case in
1006 ;;; PRINT-OBJECT (HASH-TABLE T) without having to worry about LET
1007 ;;; forms and readable gensyms and stuff.
1008 (defun %stuff-hash-table (hash-table alist)
1009 (dolist (x alist)
1010 (setf (gethash (car x) hash-table) (cdr x)))
1011 hash-table)
1013 (defmethod print-object ((hash-table hash-table) stream)
1014 (declare (type stream stream))
1015 (cond ((or (not *print-readably*) (not *read-eval*))
1016 (print-unreadable-object (hash-table stream :type t :identity t)
1017 (format stream
1018 ":TEST ~S :COUNT ~S~@[ :WEAKNESS ~S~]"
1019 (hash-table-test hash-table)
1020 (hash-table-count hash-table)
1021 (hash-table-weakness hash-table))))
1023 (write-string "#." stream)
1024 (write `(%stuff-hash-table (make-hash-table ,@(%hash-table-ctor-args
1025 hash-table))
1026 ',(%hash-table-alist hash-table))
1027 :stream stream))))
1029 (defmethod make-load-form ((hash-table hash-table) &optional environment)
1030 (declare (ignore environment))
1031 (values `(make-hash-table ,@(%hash-table-ctor-args hash-table))
1032 `(%stuff-hash-table ,hash-table ',(%hash-table-alist hash-table))))