0.7.5.7:
[sbcl.git] / src / compiler / array-tran.lisp
1 ;;;; array-specific optimizers and transforms
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!C")
13 \f
14 ;;;; utilities for optimizing array operations
15
16 ;;; Return UPGRADED-ARRAY-ELEMENT-TYPE for CONTINUATION, or do
17 ;;; GIVE-UP-IR1-TRANSFORM if the upgraded element type can't be
18 ;;; determined.
19 (defun upgraded-element-type-specifier-or-give-up (continuation)
20   (let* ((element-ctype (extract-upgraded-element-type continuation))
21          (element-type-specifier (type-specifier element-ctype)))
22     (if (eq element-type-specifier '*)
23         (give-up-ir1-transform
24          "upgraded array element type not known at compile time")
25         element-type-specifier)))
26
27 ;;; Array access functions return an object from the array, hence its
28 ;;; type is going to be the array upgraded element type.
29 (defun extract-upgraded-element-type (array)
30   (let ((type (continuation-type array)))
31     (if (array-type-p type)
32         (array-type-specialized-element-type type)
33         *universal-type*)))
34
35 ;;; The ``new-value'' for array setters must fit in the array, and the
36 ;;; return type is going to be the same as the new-value for SETF
37 ;;; functions.
38 (defun assert-new-value-type (new-value array)
39   (let ((type (continuation-type array)))
40     (when (array-type-p type)
41       (assert-continuation-type new-value (array-type-specialized-element-type type))))
42   (continuation-type new-value))
43
44 ;;; Return true if Arg is NIL, or is a constant-continuation whose
45 ;;; value is NIL, false otherwise.
46 (defun unsupplied-or-nil (arg)
47   (declare (type (or continuation null) arg))
48   (or (not arg)
49       (and (constant-continuation-p arg)
50            (not (continuation-value arg)))))
51 \f
52 ;;;; DERIVE-TYPE optimizers
53
54 ;;; Array operations that use a specific number of indices implicitly
55 ;;; assert that the array is of that rank.
56 (defun assert-array-rank (array rank)
57   (assert-continuation-type
58    array
59    (specifier-type `(array * ,(make-list rank :initial-element '*)))))
60
61 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
62   (assert-array-rank array (length indices))
63   *universal-type*)
64
65 (defoptimizer (aref derive-type) ((array &rest indices) node)
66   (assert-array-rank array (length indices))
67   ;; If the node continuation has a single use then assert its type.
68   (let ((cont (node-cont node)))
69     (when (= (length (find-uses cont)) 1)
70       (assert-continuation-type cont (extract-upgraded-element-type array))))
71   (extract-upgraded-element-type array))
72
73 (defoptimizer (%aset derive-type) ((array &rest stuff))
74   (assert-array-rank array (1- (length stuff)))
75   (assert-new-value-type (car (last stuff)) array))
76
77 (defoptimizer (hairy-data-vector-ref derive-type) ((array index))
78   (extract-upgraded-element-type array))
79 (defoptimizer (data-vector-ref derive-type) ((array index))
80   (extract-upgraded-element-type array))
81
82 (defoptimizer (data-vector-set derive-type) ((array index new-value))
83   (assert-new-value-type new-value array))
84 (defoptimizer (hairy-data-vector-set derive-type) ((array index new-value))
85   (assert-new-value-type new-value array))
86
87 ;;; Figure out the type of the data vector if we know the argument
88 ;;; element type.
89 (defoptimizer (%with-array-data derive-type) ((array start end))
90   (let ((atype (continuation-type array)))
91     (when (array-type-p atype)
92       (values-specifier-type
93        `(values (simple-array ,(type-specifier
94                                 (array-type-specialized-element-type atype))
95                               (*))
96                 index index index)))))
97
98 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
99   (assert-array-rank array (length indices))
100   *universal-type*)
101
102 (defoptimizer (row-major-aref derive-type) ((array index))
103   (extract-upgraded-element-type array))
104
105 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
106   (assert-new-value-type new-value array))
107
108 (defoptimizer (make-array derive-type)
109               ((dims &key initial-element element-type initial-contents
110                 adjustable fill-pointer displaced-index-offset displaced-to))
111   (let ((simple (and (unsupplied-or-nil adjustable)
112                      (unsupplied-or-nil displaced-to)
113                      (unsupplied-or-nil fill-pointer))))
114     (specifier-type
115      `(,(if simple 'simple-array 'array)
116        ,(cond ((not element-type) t)
117               ((constant-continuation-p element-type)
118                (continuation-value element-type))
119               (t
120                '*))
121        ,(cond ((not simple)
122                '*)
123               ((constant-continuation-p dims)
124                (let ((val (continuation-value dims)))
125                  (if (listp val) val (list val))))
126               ((csubtypep (continuation-type dims)
127                           (specifier-type 'integer))
128                '(*))
129               (t
130                '*))))))
131 \f
132 ;;;; constructors
133
134 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
135 ;;; elements.
136 (define-source-transform vector (&rest elements)
137   (let ((len (length elements))
138         (n -1))
139     (once-only ((n-vec `(make-array ,len)))
140       `(progn
141          ,@(mapcar (lambda (el)
142                      (once-only ((n-val el))
143                        `(locally (declare (optimize (safety 0)))
144                                  (setf (svref ,n-vec ,(incf n))
145                                        ,n-val))))
146                    elements)
147          ,n-vec))))
148
149 ;;; Just convert it into a MAKE-ARRAY.
150 (define-source-transform make-string (length &key
151                                              (element-type ''base-char)
152                                              (initial-element
153                                               '#.*default-init-char-form*))
154   `(make-array (the index ,length)
155                :element-type ,element-type
156                :initial-element ,initial-element))
157
158 (defstruct (specialized-array-element-type-properties
159             (:conc-name saetp-)
160             (:constructor !make-saetp (ctype
161                                        initial-element-default
162                                        n-bits
163                                        typecode
164                                        &key
165                                        (n-pad-elements 0)))
166             (:copier nil))
167   ;; the element type, e.g. #<BUILT-IN-CLASS BASE-CHAR (sealed)> or
168   ;; #<SB-KERNEL:NUMERIC-TYPE (UNSIGNED-BYTE 4)>
169   (ctype (missing-arg) :type ctype :read-only t)
170   ;; what we get when the low-level vector-creation logic zeroes all
171   ;; the bits (which also serves as the default value of MAKE-ARRAY's
172   ;; :INITIAL-ELEMENT keyword)
173   (initial-element-default (missing-arg) :read-only t)
174   ;; how many bits per element
175   (n-bits (missing-arg) :type index :read-only t)
176   ;; the low-level type code
177   (typecode (missing-arg) :type index :read-only t)
178   ;; the number of extra elements we use at the end of the array for
179   ;; low level hackery (e.g., one element for arrays of BASE-CHAR,
180   ;; which is used for a fixed #\NULL so that when we call out to C
181   ;; we don't need to cons a new copy)
182   (n-pad-elements (missing-arg) :type index :read-only t))
183
184 (defparameter *specialized-array-element-type-properties*
185   (map 'simple-vector
186        (lambda (args)
187          (destructuring-bind (type-spec &rest rest) args
188            (let ((ctype (specifier-type type-spec)))
189              (apply #'!make-saetp ctype rest))))
190        `((base-char ,(code-char 0) 8 ,sb!vm:simple-string-widetag
191                     ;; (SIMPLE-STRINGs are stored with an extra trailing
192                     ;; #\NULL for convenience in calling out to C.)
193                     :n-pad-elements 1)
194          (single-float 0.0f0 32 ,sb!vm:simple-array-single-float-widetag)
195          (double-float 0.0d0 64 ,sb!vm:simple-array-double-float-widetag)
196          #!+long-float (long-float 0.0L0 #!+x86 96 #!+sparc 128
197                                    ,sb!vm:simple-array-long-float-widetag)
198          (bit 0 1 ,sb!vm:simple-bit-vector-widetag)
199          ;; KLUDGE: The fact that these UNSIGNED-BYTE entries come
200          ;; before their SIGNED-BYTE partners is significant in the
201          ;; implementation of the compiler; some of the cross-compiler
202          ;; code (see e.g. COERCE-TO-SMALLEST-ELTYPE in
203          ;; src/compiler/debug-dump.lisp) attempts to create an array
204          ;; specialized on (UNSIGNED-BYTE FOO), where FOO could be 7;
205          ;; (UNSIGNED-BYTE 7) is SUBTYPEP (SIGNED-BYTE 8), so if we're
206          ;; not careful we could get the wrong specialized array when
207          ;; we try to FIND-IF, below. -- CSR, 2002-07-08
208          ((unsigned-byte 2) 0 2 ,sb!vm:simple-array-unsigned-byte-2-widetag)
209          ((unsigned-byte 4) 0 4 ,sb!vm:simple-array-unsigned-byte-4-widetag)
210          ((unsigned-byte 8) 0 8 ,sb!vm:simple-array-unsigned-byte-8-widetag)
211          ((unsigned-byte 16) 0 16 ,sb!vm:simple-array-unsigned-byte-16-widetag)
212          ((unsigned-byte 32) 0 32 ,sb!vm:simple-array-unsigned-byte-32-widetag)
213          ((signed-byte 8) 0 8 ,sb!vm:simple-array-signed-byte-8-widetag)
214          ((signed-byte 16) 0 16 ,sb!vm:simple-array-signed-byte-16-widetag)
215          ((signed-byte 30) 0 32 ,sb!vm:simple-array-signed-byte-30-widetag)
216          ((signed-byte 32) 0 32 ,sb!vm:simple-array-signed-byte-32-widetag)
217          ((complex single-float) #C(0.0f0 0.0f0) 64
218           ,sb!vm:simple-array-complex-single-float-widetag)
219          ((complex double-float) #C(0.0d0 0.0d0) 128
220           ,sb!vm:simple-array-complex-double-float-widetag)
221          #!+long-float ((complex long-float) #C(0.0L0 0.0L0)
222                         #!+x86 192 #!+sparc 256
223                         ,sb!vm:simple-array-complex-long-float-widetag)
224          (t 0 32 ,sb!vm:simple-vector-widetag))))
225
226 (deftransform make-array ((dims &key initial-element element-type
227                                      adjustable fill-pointer)
228                           (t &rest *))
229   (when (null initial-element)
230     (give-up-ir1-transform))
231   (let* ((eltype (cond ((not element-type) t)
232                        ((not (constant-continuation-p element-type))
233                         (give-up-ir1-transform
234                          "ELEMENT-TYPE is not constant."))
235                        (t
236                         (continuation-value element-type))))
237          (eltype-type (specifier-type eltype))
238          (saetp (find-if (lambda (saetp)
239                            (csubtypep eltype-type (saetp-ctype saetp)))
240                          *specialized-array-element-type-properties*))
241          (creation-form `(make-array dims :element-type ',eltype
242                                      ,@(when fill-pointer
243                                          '(:fill-pointer fill-pointer))
244                                      ,@(when adjustable
245                                          '(:adjustable adjustable)))))
246
247     (unless saetp
248       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
249     
250     (cond ((or (null initial-element)
251                (and (constant-continuation-p initial-element)
252                     (eql (continuation-value initial-element)
253                          (saetp-initial-element-default saetp))))
254            (unless (csubtypep (ctype-of (saetp-initial-element-default saetp))
255                               eltype-type)
256              ;; This situation arises e.g. in (MAKE-ARRAY 4
257              ;; :ELEMENT-TYPE '(INTEGER 1 5)) ANSI's definition of
258              ;; MAKE-ARRAY says "If INITIAL-ELEMENT is not supplied,
259              ;; the consequences of later reading an uninitialized
260              ;; element of new-array are undefined," so this could be
261              ;; legal code as long as the user plans to write before
262              ;; he reads, and if he doesn't we're free to do anything
263              ;; we like. But in case the user doesn't know to write
264              ;; elements before he reads elements (or to read manuals
265              ;; before he writes code:-), we'll signal a STYLE-WARNING
266              ;; in case he didn't realize this.
267              (compiler-note "The default initial element ~S is not a ~S."
268                             (saetp-initial-element-default saetp)
269                             eltype))
270            creation-form)
271           (t
272            `(let ((array ,creation-form))
273              (multiple-value-bind (vector)
274                  (%data-vector-and-index array 0)
275                (fill vector initial-element))
276              array)))))
277                          
278 ;;; The integer type restriction on the length ensures that it will be
279 ;;; a vector. The lack of :ADJUSTABLE, :FILL-POINTER, and
280 ;;; :DISPLACED-TO keywords ensures that it will be simple; the lack of
281 ;;; :INITIAL-ELEMENT relies on another transform to deal with that
282 ;;; kind of initialization efficiently.
283 (deftransform make-array ((length &key element-type)
284                           (integer &rest *))
285   (let* ((eltype (cond ((not element-type) t)
286                        ((not (constant-continuation-p element-type))
287                         (give-up-ir1-transform
288                          "ELEMENT-TYPE is not constant."))
289                        (t
290                         (continuation-value element-type))))
291          (len (if (constant-continuation-p length)
292                   (continuation-value length)
293                   '*))
294          (result-type-spec `(simple-array ,eltype (,len)))
295          (eltype-type (specifier-type eltype))
296          (saetp (find-if (lambda (saetp)
297                            (csubtypep eltype-type (saetp-ctype saetp)))
298                          *specialized-array-element-type-properties*)))
299     (unless saetp
300       (give-up-ir1-transform
301        "cannot open-code creation of ~S" result-type-spec))
302
303     (let* ((n-bits-per-element (saetp-n-bits saetp))
304            (typecode (saetp-typecode saetp))
305            (n-pad-elements (saetp-n-pad-elements saetp))
306            (padded-length-form (if (zerop n-pad-elements)
307                                    'length
308                                    `(+ length ,n-pad-elements)))
309            (n-words-form
310             (if (>= n-bits-per-element sb!vm:n-word-bits)
311                 `(* ,padded-length-form
312                     (the fixnum ; i.e., not RATIO
313                       ,(/ n-bits-per-element sb!vm:n-word-bits)))
314                 (let ((n-elements-per-word (/ sb!vm:n-word-bits
315                                               n-bits-per-element)))
316                   (declare (type index n-elements-per-word)) ; i.e., not RATIO
317                   `(ceiling ,padded-length-form ,n-elements-per-word)))))
318       (values
319        `(truly-the ,result-type-spec
320          (allocate-vector ,typecode length ,n-words-form))
321        '((declare (type index length)))))))
322
323 ;;; The list type restriction does not ensure that the result will be a
324 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
325 ;;; and displaced-to keywords ensures that it will be simple.
326 ;;;
327 ;;; FIXME: should we generalize this transform to non-simple (though
328 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
329 ;;; deal with those? Maybe when the DEFTRANSFORM
330 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
331 ;;; CSR, 2002-07-01
332 (deftransform make-array ((dims &key element-type)
333                           (list &rest *))
334   (unless (or (null element-type) (constant-continuation-p element-type))
335     (give-up-ir1-transform
336      "The element-type is not constant; cannot open code array creation."))
337   (unless (constant-continuation-p dims)
338     (give-up-ir1-transform
339      "The dimension list is not constant; cannot open code array creation."))
340   (let ((dims (continuation-value dims)))
341     (unless (every #'integerp dims)
342       (give-up-ir1-transform
343        "The dimension list contains something other than an integer: ~S"
344        dims))
345     (if (= (length dims) 1)
346         `(make-array ',(car dims)
347                      ,@(when element-type
348                          '(:element-type element-type)))
349         (let* ((total-size (reduce #'* dims))
350                (rank (length dims))
351                (spec `(simple-array
352                        ,(cond ((null element-type) t)
353                               ((constant-continuation-p element-type)
354                                (continuation-value element-type))
355                               (t '*))
356                            ,(make-list rank :initial-element '*))))
357           `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank)))
358              (setf (%array-fill-pointer header) ,total-size)
359              (setf (%array-fill-pointer-p header) nil)
360              (setf (%array-available-elements header) ,total-size)
361              (setf (%array-data-vector header)
362                    (make-array ,total-size
363                                ,@(when element-type
364                                    '(:element-type element-type))))
365              (setf (%array-displaced-p header) nil)
366              ,@(let ((axis -1))
367                  (mapcar (lambda (dim)
368                            `(setf (%array-dimension header ,(incf axis))
369                                   ,dim))
370                          dims))
371              (truly-the ,spec header))))))
372 \f
373 ;;;; miscellaneous properties of arrays
374
375 ;;; Transforms for various array properties. If the property is know
376 ;;; at compile time because of a type spec, use that constant value.
377
378 ;;; If we can tell the rank from the type info, use it instead.
379 (deftransform array-rank ((array))
380   (let ((array-type (continuation-type array)))
381     (unless (array-type-p array-type)
382       (give-up-ir1-transform))
383     (let ((dims (array-type-dimensions array-type)))
384       (if (not (listp dims))
385           (give-up-ir1-transform
386            "The array rank is not known at compile time: ~S"
387            dims)
388           (length dims)))))
389
390 ;;; If we know the dimensions at compile time, just use it. Otherwise,
391 ;;; if we can tell that the axis is in bounds, convert to
392 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
393 ;;; (if it's simple and a vector).
394 (deftransform array-dimension ((array axis)
395                                (array index))
396   (unless (constant-continuation-p axis)
397     (give-up-ir1-transform "The axis is not constant."))
398   (let ((array-type (continuation-type array))
399         (axis (continuation-value axis)))
400     (unless (array-type-p array-type)
401       (give-up-ir1-transform))
402     (let ((dims (array-type-dimensions array-type)))
403       (unless (listp dims)
404         (give-up-ir1-transform
405          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
406       (unless (> (length dims) axis)
407         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
408                              dims
409                              axis))
410       (let ((dim (nth axis dims)))
411         (cond ((integerp dim)
412                dim)
413               ((= (length dims) 1)
414                (ecase (array-type-complexp array-type)
415                  ((t)
416                   '(%array-dimension array 0))
417                  ((nil)
418                   '(length array))
419                  ((:maybe)
420                   (give-up-ir1-transform
421                    "can't tell whether array is simple"))))
422               (t
423                '(%array-dimension array axis)))))))
424
425 ;;; If the length has been declared and it's simple, just return it.
426 (deftransform length ((vector)
427                       ((simple-array * (*))))
428   (let ((type (continuation-type vector)))
429     (unless (array-type-p type)
430       (give-up-ir1-transform))
431     (let ((dims (array-type-dimensions type)))
432       (unless (and (listp dims) (integerp (car dims)))
433         (give-up-ir1-transform
434          "Vector length is unknown, must call LENGTH at runtime."))
435       (car dims))))
436
437 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
438 ;;; simple, it will extract the length slot from the vector. It it's
439 ;;; complex, it will extract the fill pointer slot from the array
440 ;;; header.
441 (deftransform length ((vector) (vector))
442   '(vector-length vector))
443
444 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
445 ;;; compile-time constant.
446 (deftransform vector-length ((vector) ((simple-array * (*))))
447   (let ((vtype (continuation-type vector)))
448     (if (array-type-p vtype)
449         (let ((dim (first (array-type-dimensions vtype))))
450           (when (eq dim '*) (give-up-ir1-transform))
451           dim)
452         (give-up-ir1-transform))))
453
454 ;;; Again, if we can tell the results from the type, just use it.
455 ;;; Otherwise, if we know the rank, convert into a computation based
456 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
457 ;;; multiplications because we know that the total size must be an
458 ;;; INDEX.
459 (deftransform array-total-size ((array)
460                                 (array))
461   (let ((array-type (continuation-type array)))
462     (unless (array-type-p array-type)
463       (give-up-ir1-transform))
464     (let ((dims (array-type-dimensions array-type)))
465       (unless (listp dims)
466         (give-up-ir1-transform "can't tell the rank at compile time"))
467       (if (member '* dims)
468           (do ((form 1 `(truly-the index
469                                    (* (array-dimension array ,i) ,form)))
470                (i 0 (1+ i)))
471               ((= i (length dims)) form))
472           (reduce #'* dims)))))
473
474 ;;; Only complex vectors have fill pointers.
475 (deftransform array-has-fill-pointer-p ((array))
476   (let ((array-type (continuation-type array)))
477     (unless (array-type-p array-type)
478       (give-up-ir1-transform))
479     (let ((dims (array-type-dimensions array-type)))
480       (if (and (listp dims) (not (= (length dims) 1)))
481           nil
482           (ecase (array-type-complexp array-type)
483             ((t)
484              t)
485             ((nil)
486              nil)
487             ((:maybe)
488              (give-up-ir1-transform
489               "The array type is ambiguous; must call ~
490               ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
491
492 ;;; Primitive used to verify indices into arrays. If we can tell at
493 ;;; compile-time or we are generating unsafe code, don't bother with
494 ;;; the VOP.
495 (deftransform %check-bound ((array dimension index))
496   (unless (constant-continuation-p dimension)
497     (give-up-ir1-transform))
498   (let ((dim (continuation-value dimension)))
499     `(the (integer 0 ,dim) index)))
500 (deftransform %check-bound ((array dimension index) * *
501                             :policy (and (> speed safety) (= safety 0)))
502   'index)
503 \f
504 ;;;; WITH-ARRAY-DATA
505
506 ;;; This checks to see whether the array is simple and the start and
507 ;;; end are in bounds. If so, it proceeds with those values.
508 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
509 ;;; may be further optimized.
510 ;;;
511 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
512 ;;; START-VAR and END-VAR to the start and end of the designated
513 ;;; portion of the data vector. SVALUE and EVALUE are any start and
514 ;;; end specified to the original operation, and are factored into the
515 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
516 ;;; offset of all displacements encountered, and does not include
517 ;;; SVALUE.
518 ;;;
519 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
520 ;;; forced to be inline, overriding the ordinary judgment of the
521 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
522 ;;; fairly picky about their arguments, figuring that if you haven't
523 ;;; bothered to get all your ducks in a row, you probably don't care
524 ;;; that much about speed anyway! But in some cases it makes sense to
525 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
526 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
527 ;;; sense to use FORCE-INLINE option in that case.
528 (def!macro with-array-data (((data-var array &key offset-var)
529                              (start-var &optional (svalue 0))
530                              (end-var &optional (evalue nil))
531                              &key force-inline)
532                             &body forms)
533   (once-only ((n-array array)
534               (n-svalue `(the index ,svalue))
535               (n-evalue `(the (or index null) ,evalue)))
536     `(multiple-value-bind (,data-var
537                            ,start-var
538                            ,end-var
539                            ,@(when offset-var `(,offset-var)))
540          (if (not (array-header-p ,n-array))
541              (let ((,n-array ,n-array))
542                (declare (type (simple-array * (*)) ,n-array))
543                ,(once-only ((n-len `(length ,n-array))
544                             (n-end `(or ,n-evalue ,n-len)))
545                   `(if (<= ,n-svalue ,n-end ,n-len)
546                        ;; success
547                        (values ,n-array ,n-svalue ,n-end 0)
548                        (failed-%with-array-data ,n-array ,n-svalue ,n-evalue))))
549              (,(if force-inline '%with-array-data-macro '%with-array-data)
550               ,n-array ,n-svalue ,n-evalue))
551        ,@forms)))
552
553 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
554 ;;; DEFTRANSFORMs and DEFUNs.
555 (def!macro %with-array-data-macro (array
556                                    start
557                                    end
558                                    &key
559                                    (element-type '*)
560                                    unsafe?
561                                    fail-inline?)
562   (let ((size (gensym "SIZE-"))
563         (defaulted-end (gensym "DEFAULTED-END-"))
564         (data (gensym "DATA-"))
565         (cumulative-offset (gensym "CUMULATIVE-OFFSET-")))
566     `(let* ((,size (array-total-size ,array))
567             (,defaulted-end
568               (cond (,end
569                      (unless (or ,unsafe? (<= ,end ,size))
570                        ,(if fail-inline?
571                             `(error "End ~W is greater than total size ~W."
572                                     ,end ,size)
573                             `(failed-%with-array-data ,array ,start ,end)))
574                      ,end)
575                     (t ,size))))
576        (unless (or ,unsafe? (<= ,start ,defaulted-end))
577          ,(if fail-inline?
578               `(error "Start ~W is greater than end ~W." ,start ,defaulted-end)
579               `(failed-%with-array-data ,array ,start ,end)))
580        (do ((,data ,array (%array-data-vector ,data))
581             (,cumulative-offset 0
582                                 (+ ,cumulative-offset
583                                    (%array-displacement ,data))))
584            ((not (array-header-p ,data))
585             (values (the (simple-array ,element-type 1) ,data)
586                     (the index (+ ,cumulative-offset ,start))
587                     (the index (+ ,cumulative-offset ,defaulted-end))
588                     (the index ,cumulative-offset)))
589          (declare (type index ,cumulative-offset))))))
590
591 (deftransform %with-array-data ((array start end)
592                                 ;; It might very well be reasonable to
593                                 ;; allow general ARRAY here, I just
594                                 ;; haven't tried to understand the
595                                 ;; performance issues involved. --
596                                 ;; WHN, and also CSR 2002-05-26
597                                 ((or vector simple-array) index (or index null))
598                                 *
599                                 :important t
600                                 :node node
601                                 :policy (> speed space))
602   "inline non-SIMPLE-vector-handling logic"
603   (let ((element-type (upgraded-element-type-specifier-or-give-up array)))
604     `(%with-array-data-macro array start end
605                              :unsafe? ,(policy node (= safety 0))
606                              :element-type ,element-type)))
607 \f
608 ;;;; array accessors
609
610 ;;; We convert all typed array accessors into AREF and %ASET with type
611 ;;; assertions on the array.
612 (macrolet ((define-frob (reffer setter type)
613              `(progn
614                 (define-source-transform ,reffer (a &rest i)
615                   `(aref (the ,',type ,a) ,@i))
616                 (define-source-transform ,setter (a &rest i)
617                   `(%aset (the ,',type ,a) ,@i)))))
618   (define-frob svref %svset simple-vector)
619   (define-frob schar %scharset simple-string)
620   (define-frob char %charset string)
621   (define-frob sbit %sbitset (simple-array bit))
622   (define-frob bit %bitset (array bit)))
623
624 (macrolet (;; This is a handy macro for computing the row-major index
625            ;; given a set of indices. We wrap each index with a call
626            ;; to %CHECK-BOUND to ensure that everything works out
627            ;; correctly. We can wrap all the interior arithmetic with
628            ;; TRULY-THE INDEX because we know the the resultant
629            ;; row-major index must be an index.
630            (with-row-major-index ((array indices index &optional new-value)
631                                   &rest body)
632              `(let (n-indices dims)
633                 (dotimes (i (length ,indices))
634                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
635                   (push (make-symbol (format nil "DIM-~D" i)) dims))
636                 (setf n-indices (nreverse n-indices))
637                 (setf dims (nreverse dims))
638                 `(lambda (,',array ,@n-indices
639                                    ,@',(when new-value (list new-value)))
640                    (let* (,@(let ((,index -1))
641                               (mapcar (lambda (name)
642                                         `(,name (array-dimension
643                                                  ,',array
644                                                  ,(incf ,index))))
645                                       dims))
646                             (,',index
647                              ,(if (null dims)
648                                   0
649                                 (do* ((dims dims (cdr dims))
650                                       (indices n-indices (cdr indices))
651                                       (last-dim nil (car dims))
652                                       (form `(%check-bound ,',array
653                                                            ,(car dims)
654                                                            ,(car indices))
655                                             `(truly-the
656                                               index
657                                               (+ (truly-the index
658                                                             (* ,form
659                                                                ,last-dim))
660                                                  (%check-bound
661                                                   ,',array
662                                                   ,(car dims)
663                                                   ,(car indices))))))
664                                     ((null (cdr dims)) form)))))
665                      ,',@body)))))
666
667   ;; Just return the index after computing it.
668   (deftransform array-row-major-index ((array &rest indices))
669     (with-row-major-index (array indices index)
670       index))
671
672   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
673   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
674   ;; expression for the row major index.
675   (deftransform aref ((array &rest indices))
676     (with-row-major-index (array indices index)
677       (hairy-data-vector-ref array index)))
678   (deftransform %aset ((array &rest stuff))
679     (let ((indices (butlast stuff)))
680       (with-row-major-index (array indices index new-value)
681         (hairy-data-vector-set array index new-value)))))
682
683 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
684 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
685 ;;; array total size.
686 (deftransform row-major-aref ((array index))
687   `(hairy-data-vector-ref array
688                           (%check-bound array (array-total-size array) index)))
689 (deftransform %set-row-major-aref ((array index new-value))
690   `(hairy-data-vector-set array
691                           (%check-bound array (array-total-size array) index)
692                           new-value))
693 \f
694 ;;;; bit-vector array operation canonicalization
695 ;;;;
696 ;;;; We convert all bit-vector operations to have the result array
697 ;;;; specified. This allows any result allocation to be open-coded,
698 ;;;; and eliminates the need for any VM-dependent transforms to handle
699 ;;;; these cases.
700
701 (macrolet ((def (fun)
702              `(progn
703                (deftransform ,fun ((bit-array-1 bit-array-2
704                                                 &optional result-bit-array)
705                                    (bit-vector bit-vector &optional null) *
706                                    :policy (>= speed space))
707                  `(,',fun bit-array-1 bit-array-2
708                    (make-array (length bit-array-1) :element-type 'bit)))
709                ;; If result is T, make it the first arg.
710                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
711                                    (bit-vector bit-vector (member t)) *)
712                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
713   (def bit-and)
714   (def bit-ior)
715   (def bit-xor)
716   (def bit-eqv)
717   (def bit-nand)
718   (def bit-nor)
719   (def bit-andc1)
720   (def bit-andc2)
721   (def bit-orc1)
722   (def bit-orc2))
723
724 ;;; Similar for BIT-NOT, but there is only one arg...
725 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
726                        (bit-vector &optional null) *
727                        :policy (>= speed space))
728   '(bit-not bit-array-1
729             (make-array (length bit-array-1) :element-type 'bit)))
730 (deftransform bit-not ((bit-array-1 result-bit-array)
731                        (bit-vector (constant-arg t)))
732   '(bit-not bit-array-1 bit-array-1))
733 ;;; FIXME: What does (CONSTANT-ARG T) mean? Is it the same thing
734 ;;; as (CONSTANT-ARG (MEMBER T)), or does it mean any constant
735 ;;; value?
736 \f
737 ;;; Pick off some constant cases.
738 (deftransform array-header-p ((array) (array))
739   (let ((type (continuation-type array)))
740     (unless (array-type-p type)
741       (give-up-ir1-transform))
742     (let ((dims (array-type-dimensions type)))
743       (cond ((csubtypep type (specifier-type '(simple-array * (*))))
744              ;; no array header
745              nil)
746             ((and (listp dims) (> (length dims) 1))
747              ;; multi-dimensional array, will have a header
748              t)
749             (t
750              (give-up-ir1-transform))))))