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