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