1.0.4.92: faster generic array access
[sbcl.git] / src / code / array.lisp
1 ;;;; functions to implement arrays
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 #!-sb-fluid
15 (declaim (inline fill-pointer array-has-fill-pointer-p adjustable-array-p
16                  array-displacement))
17 \f
18 ;;;; miscellaneous accessor functions
19
20 ;;; These functions are only needed by the interpreter, 'cause the
21 ;;; compiler inlines them.
22 (macrolet ((def (name)
23              `(progn
24                 (defun ,name (array)
25                   (,name array))
26                 (defun (setf ,name) (value array)
27                   (setf (,name array) value)))))
28   (def %array-fill-pointer)
29   (def %array-fill-pointer-p)
30   (def %array-available-elements)
31   (def %array-data-vector)
32   (def %array-displacement)
33   (def %array-displaced-p))
34
35 (defun %array-rank (array)
36   (%array-rank array))
37
38 (defun %array-dimension (array axis)
39   (%array-dimension array axis))
40
41 (defun %set-array-dimension (array axis value)
42   (%set-array-dimension array axis value))
43
44 (defun %check-bound (array bound index)
45   (declare (type index bound)
46            (fixnum index))
47   (%check-bound array bound index))
48
49 (defun %with-array-data (array start end)
50   (%with-array-data-macro array start end :fail-inline? t))
51
52 (defun %data-vector-and-index (array index)
53   (if (array-header-p array)
54       (multiple-value-bind (vector index)
55           (%with-array-data array index nil)
56         (values vector index))
57       (values array index)))
58
59 ;;; It'd waste space to expand copies of error handling in every
60 ;;; inline %WITH-ARRAY-DATA, so we have them call this function
61 ;;; instead. This is just a wrapper which is known never to return.
62 (defun failed-%with-array-data (array start end)
63   (declare (notinline %with-array-data))
64   (%with-array-data array start end)
65   (bug "called FAILED-%WITH-ARRAY-DATA with valid array parameters?"))
66 \f
67 ;;;; MAKE-ARRAY
68 (eval-when (:compile-toplevel :execute)
69   (sb!xc:defmacro pick-vector-type (type &rest specs)
70     `(cond ,@(mapcar (lambda (spec)
71                        `(,(if (eq (car spec) t)
72                               t
73                               `(subtypep ,type ',(car spec)))
74                          ,@(cdr spec)))
75                      specs))))
76
77 ;;; These functions are used in the implementation of MAKE-ARRAY for
78 ;;; complex arrays. There are lots of transforms to simplify
79 ;;; MAKE-ARRAY for various easy cases, but not for all reasonable
80 ;;; cases, so e.g. as of sbcl-0.6.6 we still make full calls to
81 ;;; MAKE-ARRAY for any non-simple array. Thus, there's some value to
82 ;;; making this somewhat efficient, at least not doing full calls to
83 ;;; SUBTYPEP in the easy cases.
84 (defun %vector-widetag-and-n-bits (type)
85   (case type
86     ;; Pick off some easy common cases.
87     ;;
88     ;; (Perhaps we should make a much more exhaustive table of easy
89     ;; common cases here. Or perhaps the effort would be better spent
90     ;; on smarter compiler transforms which do the calculation once
91     ;; and for all in any reasonable user programs.)
92     ((t)
93      (values #.sb!vm:simple-vector-widetag #.sb!vm:n-word-bits))
94     ((base-char standard-char #!-sb-unicode character)
95      (values #.sb!vm:simple-base-string-widetag #.sb!vm:n-byte-bits))
96     #!+sb-unicode
97     ((character)
98      (values #.sb!vm:simple-character-string-widetag #.sb!vm:n-word-bits))
99     ((bit)
100      (values #.sb!vm:simple-bit-vector-widetag 1))
101     ;; OK, we have to wade into SUBTYPEPing after all.
102     (t
103      #.`(pick-vector-type type
104          ,@(map 'list
105                 (lambda (saetp)
106                   `(,(sb!vm:saetp-specifier saetp)
107                     (values ,(sb!vm:saetp-typecode saetp)
108                             ,(sb!vm:saetp-n-bits saetp))))
109                 sb!vm:*specialized-array-element-type-properties*)))))
110
111 (defun %complex-vector-widetag (type)
112   (case type
113     ;; Pick off some easy common cases.
114     ((t)
115      #.sb!vm:complex-vector-widetag)
116     ((base-char #!-sb-unicode character)
117      #.sb!vm:complex-base-string-widetag)
118     #!+sb-unicode
119     ((character)
120      #.sb!vm:complex-character-string-widetag)
121     ((nil)
122      #.sb!vm:complex-vector-nil-widetag)
123     ((bit)
124      #.sb!vm:complex-bit-vector-widetag)
125     ;; OK, we have to wade into SUBTYPEPing after all.
126     (t
127      (pick-vector-type type
128        (nil #.sb!vm:complex-vector-nil-widetag)
129        #!-sb-unicode
130        (character #.sb!vm:complex-base-string-widetag)
131        #!+sb-unicode
132        (base-char #.sb!vm:complex-base-string-widetag)
133        #!+sb-unicode
134        (character #.sb!vm:complex-character-string-widetag)
135        (bit #.sb!vm:complex-bit-vector-widetag)
136        (t #.sb!vm:complex-vector-widetag)))))
137
138 (defun make-array (dimensions &key
139                               (element-type t)
140                               (initial-element nil initial-element-p)
141                               (initial-contents nil initial-contents-p)
142                               adjustable fill-pointer
143                               displaced-to displaced-index-offset)
144   (let* ((dimensions (if (listp dimensions) dimensions (list dimensions)))
145          (array-rank (length (the list dimensions)))
146          (simple (and (null fill-pointer)
147                       (not adjustable)
148                       (null displaced-to))))
149     (declare (fixnum array-rank))
150     (when (and displaced-index-offset (null displaced-to))
151       (error "can't specify :DISPLACED-INDEX-OFFSET without :DISPLACED-TO"))
152     (when (and displaced-to
153                (arrayp displaced-to)
154                (not (equal (array-element-type displaced-to)
155                            (upgraded-array-element-type element-type))))
156       (error "Array element type of :DISPLACED-TO array does not match specified element type"))
157     (if (and simple (= array-rank 1))
158         ;; it's a (SIMPLE-ARRAY * (*))
159         (multiple-value-bind (type n-bits)
160             (%vector-widetag-and-n-bits element-type)
161           (declare (type (unsigned-byte 8) type)
162                    (type (integer 0 256) n-bits))
163           (let* ((length (car dimensions))
164                  (array (allocate-vector
165                          type
166                          length
167                          (ceiling
168                           (* (if (or (= type sb!vm:simple-base-string-widetag)
169                                      #!+sb-unicode
170                                      (= type
171                                         sb!vm:simple-character-string-widetag))
172                                  (1+ length)
173                                  length)
174                              n-bits)
175                           sb!vm:n-word-bits))))
176             (declare (type index length))
177             (when initial-element-p
178               (fill array initial-element))
179             (when initial-contents-p
180               (when initial-element-p
181                 (error "can't specify both :INITIAL-ELEMENT and ~
182                        :INITIAL-CONTENTS"))
183               (unless (= length (length initial-contents))
184                 (error "There are ~W elements in the :INITIAL-CONTENTS, but ~
185                        the vector length is ~W."
186                        (length initial-contents)
187                        length))
188               (replace array initial-contents))
189             array))
190         ;; it's either a complex array or a multidimensional array.
191         (let* ((total-size (reduce #'* dimensions))
192                (data (or displaced-to
193                          (data-vector-from-inits
194                           dimensions total-size element-type
195                           initial-contents initial-contents-p
196                           initial-element initial-element-p)))
197                (array (make-array-header
198                        (cond ((= array-rank 1)
199                               (%complex-vector-widetag element-type))
200                              (simple sb!vm:simple-array-widetag)
201                              (t sb!vm:complex-array-widetag))
202                        array-rank)))
203           (cond (fill-pointer
204                  (unless (= array-rank 1)
205                    (error "Only vectors can have fill pointers."))
206                  (let ((length (car dimensions)))
207                    (declare (fixnum length))
208                    (setf (%array-fill-pointer array)
209                      (cond ((eq fill-pointer t)
210                             length)
211                            (t
212                             (unless (and (fixnump fill-pointer)
213                                          (>= fill-pointer 0)
214                                          (<= fill-pointer length))
215                               ;; FIXME: should be TYPE-ERROR?
216                               (error "invalid fill-pointer ~W"
217                                      fill-pointer))
218                             fill-pointer))))
219                  (setf (%array-fill-pointer-p array) t))
220                 (t
221                  (setf (%array-fill-pointer array) total-size)
222                  (setf (%array-fill-pointer-p array) nil)))
223           (setf (%array-available-elements array) total-size)
224           (setf (%array-data-vector array) data)
225           (cond (displaced-to
226                  (when (or initial-element-p initial-contents-p)
227                    (error "Neither :INITIAL-ELEMENT nor :INITIAL-CONTENTS ~
228                    can be specified along with :DISPLACED-TO"))
229                  (let ((offset (or displaced-index-offset 0)))
230                    (when (> (+ offset total-size)
231                             (array-total-size displaced-to))
232                      (error "~S doesn't have enough elements." displaced-to))
233                    (setf (%array-displacement array) offset)
234                    (setf (%array-displaced-p array) t)))
235                 (t
236                  (setf (%array-displaced-p array) nil)))
237           (let ((axis 0))
238             (dolist (dim dimensions)
239               (setf (%array-dimension array axis) dim)
240               (incf axis)))
241           array))))
242
243 (defun make-static-vector (length &key
244                            (element-type '(unsigned-byte 8))
245                            (initial-contents nil initial-contents-p)
246                            (initial-element nil initial-element-p))
247   "Allocate vector of LENGTH elements in static space. Only allocation
248 of specialized arrays is supported."
249   ;; STEP 1: check inputs fully
250   ;;
251   ;; This way of doing explicit checks before the vector is allocated
252   ;; is expensive, but probably worth the trouble as once we've allocated
253   ;; the vector we have no way to get rid of it anymore...
254   (when (eq t (upgraded-array-element-type element-type))
255     (error "Static arrays of type ~S not supported."
256            element-type))
257   (when initial-contents-p
258     (when initial-element-p
259       (error "can't specify both :INITIAL-ELEMENT and :INITIAL-CONTENTS"))
260     (unless (= length (length initial-contents))
261       (error "There are ~W elements in the :INITIAL-CONTENTS, but the ~
262               vector length is ~W."
263              (length initial-contents)
264              length))
265     (unless (every (lambda (x) (typep x element-type)) initial-contents)
266       (error ":INITIAL-CONTENTS contains elements not of type ~S."
267              element-type)))
268   (when initial-element-p
269     (unless (typep initial-element element-type)
270       (error ":INITIAL-ELEMENT ~S is not of type ~S."
271              initial-element element-type)))
272   ;; STEP 2
273   ;;
274   ;; Allocate and possibly initialize the vector.
275   (multiple-value-bind (type n-bits)
276       (sb!impl::%vector-widetag-and-n-bits element-type)
277     (let ((vector
278            (allocate-static-vector type length
279                                    (ceiling (* length n-bits)
280                                             sb!vm:n-word-bits))))
281       (cond (initial-element-p
282              (fill vector initial-element))
283             (initial-contents-p
284              (replace vector initial-contents))
285             (t
286              vector)))))
287
288 ;;; DATA-VECTOR-FROM-INITS returns a simple vector that has the
289 ;;; specified array characteristics. Dimensions is only used to pass
290 ;;; to FILL-DATA-VECTOR for error checking on the structure of
291 ;;; initial-contents.
292 (defun data-vector-from-inits (dimensions total-size element-type
293                                initial-contents initial-contents-p
294                                initial-element initial-element-p)
295   (when (and initial-contents-p initial-element-p)
296     (error "cannot supply both :INITIAL-CONTENTS and :INITIAL-ELEMENT to
297             either MAKE-ARRAY or ADJUST-ARRAY."))
298   (let ((data (if initial-element-p
299                   (make-array total-size
300                               :element-type element-type
301                               :initial-element initial-element)
302                   (make-array total-size
303                               :element-type element-type))))
304     (cond (initial-element-p
305            (unless (simple-vector-p data)
306              (unless (typep initial-element element-type)
307                (error "~S cannot be used to initialize an array of type ~S."
308                       initial-element element-type))
309              (fill (the vector data) initial-element)))
310           (initial-contents-p
311            (fill-data-vector data dimensions initial-contents)))
312     data))
313
314 (defun vector (&rest objects)
315   #!+sb-doc
316   "Construct a SIMPLE-VECTOR from the given objects."
317   (coerce (the list objects) 'simple-vector))
318 \f
319
320 ;;;; accessor/setter functions
321
322 ;;; Dispatch to an optimized routine the data vector accessors for
323 ;;; each different specialized vector type. Do dispatching by looking
324 ;;; up the widetag in the array rather than with the typecases, which
325 ;;; as of 1.0.5 compiles to a naive sequence of linear TYPEPs. Also
326 ;;; provide separate versions where bounds checking has been moved
327 ;;; from the callee to the caller, since it's much cheaper to do once
328 ;;; the type information is available. Finally, for each of these
329 ;;; routines also provide a slow path, taken for arrays that are not
330 ;;; vectors or not simple.
331 (macrolet ((define (accessor-name slow-accessor-name table-name extra-params
332                                   check-bounds)
333              `(progn
334                 (defvar ,table-name)
335                 (defun ,accessor-name (array index ,@extra-params)
336                   (declare (optimize speed
337                                      ;; (SAFETY 0) is ok. All calls to
338                                      ;; these functions are generated by
339                                      ;; the compiler, so argument count
340                                      ;; checking isn't needed. Type checking
341                                      ;; is done implicitly via the widetag
342                                      ;; dispatch.
343                                      (safety 0)))
344                   #1=(funcall (the function
345                                 (let ((tag 0))
346                                   ;; WIDETAG-OF needs extra code to
347                                   ;; handle LIST and FUNCTION
348                                   ;; lowtags. We're only dispatching
349                                   ;; on other pointers, so let's do
350                                   ;; the lowtag extraction manually.
351                                   (when (sb!vm::%other-pointer-p array)
352                                     (setf tag (sb!sys:sap-ref-8
353                                                (int-sap (get-lisp-obj-address array))
354                                                (- sb!vm:other-pointer-lowtag))))
355                                   ;; SYMBOL-GLOBAL-VALUE is a performance hack
356                                   ;; for threaded builds.
357                                   (svref (sb!vm::symbol-global-value ',table-name)
358                                          tag)))
359                                 array index ,@extra-params))
360                 (defun ,slow-accessor-name (array index ,@extra-params)
361                   (declare (optimize speed (safety 0)))
362                   (if (not (%array-displaced-p array))
363                       ;; The reasonably quick path of non-displaced complex
364                       ;; arrays.
365                       (let ((array (%array-data-vector array)))
366                         #1#)
367                       ;; The real slow path.
368                       (with-array-data
369                           ((vector array)
370                            (index (locally
371                                       (declare (optimize (speed 1) (safety 1)))
372                                     (,@check-bounds index)))
373                            (end)
374                            :force-inline t)
375                         (declare (ignore end))
376                         (,accessor-name vector index ,@extra-params)))))))
377   (define hairy-data-vector-ref slow-hairy-data-vector-ref
378     *data-vector-reffers* nil (progn))
379   (define hairy-data-vector-set slow-hairy-data-vector-set
380     *data-vector-setters* (new-value) (progn))
381   (define hairy-data-vector-ref/check-bounds
382       slow-hairy-data-vector-ref/check-bounds
383     *data-vector-reffers/check-bounds* nil
384     (%check-bound array (array-dimension array 0)))
385   (define hairy-data-vector-set/check-bounds
386       slow-hairy-data-vector-set/check-bounds
387     *data-vector-setters/check-bounds* (new-value)
388     (%check-bound array (array-dimension array 0))))
389
390 (defun hairy-ref-error (array index &optional new-value)
391   (declare (ignore index new-value))
392   (error 'type-error
393          :datum array
394          :expected-type 'vector))
395
396 ;;; Populate the dispatch tables.
397 (macrolet ((define-reffer (saetp check-form)
398              (let* ((type (sb!vm:saetp-specifier saetp))
399                     (atype `(simple-array ,type (*))))
400                `(named-lambda optimized-data-vector-ref (vector index)
401                   (declare (optimize speed (safety 0)))
402                   (data-vector-ref (the ,atype vector)
403                                    (locally
404                                        (declare (optimize (safety 1)))
405                                      (the index
406                                        (,@check-form index)))))))
407            (define-setter (saetp check-form)
408              (let* ((type (sb!vm:saetp-specifier saetp))
409                     (atype `(simple-array ,type (*))))
410                `(named-lambda optimized-data-vector-set (vector index new-value)
411                   (declare (optimize speed (safety 0)))
412                   (data-vector-set (the ,atype vector)
413                                    (locally
414                                        (declare (optimize (safety 1)))
415                                      (the index
416                                        (,@check-form index)))
417                                    (locally
418                                        ;; SPEED 1 needed to avoid the compiler
419                                        ;; from downgrading the type check to
420                                        ;; a cheaper one.
421                                        (declare (optimize (speed 1)
422                                                           (safety 1)))
423                                      (the ,type new-value)))
424                   ;; For specialized arrays, the return from
425                   ;; data-vector-set would have to be reboxed to be a
426                   ;; (Lisp) return value; instead, we use the
427                   ;; already-boxed value as the return.
428                   new-value)))
429            (define-reffers (symbol deffer check-form slow-path)
430              `(progn
431                 (setf ,symbol (make-array sb!vm::widetag-mask
432                                           :initial-element #'hairy-ref-error))
433                 ,@(loop for widetag in '(sb!vm:complex-vector-widetag
434                                          sb!vm:complex-vector-nil-widetag
435                                          sb!vm:complex-bit-vector-widetag
436                                          sb!vm:complex-character-string-widetag
437                                          sb!vm:complex-base-string-widetag
438                                          sb!vm:simple-array-widetag
439                                          sb!vm:complex-array-widetag)
440                         collect `(setf (svref ,symbol ,widetag) ,slow-path))
441                 ,@(loop for saetp across sb!vm:*specialized-array-element-type-properties*
442                         for widetag = (sb!vm:saetp-typecode saetp)
443                         collect `(setf (svref ,symbol ,widetag)
444                                        (,deffer ,saetp ,check-form))))))
445   (defun !hairy-data-vector-reffer-init ()
446     (define-reffers *data-vector-reffers* define-reffer
447       (progn)
448       #'slow-hairy-data-vector-ref)
449     (define-reffers *data-vector-setters* define-setter
450       (progn)
451       #'slow-hairy-data-vector-set)
452     (define-reffers *data-vector-reffers/check-bounds* define-reffer
453       (%check-bound vector (length vector))
454       #'slow-hairy-data-vector-ref/check-bounds)
455     (define-reffers *data-vector-setters/check-bounds* define-setter
456       (%check-bound vector (length vector))
457       #'slow-hairy-data-vector-set/check-bounds)))
458
459 ;;; (Ordinary DATA-VECTOR-REF usage compiles into a vop, but
460 ;;; DATA-VECTOR-REF is also FOLDABLE, and this ordinary function
461 ;;; definition is needed for the compiler to use in constant folding.)
462 (defun data-vector-ref (array index)
463   (hairy-data-vector-ref array index))
464
465 ;;; SUBSCRIPTS has a dynamic-extent list structure and is destroyed
466 (defun %array-row-major-index (array subscripts
467                                      &optional (invalid-index-error-p t))
468   (declare (array array)
469            (list subscripts))
470   (let ((rank (array-rank array)))
471     (unless (= rank (length subscripts))
472       (error "wrong number of subscripts, ~W, for array of rank ~W"
473              (length subscripts) rank))
474     (if (array-header-p array)
475         (do ((subs (nreverse subscripts) (cdr subs))
476              (axis (1- (array-rank array)) (1- axis))
477              (chunk-size 1)
478              (result 0))
479             ((null subs) result)
480           (declare (list subs) (fixnum axis chunk-size result))
481           (let ((index (car subs))
482                 (dim (%array-dimension array axis)))
483             (declare (fixnum dim))
484             (unless (and (fixnump index) (< -1 index dim))
485               (if invalid-index-error-p
486                   (error 'simple-type-error
487                          :format-control "invalid index ~W~[~;~:; on axis ~:*~W~] in ~S"
488                          :format-arguments (list index axis array)
489                          :datum index
490                          :expected-type `(integer 0 (,dim)))
491                   (return-from %array-row-major-index nil)))
492             (incf result (* chunk-size (the fixnum index)))
493             (setf chunk-size (* chunk-size dim))))
494         (let ((index (first subscripts))
495               (length (length (the (simple-array * (*)) array))))
496           (unless (and (fixnump index) (< -1 index length))
497             (if invalid-index-error-p
498                 ;; FIXME: perhaps this should share a format-string
499                 ;; with INVALID-ARRAY-INDEX-ERROR or
500                 ;; INDEX-TOO-LARGE-ERROR?
501                 (error 'simple-type-error
502                        :format-control "invalid index ~W in ~S"
503                        :format-arguments (list index array)
504                        :datum index
505                        :expected-type `(integer 0 (,length)))
506                 (return-from %array-row-major-index nil)))
507           index))))
508
509 (defun array-in-bounds-p (array &rest subscripts)
510   #!+sb-doc
511   "Return T if the SUBSCIPTS are in bounds for the ARRAY, NIL otherwise."
512   (if (%array-row-major-index array subscripts nil)
513       t))
514
515 (defun array-row-major-index (array &rest subscripts)
516   (declare (dynamic-extent subscripts))
517   (%array-row-major-index array subscripts))
518
519 (defun aref (array &rest subscripts)
520   #!+sb-doc
521   "Return the element of the ARRAY specified by the SUBSCRIPTS."
522   (declare (dynamic-extent subscripts))
523   (row-major-aref array (%array-row-major-index array subscripts)))
524
525 (defun %aset (array &rest stuff)
526   (declare (dynamic-extent stuff))
527   (let ((subscripts (butlast stuff))
528         (new-value (car (last stuff))))
529     (setf (row-major-aref array (%array-row-major-index array subscripts))
530           new-value)))
531
532 ;;; FIXME: What's supposed to happen with functions
533 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
534 ;;; DEFSETF FOO is also defined? It seems as though the logical
535 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
536 ;;; and replace it with the (SETF FOO) function, issuing a warning,
537 ;;; just as for ordinary functions
538 ;;;  * (LISP-IMPLEMENTATION-VERSION)
539 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
540 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
541 ;;;  ZOO
542 ;;;  * (DEFUN ZOO (X) (* 3 X))
543 ;;;  Warning: ZOO previously defined as a macro.
544 ;;;  ZOO
545 ;;; But that doesn't seem to be what happens in CMU CL.
546 ;;;
547 ;;; KLUDGE: this is probably because ANSI, in its wisdom (CLHS
548 ;;; 5.1.2.5) requires implementations to support
549 ;;;   (SETF (APPLY #'AREF ...) ...)
550 ;;; [and also #'BIT and #'SBIT].  Yes, this is terrifying, and it's
551 ;;; also terrifying that this sequence of definitions causes it to
552 ;;; work.
553 ;;;
554 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
555 ;;; has a setf expansion and/or a setf function defined.
556
557 #!-sb-fluid (declaim (inline (setf aref)))
558 (defun (setf aref) (new-value array &rest subscripts)
559   (declare (dynamic-extent subscripts))
560   (declare (type array array))
561   (setf (row-major-aref array (%array-row-major-index array subscripts))
562         new-value))
563
564 (defun row-major-aref (array index)
565   #!+sb-doc
566   "Return the element of array corressponding to the row-major index. This is
567    SETF'able."
568   (declare (optimize (safety 1)))
569   (row-major-aref array index))
570
571 (defun %set-row-major-aref (array index new-value)
572   (declare (optimize (safety 1)))
573   (setf (row-major-aref array index) new-value))
574
575 (defun svref (simple-vector index)
576   #!+sb-doc
577   "Return the INDEX'th element of the given Simple-Vector."
578   (declare (optimize (safety 1)))
579   (aref simple-vector index))
580
581 (defun %svset (simple-vector index new)
582   (declare (optimize (safety 1)))
583   (setf (aref simple-vector index) new))
584
585 (defun bit (bit-array &rest subscripts)
586   #!+sb-doc
587   "Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
588   (declare (type (array bit) bit-array) (optimize (safety 1)))
589   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
590
591 (defun %bitset (bit-array &rest stuff)
592   (declare (type (array bit) bit-array) (optimize (safety 1)))
593   (let ((subscripts (butlast stuff))
594         (new-value (car (last stuff))))
595     (setf (row-major-aref bit-array
596                           (%array-row-major-index bit-array subscripts))
597           new-value)))
598
599 #!-sb-fluid (declaim (inline (setf bit)))
600 (defun (setf bit) (new-value bit-array &rest subscripts)
601   (declare (type (array bit) bit-array) (optimize (safety 1)))
602   (setf (row-major-aref bit-array
603                         (%array-row-major-index bit-array subscripts))
604         new-value))
605
606 (defun sbit (simple-bit-array &rest subscripts)
607   #!+sb-doc
608   "Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
609   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
610   (row-major-aref simple-bit-array
611                   (%array-row-major-index simple-bit-array subscripts)))
612
613 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
614 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
615 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
616 ;;; -- WHN 19990911
617 (defun %sbitset (simple-bit-array &rest stuff)
618   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
619   (let ((subscripts (butlast stuff))
620         (new-value (car (last stuff))))
621     (setf (row-major-aref simple-bit-array
622                           (%array-row-major-index simple-bit-array subscripts))
623           new-value)))
624
625 #!-sb-fluid (declaim (inline (setf sbit)))
626 (defun (setf sbit) (new-value bit-array &rest subscripts)
627   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
628   (setf (row-major-aref bit-array
629                         (%array-row-major-index bit-array subscripts))
630         new-value))
631 \f
632 ;;;; miscellaneous array properties
633
634 (defun array-element-type (array)
635   #!+sb-doc
636   "Return the type of the elements of the array"
637   (let ((widetag (widetag-of array)))
638     (macrolet ((pick-element-type (&rest stuff)
639                  `(cond ,@(mapcar (lambda (stuff)
640                                     (cons
641                                      (let ((item (car stuff)))
642                                        (cond ((eq item t)
643                                               t)
644                                              ((listp item)
645                                               (cons 'or
646                                                     (mapcar (lambda (x)
647                                                               `(= widetag ,x))
648                                                             item)))
649                                              (t
650                                               `(= widetag ,item))))
651                                      (cdr stuff)))
652                                   stuff))))
653       #.`(pick-element-type
654           ,@(map 'list
655                  (lambda (saetp)
656                    `(,(if (sb!vm:saetp-complex-typecode saetp)
657                           (list (sb!vm:saetp-typecode saetp)
658                                 (sb!vm:saetp-complex-typecode saetp))
659                           (sb!vm:saetp-typecode saetp))
660                      ',(sb!vm:saetp-specifier saetp)))
661                  sb!vm:*specialized-array-element-type-properties*)
662           ((sb!vm:simple-array-widetag
663             sb!vm:complex-vector-widetag
664             sb!vm:complex-array-widetag)
665            (with-array-data ((array array) (start) (end))
666              (declare (ignore start end))
667              (array-element-type array)))
668           (t
669            (error 'type-error :datum array :expected-type 'array))))))
670
671 (defun array-rank (array)
672   #!+sb-doc
673   "Return the number of dimensions of ARRAY."
674   (if (array-header-p array)
675       (%array-rank array)
676       1))
677
678 (defun array-dimension (array axis-number)
679   #!+sb-doc
680   "Return the length of dimension AXIS-NUMBER of ARRAY."
681   (declare (array array) (type index axis-number))
682   (cond ((not (array-header-p array))
683          (unless (= axis-number 0)
684            (error "Vector axis is not zero: ~S" axis-number))
685          (length (the (simple-array * (*)) array)))
686         ((>= axis-number (%array-rank array))
687          (error "Axis number ~W is too big; ~S only has ~D dimension~:P."
688                 axis-number array (%array-rank array)))
689         (t
690          ;; ANSI sayeth (ADJUST-ARRAY dictionary entry):
691          ;;
692          ;;   "If A is displaced to B, the consequences are
693          ;;   unspecified if B is adjusted in such a way that it no
694          ;;   longer has enough elements to satisfy A.
695          ;;
696          ;; In situations where this matters we should be doing a
697          ;; bounds-check, which in turn uses ARRAY-DIMENSION -- so
698          ;; this seems like a good place to signal an error.
699          (multiple-value-bind (target offset) (array-displacement array)
700            (when (and target
701                       (> (array-total-size array)
702                          (- (array-total-size target) offset)))
703                (error 'displaced-to-array-too-small-error
704                       :format-control "~@<The displaced-to array is too small. ~S ~
705                                       elements after offset required, ~S available.~:@>"
706                       :format-arguments (list (array-total-size array)
707                                               (- (array-total-size target) offset))))
708            (%array-dimension array axis-number)))))
709
710 (defun array-dimensions (array)
711   #!+sb-doc
712   "Return a list whose elements are the dimensions of the array"
713   (declare (array array))
714   (if (array-header-p array)
715       (do ((results nil (cons (array-dimension array index) results))
716            (index (1- (array-rank array)) (1- index)))
717           ((minusp index) results))
718       (list (array-dimension array 0))))
719
720 (defun array-total-size (array)
721   #!+sb-doc
722   "Return the total number of elements in the Array."
723   (declare (array array))
724   (if (array-header-p array)
725       (%array-available-elements array)
726       (length (the vector array))))
727
728 (defun array-displacement (array)
729   #!+sb-doc
730   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
731    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
732   (declare (type array array))
733   (if (and (array-header-p array) ; if unsimple and
734            (%array-displaced-p array)) ; displaced
735       (values (%array-data-vector array) (%array-displacement array))
736       (values nil 0)))
737
738 (defun adjustable-array-p (array)
739   #!+sb-doc
740   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
741    to the argument, this happens for complex arrays."
742   (declare (array array))
743   ;; Note that this appears not to be a fundamental limitation.
744   ;; non-vector SIMPLE-ARRAYs are in fact capable of being adjusted,
745   ;; but in practice we test using ADJUSTABLE-ARRAY-P in ADJUST-ARRAY.
746   ;; -- CSR, 2004-03-01.
747   (not (typep array 'simple-array)))
748 \f
749 ;;;; fill pointer frobbing stuff
750
751 (defun array-has-fill-pointer-p (array)
752   #!+sb-doc
753   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
754   (declare (array array))
755   (and (array-header-p array) (%array-fill-pointer-p array)))
756
757 (defun fill-pointer (vector)
758   #!+sb-doc
759   "Return the FILL-POINTER of the given VECTOR."
760   (declare (vector vector))
761   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
762       (%array-fill-pointer vector)
763       (error 'simple-type-error
764              :datum vector
765              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
766              :format-control "~S is not an array with a fill pointer."
767              :format-arguments (list vector))))
768
769 (defun %set-fill-pointer (vector new)
770   (declare (vector vector) (fixnum new))
771   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
772       (if (> new (%array-available-elements vector))
773         (error
774          "The new fill pointer, ~S, is larger than the length of the vector."
775          new)
776         (setf (%array-fill-pointer vector) new))
777       (error 'simple-type-error
778              :datum vector
779              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
780              :format-control "~S is not an array with a fill pointer."
781              :format-arguments (list vector))))
782
783 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
784 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
785 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
786 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
787 ;;; back to CMU CL).
788 (defun vector-push (new-el array)
789   #!+sb-doc
790   "Attempt to set the element of ARRAY designated by its fill pointer
791    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
792    too large, NIL is returned, otherwise the index of the pushed element is
793    returned."
794   (declare (vector array))
795   (let ((fill-pointer (fill-pointer array)))
796     (declare (fixnum fill-pointer))
797     (cond ((= fill-pointer (%array-available-elements array))
798            nil)
799           (t
800            (setf (aref array fill-pointer) new-el)
801            (setf (%array-fill-pointer array) (1+ fill-pointer))
802            fill-pointer))))
803
804 (defun vector-push-extend (new-element
805                            vector
806                            &optional
807                            (extension (1+ (length vector))))
808   (declare (vector vector) (fixnum extension))
809   (let ((fill-pointer (fill-pointer vector)))
810     (declare (fixnum fill-pointer))
811     (when (= fill-pointer (%array-available-elements vector))
812       (adjust-array vector (+ fill-pointer extension)))
813     ;; disable bounds checking
814     (locally (declare (optimize (safety 0)))
815       (setf (aref vector fill-pointer) new-element))
816     (setf (%array-fill-pointer vector) (1+ fill-pointer))
817     fill-pointer))
818
819 (defun vector-pop (array)
820   #!+sb-doc
821   "Decrease the fill pointer by 1 and return the element pointed to by the
822   new fill pointer."
823   (declare (vector array))
824   (let ((fill-pointer (fill-pointer array)))
825     (declare (fixnum fill-pointer))
826     (if (zerop fill-pointer)
827         (error "There is nothing left to pop.")
828         ;; disable bounds checking (and any fixnum test)
829         (locally (declare (optimize (safety 0)))
830           (aref array
831                 (setf (%array-fill-pointer array)
832                       (1- fill-pointer)))))))
833
834 \f
835 ;;;; ADJUST-ARRAY
836
837 (defun adjust-array (array dimensions &key
838                            (element-type (array-element-type array))
839                            (initial-element nil initial-element-p)
840                            (initial-contents nil initial-contents-p)
841                            fill-pointer
842                            displaced-to displaced-index-offset)
843   #!+sb-doc
844   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
845   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
846     (cond ((/= (the fixnum (length (the list dimensions)))
847                (the fixnum (array-rank array)))
848            (error "The number of dimensions not equal to rank of array."))
849           ((not (subtypep element-type (array-element-type array)))
850            (error "The new element type, ~S, is incompatible with old type."
851                   element-type))
852           ((and fill-pointer (not (array-has-fill-pointer-p array)))
853            (error 'type-error
854                   :datum array
855                   :expected-type '(satisfies array-has-fill-pointer-p))))
856     (let ((array-rank (length (the list dimensions))))
857       (declare (fixnum array-rank))
858       (unless (= array-rank 1)
859         (when fill-pointer
860           (error "Only vectors can have fill pointers.")))
861       (cond (initial-contents-p
862              ;; array former contents replaced by INITIAL-CONTENTS
863              (if (or initial-element-p displaced-to)
864                  (error "INITIAL-CONTENTS may not be specified with ~
865                          the :INITIAL-ELEMENT or :DISPLACED-TO option."))
866              (let* ((array-size (apply #'* dimensions))
867                     (array-data (data-vector-from-inits
868                                  dimensions array-size element-type
869                                  initial-contents initial-contents-p
870                                  initial-element initial-element-p)))
871                (if (adjustable-array-p array)
872                    (set-array-header array array-data array-size
873                                  (get-new-fill-pointer array array-size
874                                                        fill-pointer)
875                                  0 dimensions nil)
876                    (if (array-header-p array)
877                        ;; simple multidimensional or single dimensional array
878                        (make-array dimensions
879                                    :element-type element-type
880                                    :initial-contents initial-contents)
881                        array-data))))
882             (displaced-to
883              ;; We already established that no INITIAL-CONTENTS was supplied.
884              (when initial-element
885                (error "The :INITIAL-ELEMENT option may not be specified ~
886                        with :DISPLACED-TO."))
887              (unless (subtypep element-type (array-element-type displaced-to))
888                (error "can't displace an array of type ~S into another of ~
889                        type ~S"
890                       element-type (array-element-type displaced-to)))
891              (let ((displacement (or displaced-index-offset 0))
892                    (array-size (apply #'* dimensions)))
893                (declare (fixnum displacement array-size))
894                (if (< (the fixnum (array-total-size displaced-to))
895                       (the fixnum (+ displacement array-size)))
896                    (error "The :DISPLACED-TO array is too small."))
897                (if (adjustable-array-p array)
898                    ;; None of the original contents appear in adjusted array.
899                    (set-array-header array displaced-to array-size
900                                      (get-new-fill-pointer array array-size
901                                                            fill-pointer)
902                                      displacement dimensions t)
903                    ;; simple multidimensional or single dimensional array
904                    (make-array dimensions
905                                :element-type element-type
906                                :displaced-to displaced-to
907                                :displaced-index-offset
908                                displaced-index-offset))))
909             ((= array-rank 1)
910              (let ((old-length (array-total-size array))
911                    (new-length (car dimensions))
912                    new-data)
913                (declare (fixnum old-length new-length))
914                (with-array-data ((old-data array) (old-start)
915                                  (old-end old-length))
916                  (cond ((or (and (array-header-p array)
917                                  (%array-displaced-p array))
918                             (< old-length new-length))
919                         (setf new-data
920                               (data-vector-from-inits
921                                dimensions new-length element-type
922                                initial-contents initial-contents-p
923                                initial-element initial-element-p))
924                         (replace new-data old-data
925                                  :start2 old-start :end2 old-end))
926                        (t (setf new-data
927                                 (shrink-vector old-data new-length))))
928                  (if (adjustable-array-p array)
929                      (set-array-header array new-data new-length
930                                        (get-new-fill-pointer array new-length
931                                                              fill-pointer)
932                                        0 dimensions nil)
933                      new-data))))
934             (t
935              (let ((old-length (%array-available-elements array))
936                    (new-length (apply #'* dimensions)))
937                (declare (fixnum old-length new-length))
938                (with-array-data ((old-data array) (old-start)
939                                  (old-end old-length))
940                  (declare (ignore old-end))
941                  (let ((new-data (if (or (and (array-header-p array)
942                                               (%array-displaced-p array))
943                                          (> new-length old-length))
944                                      (data-vector-from-inits
945                                       dimensions new-length
946                                       element-type () nil
947                                       initial-element initial-element-p)
948                                      old-data)))
949                    (if (or (zerop old-length) (zerop new-length))
950                        (when initial-element-p (fill new-data initial-element))
951                        (zap-array-data old-data (array-dimensions array)
952                                        old-start
953                                        new-data dimensions new-length
954                                        element-type initial-element
955                                        initial-element-p))
956                    (if (adjustable-array-p array)
957                        (set-array-header array new-data new-length
958                                          new-length 0 dimensions nil)
959                        (let ((new-array
960                               (make-array-header
961                                sb!vm:simple-array-widetag array-rank)))
962                          (set-array-header new-array new-data new-length
963                                            new-length 0 dimensions nil)))))))))))
964
965
966 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
967   (cond ((not fill-pointer)
968          (when (array-has-fill-pointer-p old-array)
969            (when (> (%array-fill-pointer old-array) new-array-size)
970              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
971                      smaller than its fill pointer (~S)"
972                     old-array new-array-size (fill-pointer old-array)))
973            (%array-fill-pointer old-array)))
974         ((not (array-has-fill-pointer-p old-array))
975          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
976                  in ADJUST-ARRAY unless the array (~S) was originally ~
977                  created with a fill pointer"
978                 fill-pointer
979                 old-array))
980         ((numberp fill-pointer)
981          (when (> fill-pointer new-array-size)
982            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
983                    than the new length of the vector (~S)"
984                   fill-pointer new-array-size))
985          fill-pointer)
986         ((eq fill-pointer t)
987          new-array-size)
988         (t
989          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
990                 fill-pointer))))
991
992 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
993 ;;; which must be less than or equal to its current length. This can
994 ;;; be called on vectors without a fill pointer but it is extremely
995 ;;; dangerous to do so: shrinking the size of an object (as viewed by
996 ;;; the gc) makes bounds checking unreliable in the face of interrupts
997 ;;; or multi-threading. Call it only on provably local vectors.
998 (defun %shrink-vector (vector new-length)
999   (declare (vector vector))
1000   (unless (array-header-p vector)
1001     (macrolet ((frob (name &rest things)
1002                  `(etypecase ,name
1003                     ((simple-array nil (*)) (error 'nil-array-accessed-error))
1004                     ,@(mapcar (lambda (thing)
1005                                 (destructuring-bind (type-spec fill-value)
1006                                     thing
1007                                   `(,type-spec
1008                                     (fill (truly-the ,type-spec ,name)
1009                                           ,fill-value
1010                                           :start new-length))))
1011                               things))))
1012       ;; Set the 'tail' of the vector to the appropriate type of zero,
1013       ;; "because in some cases we'll scavenge larger areas in one go,
1014       ;; like groups of pages that had triggered the write barrier, or
1015       ;; the whole static space" according to jsnell.
1016       #.`(frob vector
1017           ,@(map 'list
1018                  (lambda (saetp)
1019                    `((simple-array ,(sb!vm:saetp-specifier saetp) (*))
1020                      ,(if (or (eq (sb!vm:saetp-specifier saetp) 'character)
1021                               #!+sb-unicode
1022                               (eq (sb!vm:saetp-specifier saetp) 'base-char))
1023                           *default-init-char-form*
1024                           (sb!vm:saetp-initial-element-default saetp))))
1025                  (remove-if-not
1026                   #'sb!vm:saetp-specifier
1027                   sb!vm:*specialized-array-element-type-properties*)))))
1028   ;; Only arrays have fill-pointers, but vectors have their length
1029   ;; parameter in the same place.
1030   (setf (%array-fill-pointer vector) new-length)
1031   vector)
1032
1033 (defun shrink-vector (vector new-length)
1034   (declare (vector vector))
1035   (cond
1036     ((eq (length vector) new-length)
1037      vector)
1038     ((array-has-fill-pointer-p vector)
1039      (setf (%array-fill-pointer vector) new-length)
1040      vector)
1041     (t (subseq vector 0 new-length))))
1042
1043 ;;; Fill in array header with the provided information, and return the array.
1044 (defun set-array-header (array data length fill-pointer displacement dimensions
1045                          &optional displacedp)
1046   (setf (%array-data-vector array) data)
1047   (setf (%array-available-elements array) length)
1048   (cond (fill-pointer
1049          (setf (%array-fill-pointer array) fill-pointer)
1050          (setf (%array-fill-pointer-p array) t))
1051         (t
1052          (setf (%array-fill-pointer array) length)
1053          (setf (%array-fill-pointer-p array) nil)))
1054   (setf (%array-displacement array) displacement)
1055   (if (listp dimensions)
1056       (dotimes (axis (array-rank array))
1057         (declare (type index axis))
1058         (setf (%array-dimension array axis) (pop dimensions)))
1059       (setf (%array-dimension array 0) dimensions))
1060   (setf (%array-displaced-p array) displacedp)
1061   array)
1062 \f
1063 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
1064
1065 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
1066 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice. This is rebound
1067 ;;; to length zero array in each new thread.
1068 ;;;
1069 ;;; DX is probably a bad idea, because a with a big array it would
1070 ;;; be fairly easy to blow the stack.
1071 (defvar *zap-array-data-temp* (vector))
1072 (declaim (simple-vector *zap-array-data-temp*))
1073
1074 (defun zap-array-data-temp (length initial-element initial-element-p)
1075   (declare (fixnum length))
1076   (let ((tmp *zap-array-data-temp*))
1077     (declare (simple-vector tmp))
1078     (cond ((> length (length tmp))
1079            (setf *zap-array-data-temp*
1080                  (if initial-element-p
1081                      (make-array length :initial-element initial-element)
1082                      (make-array length))))
1083           (initial-element-p
1084            (fill tmp initial-element :end length))
1085           (t
1086            tmp))))
1087
1088 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
1089 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
1090 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
1091 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
1092 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
1093                        element-type initial-element initial-element-p)
1094   (declare (list old-dims new-dims))
1095   ;; OLD-DIMS comes from array-dimensions, which returns a fresh list
1096   ;; at least in SBCL.
1097   ;; NEW-DIMS comes from the user.
1098   (setf old-dims (nreverse old-dims)
1099         new-dims (reverse new-dims))
1100   (cond ((eq old-data new-data)
1101          ;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and
1102          ;; INITIAL-ELEMENT-P are used when OLD-DATA and NEW-DATA are
1103          ;; EQ; in this case, a temporary must be used and filled
1104          ;; appropriately. specified initial-element.
1105          (when initial-element-p
1106            ;; FIXME: transforming this TYPEP to someting a bit faster
1107            ;; would be a win...
1108            (unless (typep initial-element element-type)
1109              (error "~S can't be used to initialize an array of type ~S."
1110                     initial-element element-type)))
1111          (without-interrupts
1112            ;; Need to disable interrupts while using the temp-vector.
1113            ;; An interrupt handler that also happened to call
1114            ;; ADJUST-ARRAY could otherwise stomp on our data here.
1115            (let ((temp (zap-array-data-temp new-length
1116                                             initial-element initial-element-p)))
1117              (declare (simple-vector temp))
1118              (zap-array-data-aux old-data old-dims offset temp new-dims)
1119              (dotimes (i new-length)
1120                (setf (aref new-data i) (aref temp i)
1121                      ;; zero out any garbage right away
1122                      (aref temp i) 0)))))
1123         (t
1124          ;; When OLD-DATA and NEW-DATA are not EQ, NEW-DATA has
1125          ;; already been filled with any
1126          (zap-array-data-aux old-data old-dims offset new-data new-dims))))
1127
1128 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
1129   (declare (fixnum offset))
1130   (let ((limits (mapcar (lambda (x y)
1131                           (declare (fixnum x y))
1132                           (1- (the fixnum (min x y))))
1133                         old-dims new-dims)))
1134     (macrolet ((bump-index-list (index limits)
1135                  `(do ((subscripts ,index (cdr subscripts))
1136                        (limits ,limits (cdr limits)))
1137                       ((null subscripts) :eof)
1138                     (cond ((< (the fixnum (car subscripts))
1139                               (the fixnum (car limits)))
1140                            (rplaca subscripts
1141                                    (1+ (the fixnum (car subscripts))))
1142                            (return ,index))
1143                           (t (rplaca subscripts 0))))))
1144       (do ((index (make-list (length old-dims) :initial-element 0)
1145                   (bump-index-list index limits)))
1146           ((eq index :eof))
1147         (setf (aref new-data (row-major-index-from-dims index new-dims))
1148               (aref old-data
1149                     (+ (the fixnum (row-major-index-from-dims index old-dims))
1150                        offset)))))))
1151
1152 ;;; Figure out the row-major-order index of an array reference from a
1153 ;;; list of subscripts and a list of dimensions. This is for internal
1154 ;;; calls only, and the subscripts and dim-list variables are assumed
1155 ;;; to be reversed from what the user supplied.
1156 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
1157   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
1158        (rev-dim-list rev-dim-list (cdr rev-dim-list))
1159        (chunk-size 1)
1160        (result 0))
1161       ((null rev-dim-list) result)
1162     (declare (fixnum chunk-size result))
1163     (setq result (+ result
1164                     (the fixnum (* (the fixnum (car rev-subscripts))
1165                                    chunk-size))))
1166     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
1167 \f
1168 ;;;; some bit stuff
1169
1170 (defun bit-array-same-dimensions-p (array1 array2)
1171   (declare (type (array bit) array1 array2))
1172   (and (= (array-rank array1)
1173           (array-rank array2))
1174        (dotimes (index (array-rank array1) t)
1175          (when (/= (array-dimension array1 index)
1176                    (array-dimension array2 index))
1177            (return nil)))))
1178
1179 (defun pick-result-array (result-bit-array bit-array-1)
1180   (case result-bit-array
1181     ((t) bit-array-1)
1182     ((nil) (make-array (array-dimensions bit-array-1)
1183                        :element-type 'bit
1184                        :initial-element 0))
1185     (t
1186      (unless (bit-array-same-dimensions-p bit-array-1
1187                                           result-bit-array)
1188        (error "~S and ~S don't have the same dimensions."
1189               bit-array-1 result-bit-array))
1190      result-bit-array)))
1191
1192 (defmacro def-bit-array-op (name function)
1193   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
1194      #!+sb-doc
1195      ,(format nil
1196               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
1197                BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
1198                If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1199                RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1200                All the arrays must have the same rank and dimensions."
1201               (symbol-name function))
1202      (declare (type (array bit) bit-array-1 bit-array-2)
1203               (type (or (array bit) (member t nil)) result-bit-array))
1204      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1205        (error "~S and ~S don't have the same dimensions."
1206               bit-array-1 bit-array-2))
1207      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1208        (if (and (simple-bit-vector-p bit-array-1)
1209                 (simple-bit-vector-p bit-array-2)
1210                 (simple-bit-vector-p result-bit-array))
1211            (locally (declare (optimize (speed 3) (safety 0)))
1212              (,name bit-array-1 bit-array-2 result-bit-array))
1213            (with-array-data ((data1 bit-array-1) (start1) (end1))
1214              (declare (ignore end1))
1215              (with-array-data ((data2 bit-array-2) (start2) (end2))
1216                (declare (ignore end2))
1217                (with-array-data ((data3 result-bit-array) (start3) (end3))
1218                  (do ((index-1 start1 (1+ index-1))
1219                       (index-2 start2 (1+ index-2))
1220                       (index-3 start3 (1+ index-3)))
1221                      ((>= index-3 end3) result-bit-array)
1222                    (declare (type index index-1 index-2 index-3))
1223                    (setf (sbit data3 index-3)
1224                          (logand (,function (sbit data1 index-1)
1225                                             (sbit data2 index-2))
1226                                  1))))))))))
1227
1228 (def-bit-array-op bit-and logand)
1229 (def-bit-array-op bit-ior logior)
1230 (def-bit-array-op bit-xor logxor)
1231 (def-bit-array-op bit-eqv logeqv)
1232 (def-bit-array-op bit-nand lognand)
1233 (def-bit-array-op bit-nor lognor)
1234 (def-bit-array-op bit-andc1 logandc1)
1235 (def-bit-array-op bit-andc2 logandc2)
1236 (def-bit-array-op bit-orc1 logorc1)
1237 (def-bit-array-op bit-orc2 logorc2)
1238
1239 (defun bit-not (bit-array &optional result-bit-array)
1240   #!+sb-doc
1241   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1242   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1243   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1244   created. Both arrays must have the same rank and dimensions."
1245   (declare (type (array bit) bit-array)
1246            (type (or (array bit) (member t nil)) result-bit-array))
1247   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1248     (if (and (simple-bit-vector-p bit-array)
1249              (simple-bit-vector-p result-bit-array))
1250         (locally (declare (optimize (speed 3) (safety 0)))
1251           (bit-not bit-array result-bit-array))
1252         (with-array-data ((src bit-array) (src-start) (src-end))
1253           (declare (ignore src-end))
1254           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1255             (do ((src-index src-start (1+ src-index))
1256                  (dst-index dst-start (1+ dst-index)))
1257                 ((>= dst-index dst-end) result-bit-array)
1258               (declare (type index src-index dst-index))
1259               (setf (sbit dst dst-index)
1260                     (logxor (sbit src src-index) 1))))))))