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