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