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