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