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