1.0.25.8: fix sxhash bug
[sbcl.git] / src / code / target-sxhash.lisp
1 ;;;; hashing functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 (defun pointer-hash (key)
15   (pointer-hash key))
16
17 ;;; the depthoid explored when calculating hash values
18 ;;;
19 ;;; "Depthoid" here is a sort of mixture of what Common Lisp ordinarily calls
20 ;;; depth and what Common Lisp ordinarily calls length; it's incremented either
21 ;;; when we descend into a compound object or when we step through elements of
22 ;;; a compound object.
23 (defconstant +max-hash-depthoid+ 4)
24 \f
25 ;;;; mixing hash values
26
27 ;;; a function for mixing hash values
28 ;;;
29 ;;; desiderata:
30 ;;;   * Non-commutativity keeps us from hashing e.g. #(1 5) to the
31 ;;;     same value as #(5 1), and ending up in real trouble in some
32 ;;;     special cases like bit vectors the way that CMUCL 18b SXHASH
33 ;;;     does. (Under CMUCL 18b, SXHASH of any bit vector is 1..)
34 ;;;   * We'd like to scatter our hash values over the entire possible range
35 ;;;     of values instead of hashing small or common key values (like
36 ;;;     2 and NIL and #\a) to small FIXNUMs the way that the CMUCL 18b
37 ;;;     SXHASH function does, again helping to avoid pathologies like
38 ;;;     hashing all bit vectors to 1.
39 ;;;   * We'd like this to be simple and fast, too.
40 ;;;
41 ;;; FIXME: Should this be INLINE?
42 (declaim (ftype (sfunction ((and fixnum unsigned-byte)
43                             (and fixnum unsigned-byte))
44                            (and fixnum unsigned-byte))
45                 mix))
46 (declaim (inline mix))
47 (defun mix (x y)
48   ;; FIXME: We wouldn't need the nasty (SAFETY 0) here if the compiler
49   ;; were smarter about optimizing ASH. (Without the THE FIXNUM below,
50   ;; and the (SAFETY 0) declaration here to get the compiler to trust
51   ;; it, the sbcl-0.5.0m cross-compiler running under Debian
52   ;; cmucl-2.4.17 turns the ASH into a full call, requiring the
53   ;; UNSIGNED-BYTE 32 argument to be coerced to a bignum, requiring
54   ;; consing, and thus generally obliterating performance.)
55   (declare (optimize (speed 3) (safety 0)))
56   (declare (type (and fixnum unsigned-byte) x y))
57   ;; the ideas here:
58   ;;   * Bits diffuse in both directions (shifted left by up to 2 places
59   ;;     in the calculation of XY, and shifted right by up to 5 places
60   ;;     by the ASH).
61   ;;   * The #'+ and #'LOGXOR operations don't commute with each other,
62   ;;     so different bit patterns are mixed together as they shift
63   ;;     past each other.
64   ;;   * The arbitrary constant in the #'LOGXOR expression is intended
65   ;;     to help break up any weird anomalies we might otherwise get
66   ;;     when hashing highly regular patterns.
67   ;; (These are vaguely like the ideas used in many cryptographic
68   ;; algorithms, but we're not pushing them hard enough here for them
69   ;; to be cryptographically strong.)
70   (let* ((xy (+ (* x 3) y)))
71     (logand most-positive-fixnum
72             (logxor 441516657
73                     xy
74                     (ash xy -5)))))
75 \f
76 ;;;; hashing strings
77 ;;;;
78 ;;;; Note that this operation is used in compiler symbol table
79 ;;;; lookups, so we'd like it to be fast.
80 ;;;;
81 ;;;; As of 2004-03-10, we implement the one-at-a-time algorithm
82 ;;;; designed by Bob Jenkins (see
83 ;;;; <http://burtleburtle.net/bob/hash/doobs.html> for some more
84 ;;;; information).
85
86 (declaim (inline %sxhash-substring))
87 (defun %sxhash-substring (string &optional (count (length string)))
88   ;; FIXME: As in MIX above, we wouldn't need (SAFETY 0) here if the
89   ;; cross-compiler were smarter about ASH, but we need it for
90   ;; sbcl-0.5.0m.  (probably no longer true?  We might need SAFETY 0
91   ;; to elide some type checks, but then again if this is inlined in
92   ;; all the critical places, we might not -- CSR, 2004-03-10)
93   (declare (optimize (speed 3) (safety 0)))
94   (declare (type string string))
95   (declare (type index count))
96   (macrolet ((set-result (form)
97                `(setf result (ldb (byte #.sb!vm:n-word-bits 0) ,form))))
98     (let ((result 0))
99       (declare (type (unsigned-byte #.sb!vm:n-word-bits) result))
100       (unless (typep string '(vector nil))
101         (dotimes (i count)
102           (declare (type index i))
103           (set-result (+ result (char-code (aref string i))))
104           (set-result (+ result (ash result 10)))
105           (set-result (logxor result (ash result -6)))))
106       (set-result (+ result (ash result 3)))
107       (set-result (logxor result (ash result -11)))
108       (set-result (logxor result (ash result 15)))
109       (logand result most-positive-fixnum))))
110 ;;; test:
111 ;;;   (let ((ht (make-hash-table :test 'equal)))
112 ;;;     (do-all-symbols (symbol)
113 ;;;       (let* ((string (symbol-name symbol))
114 ;;;           (hash (%sxhash-substring string)))
115 ;;;      (if (gethash hash ht)
116 ;;;          (unless (string= (gethash hash ht) string)
117 ;;;            (format t "collision: ~S ~S~%" string (gethash hash ht)))
118 ;;;          (setf (gethash hash ht) string))))
119 ;;;     (format t "final count=~W~%" (hash-table-count ht)))
120
121 (defun %sxhash-simple-string (x)
122   (declare (optimize speed))
123   (declare (type simple-string x))
124   ;; KLUDGE: this FLET is a workaround (suggested by APD) for presence
125   ;; of let conversion in the cross compiler, which otherwise causes
126   ;; strongly suboptimal register allocation.
127   (flet ((trick (x)
128            (%sxhash-substring x)))
129     (declare (notinline trick))
130     (trick x)))
131
132 (defun %sxhash-simple-substring (x count)
133   (declare (optimize speed))
134   (declare (type simple-string x))
135   (declare (type index count))
136   ;; see comment in %SXHASH-SIMPLE-STRING
137   (flet ((trick (x count)
138            (%sxhash-substring x count)))
139     (declare (notinline trick))
140     (trick x count)))
141 \f
142 ;;;; the SXHASH function
143
144 ;; simple cases
145 (declaim (ftype (sfunction (integer) hash) sxhash-bignum))
146 (declaim (ftype (sfunction (t) hash) sxhash-instance))
147
148 (defun sxhash (x)
149   ;; profiling SXHASH is hard, but we might as well try to make it go
150   ;; fast, in case it is the bottleneck somewhere.  -- CSR, 2003-03-14
151   (declare (optimize speed))
152   (labels ((sxhash-number (x)
153              (etypecase x
154                (fixnum (sxhash x))      ; through DEFTRANSFORM
155                (integer (sb!bignum:sxhash-bignum x))
156                (single-float (sxhash x)) ; through DEFTRANSFORM
157                (double-float (sxhash x)) ; through DEFTRANSFORM
158                #!+long-float (long-float (error "stub: no LONG-FLOAT"))
159                (ratio (let ((result 127810327))
160                         (declare (type fixnum result))
161                         (mixf result (sxhash-number (numerator x)))
162                         (mixf result (sxhash-number (denominator x)))
163                         result))
164                (complex (let ((result 535698211))
165                           (declare (type fixnum result))
166                           (mixf result (sxhash-number (realpart x)))
167                           (mixf result (sxhash-number (imagpart x)))
168                           result))))
169            (sxhash-recurse (x depthoid)
170              (declare (type index depthoid))
171              (typecase x
172                ;; we test for LIST here, rather than CONS, because the
173                ;; type test for CONS is in fact the test for
174                ;; LIST-POINTER-LOWTAG followed by a negated test for
175                ;; NIL.  If we're going to have to test for NIL anyway,
176                ;; we might as well do it explicitly and pick off the
177                ;; answer.  -- CSR, 2004-07-14
178                (list
179                 (if (null x)
180                     (sxhash x) ; through DEFTRANSFORM
181                     (if (plusp depthoid)
182                         (mix (sxhash-recurse (car x) (1- depthoid))
183                              (sxhash-recurse (cdr x) (1- depthoid)))
184                         261835505)))
185                (instance
186                 (if (or (typep x 'structure-object) (typep x 'condition))
187                     (logxor 422371266
188                             (sxhash ; through DEFTRANSFORM
189                              (classoid-name
190                               (layout-classoid (%instance-layout x)))))
191                     (sxhash-instance x)))
192                (symbol (sxhash x)) ; through DEFTRANSFORM
193                (array
194                 (typecase x
195                   (simple-string (sxhash x)) ; through DEFTRANSFORM
196                   (string (%sxhash-substring x))
197                   (simple-bit-vector (sxhash x)) ; through DEFTRANSFORM
198                   (bit-vector
199                    ;; FIXME: It must surely be possible to do better
200                    ;; than this.  The problem is that a non-SIMPLE
201                    ;; BIT-VECTOR could be displaced to another, with a
202                    ;; non-zero offset -- so that significantly more
203                    ;; work needs to be done using the %RAW-BITS
204                    ;; approach.  This will probably do for now.
205                    (sxhash-recurse (copy-seq x) depthoid))
206                   (t (logxor 191020317 (sxhash (array-rank x))))))
207                (character
208                 (logxor 72185131
209                         (sxhash (char-code x)))) ; through DEFTRANSFORM
210                ;; general, inefficient case of NUMBER
211                (number (sxhash-number x))
212                (generic-function (sxhash-instance x))
213                (t 42))))
214     (sxhash-recurse x +max-hash-depthoid+)))
215 \f
216 ;;;; the PSXHASH function
217
218 ;;;; FIXME: This code does a lot of unnecessary full calls. It could be made
219 ;;;; more efficient (in both time and space) by rewriting it along the lines
220 ;;;; of the SXHASH code above.
221
222 ;;; like SXHASH, but for EQUALP hashing instead of EQUAL hashing
223 (defun psxhash (key &optional (depthoid +max-hash-depthoid+))
224   (declare (optimize speed))
225   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
226   ;; Note: You might think it would be cleaner to use the ordering given in the
227   ;; table from Figure 5-13 in the EQUALP section of the ANSI specification
228   ;; here. So did I, but that is a snare for the unwary! Nothing in the ANSI
229   ;; spec says that HASH-TABLE can't be a STRUCTURE-OBJECT, and in fact our
230   ;; HASH-TABLEs *are* STRUCTURE-OBJECTs, so we need to pick off the special
231   ;; HASH-TABLE behavior before we fall through to the generic STRUCTURE-OBJECT
232   ;; comparison behavior.
233   (typecase key
234     (array (array-psxhash key depthoid))
235     (hash-table (hash-table-psxhash key))
236     (structure-object (structure-object-psxhash key depthoid))
237     (cons (list-psxhash key depthoid))
238     (number (number-psxhash key))
239     (character (char-code (char-upcase key)))
240     (t (sxhash key))))
241
242 (defun array-psxhash (key depthoid)
243   (declare (optimize speed))
244   (declare (type array key))
245   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
246   (typecase key
247     ;; VECTORs have to be treated specially because ANSI specifies
248     ;; that we must respect fill pointers.
249     (vector
250      (macrolet ((frob ()
251                   '(let ((result 572539))
252                      (declare (type fixnum result))
253                      (mixf result (length key))
254                     (when (plusp depthoid)
255                       (decf depthoid)
256                       (dotimes (i (length key))
257                        (declare (type fixnum i))
258                        (mixf result
259                              (psxhash (aref key i) depthoid))))
260                     result))
261                 (make-dispatch (types)
262                   `(typecase key
263                      ,@(loop for type in types
264                              collect `(,type
265                                        (frob))))))
266        (make-dispatch (simple-base-string
267                        (simple-array character (*))
268                        simple-vector
269                        (simple-array (unsigned-byte 8) (*))
270                        (simple-array fixnum (*))
271                        t))))
272     ;; Any other array can be hashed by working with its underlying
273     ;; one-dimensional physical representation.
274     (t
275      (let ((result 60828))
276        (declare (type fixnum result))
277        (dotimes (i (array-rank key))
278          (mixf result (array-dimension key i)))
279        (when (plusp depthoid)
280          (decf depthoid)
281          (dotimes (i (array-total-size key))
282           (mixf result
283                 (psxhash (row-major-aref key i) depthoid))))
284        result))))
285
286 (defun structure-object-psxhash (key depthoid)
287   (declare (optimize speed))
288   (declare (type structure-object key))
289   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
290   (let* ((layout (%instance-layout key)) ; i.e. slot #0
291          (length (layout-length layout))
292          (classoid (layout-classoid layout))
293          (name (classoid-name classoid))
294          (result (mix (sxhash name) (the fixnum 79867))))
295     (declare (type fixnum result))
296     (dotimes (i (min depthoid (- length 1 (layout-n-untagged-slots layout))))
297       (declare (type fixnum i))
298       (let ((j (1+ i))) ; skipping slot #0, which is for LAYOUT
299         (declare (type fixnum j))
300         (mixf result
301               (psxhash (%instance-ref key j)
302                        (1- depthoid)))))
303     ;; KLUDGE: Should hash untagged slots, too.  (Although +max-hash-depthoid+
304     ;; is pretty low currently, so they might not make it into the hash
305     ;; value anyway.)
306     result))
307
308 (defun list-psxhash (key depthoid)
309   (declare (optimize speed))
310   (declare (type list key))
311   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
312   (cond ((null key)
313          (the fixnum 480929))
314         ((zerop depthoid)
315          (the fixnum 779578))
316         (t
317          (mix (psxhash (car key) (1- depthoid))
318               (psxhash (cdr key) (1- depthoid))))))
319
320 (defun hash-table-psxhash (key)
321   (declare (optimize speed))
322   (declare (type hash-table key))
323   (let ((result 103924836))
324     (declare (type fixnum result))
325     (mixf result (hash-table-count key))
326     (mixf result (sxhash (hash-table-test key)))
327     result))
328
329 (defun number-psxhash (key)
330   (declare (optimize speed))
331   (declare (type number key))
332   (flet ((sxhash-double-float (val)
333            (declare (type double-float val))
334            ;; FIXME: Check to make sure that the DEFTRANSFORM kicks in and the
335            ;; resulting code works without consing. (In Debian cmucl 2.4.17,
336            ;; it didn't.)
337            (sxhash val)))
338     (etypecase key
339       (integer (sxhash key))
340       (float (macrolet ((frob (type)
341                           (let ((lo (coerce most-negative-fixnum type))
342                                 (hi (coerce most-positive-fixnum type)))
343                             `(cond (;; This clause allows FIXNUM-sized integer
344                                     ;; values to be handled without consing.
345                                     (<= ,lo key ,hi)
346                                     (multiple-value-bind (q r)
347                                         (floor (the (,type ,lo ,hi) key))
348                                       (if (zerop (the ,type r))
349                                           (sxhash q)
350                                           (sxhash-double-float
351                                            (coerce key 'double-float)))))
352                                    (t
353                                     (multiple-value-bind (q r) (floor key)
354                                       (if (zerop (the ,type r))
355                                           (sxhash q)
356                                           (sxhash-double-float
357                                            (coerce key 'double-float)))))))))
358                (etypecase key
359                  (single-float (frob single-float))
360                  (double-float (frob double-float))
361                  #!+long-float
362                  (long-float (error "LONG-FLOAT not currently supported")))))
363       (rational (if (and (<= most-negative-double-float
364                              key
365                              most-positive-double-float)
366                          (= (coerce key 'double-float) key))
367                     (sxhash-double-float (coerce key 'double-float))
368                     (sxhash key)))
369       (complex (if (zerop (imagpart key))
370                    (number-psxhash (realpart key))
371                    (let ((result 330231))
372                      (declare (type fixnum result))
373                      (mixf result (number-psxhash (realpart key)))
374                      (mixf result (number-psxhash (imagpart key)))
375                      result))))))