Micro-optimize vector creation.
[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 LVAR, 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 (lvar)
20   (let ((element-type-specifier (upgraded-element-type-specifier lvar)))
21     (if (eq element-type-specifier '*)
22         (give-up-ir1-transform
23          "upgraded array element type not known at compile time")
24         element-type-specifier)))
25
26 (defun upgraded-element-type-specifier (lvar)
27   (type-specifier (array-type-upgraded-element-type (lvar-type lvar))))
28
29 ;;; Array access functions return an object from the array, hence its type is
30 ;;; going to be the array upgraded element type. Secondary return value is the
31 ;;; known supertype of the upgraded-array-element-type, if if the exact
32 ;;; U-A-E-T is not known. (If it is NIL, the primary return value is as good
33 ;;; as it gets.)
34 (defun array-type-upgraded-element-type (type)
35   (typecase type
36     ;; Note that this IF mightn't be satisfied even if the runtime
37     ;; value is known to be a subtype of some specialized ARRAY, because
38     ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
39     ;; which are represented in the compiler as INTERSECTION-TYPE, not
40     ;; array type.
41     (array-type
42      (values (array-type-specialized-element-type type) nil))
43     ;; Deal with intersection types (bug #316078)
44     (intersection-type
45      (let ((intersection-types (intersection-type-types type))
46            (element-type *wild-type*)
47            (element-supertypes nil))
48        (dolist (intersection-type intersection-types)
49          (multiple-value-bind (cur-type cur-supertype)
50              (array-type-upgraded-element-type intersection-type)
51            ;; According to ANSI, an array may have only one specialized
52            ;; element type - e.g. '(and (array foo) (array bar))
53            ;; is not a valid type unless foo and bar upgrade to the
54            ;; same element type.
55            (cond
56              ((eq cur-type *wild-type*)
57               nil)
58              ((eq element-type *wild-type*)
59               (setf element-type cur-type))
60              ((or (not (csubtypep cur-type element-type))
61                   (not (csubtypep element-type cur-type)))
62               ;; At least two different element types where given, the array
63               ;; is valid iff they represent the same type.
64               ;;
65               ;; FIXME: TYPE-INTERSECTION already takes care of disjoint array
66               ;; types, so I believe this code should be unreachable. Maybe
67               ;; signal a warning / error instead?
68               (setf element-type *empty-type*)))
69            (push (or cur-supertype (type-*-to-t cur-type))
70                  element-supertypes)))
71        (values element-type
72                (when (and (eq *wild-type* element-type) element-supertypes)
73                  (apply #'type-intersection element-supertypes)))))
74     (union-type
75      (let ((union-types (union-type-types type))
76            (element-type nil)
77            (element-supertypes nil))
78        (dolist (union-type union-types)
79          (multiple-value-bind (cur-type cur-supertype)
80              (array-type-upgraded-element-type union-type)
81            (cond
82              ((eq element-type *wild-type*)
83               nil)
84              ((eq element-type nil)
85               (setf element-type cur-type))
86              ((or (eq cur-type *wild-type*)
87                   ;; If each of the two following tests fail, it is not
88                   ;; possible to determine the element-type of the array
89                   ;; because more than one kind of element-type was provided
90                   ;; like in '(or (array foo) (array bar)) although a
91                   ;; supertype (or foo bar) may be provided as the second
92                   ;; returned value returned. See also the KLUDGE below.
93                   (not (csubtypep cur-type element-type))
94                   (not (csubtypep element-type cur-type)))
95               (setf element-type *wild-type*)))
96            (push (or cur-supertype (type-*-to-t cur-type))
97                  element-supertypes)))
98        (values element-type
99                (when (eq *wild-type* element-type)
100                  (apply #'type-union element-supertypes)))))
101     (member-type
102      ;; Convert member-type to an union-type.
103      (array-type-upgraded-element-type
104       (apply #'type-union (mapcar #'ctype-of (member-type-members type)))))
105     (t
106      ;; KLUDGE: there is no good answer here, but at least
107      ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
108      ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
109      ;; 2002-08-21
110      (values *wild-type* nil))))
111
112 (defun array-type-declared-element-type (type)
113   (if (array-type-p type)
114       (array-type-element-type type)
115       *wild-type*))
116
117 ;;; The ``new-value'' for array setters must fit in the array, and the
118 ;;; return type is going to be the same as the new-value for SETF
119 ;;; functions.
120 (defun assert-new-value-type (new-value array)
121   (let ((type (lvar-type array)))
122     (when (array-type-p type)
123       (assert-lvar-type
124        new-value
125        (array-type-specialized-element-type type)
126        (lexenv-policy (node-lexenv (lvar-dest new-value))))))
127   (lvar-type new-value))
128
129 ;;; Return true if ARG is NIL, or is a constant-lvar whose
130 ;;; value is NIL, false otherwise.
131 (defun unsupplied-or-nil (arg)
132   (declare (type (or lvar null) arg))
133   (or (not arg)
134       (and (constant-lvar-p arg)
135            (not (lvar-value arg)))))
136
137 (defun supplied-and-true (arg)
138   (and arg
139        (constant-lvar-p arg)
140        (lvar-value arg)
141        t))
142 \f
143 ;;;; DERIVE-TYPE optimizers
144
145 ;;; Array operations that use a specific number of indices implicitly
146 ;;; assert that the array is of that rank.
147 (defun assert-array-rank (array rank)
148   (assert-lvar-type
149    array
150    (specifier-type `(array * ,(make-list rank :initial-element '*)))
151    (lexenv-policy (node-lexenv (lvar-dest array)))))
152
153 (defun derive-aref-type (array)
154   (multiple-value-bind (uaet other)
155       (array-type-upgraded-element-type (lvar-type array))
156     (or other uaet)))
157
158 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
159   (assert-array-rank array (length indices))
160   *universal-type*)
161
162 (deftransform array-in-bounds-p ((array &rest subscripts))
163   (flet ((give-up ()
164            (give-up-ir1-transform
165             "~@<lower array bounds unknown or negative and upper bounds not ~
166              negative~:@>"))
167          (bound-known-p (x)
168            (integerp x))) ; might be NIL or *
169     (block nil
170       (let ((dimensions (array-type-dimensions-or-give-up
171                          (lvar-conservative-type array))))
172         ;; Might be *. (Note: currently this is never true, because the type
173         ;; derivation infers the rank from the call to ARRAY-IN-BOUNDS-P, but
174         ;; let's keep this future proof.)
175         (when (eq '* dimensions)
176           (give-up-ir1-transform "array bounds unknown"))
177         ;; shortcut for zero dimensions
178         (when (some (lambda (dim)
179                       (and (bound-known-p dim) (zerop dim)))
180                     dimensions)
181           (return nil))
182         ;; we first collect the subscripts LVARs' bounds and see whether
183         ;; we can already decide on the result of the optimization without
184         ;; even taking a look at the dimensions.
185         (flet ((subscript-bounds (subscript)
186                  (let* ((type1 (lvar-type subscript))
187                         (type2 (if (csubtypep type1 (specifier-type 'integer))
188                                    (weaken-integer-type type1 :range-only t)
189                                    (give-up)))
190                         (low (if (integer-type-p type2)
191                                  (numeric-type-low type2)
192                                  (give-up)))
193                         (high (numeric-type-high type2)))
194                    (cond
195                      ((and (or (not (bound-known-p low)) (minusp low))
196                            (or (not (bound-known-p high)) (not (minusp high))))
197                       ;; can't be sure about the lower bound and the upper bound
198                       ;; does not give us a definite clue either.
199                       (give-up))
200                      ((and (bound-known-p high) (minusp high))
201                       (return nil))     ; definitely below lower bound (zero).
202                      (t
203                       (cons low high))))))
204           (let* ((subscripts-bounds (mapcar #'subscript-bounds subscripts))
205                  (subscripts-lower-bound (mapcar #'car subscripts-bounds))
206                  (subscripts-upper-bound (mapcar #'cdr subscripts-bounds))
207                  (in-bounds 0))
208             (mapcar (lambda (low high dim)
209                       (cond
210                         ;; first deal with infinite bounds
211                         ((some (complement #'bound-known-p) (list low high dim))
212                          (when (and (bound-known-p dim) (bound-known-p low) (<= dim low))
213                            (return nil)))
214                         ;; now we know all bounds
215                         ((>= low dim)
216                          (return nil))
217                         ((< high dim)
218                          (aver (not (minusp low)))
219                          (incf in-bounds))
220                         (t
221                          (give-up))))
222                     subscripts-lower-bound
223                     subscripts-upper-bound
224                     dimensions)
225             (if (eql in-bounds (length dimensions))
226                 t
227                 (give-up))))))))
228
229 (defoptimizer (aref derive-type) ((array &rest indices) node)
230   (assert-array-rank array (length indices))
231   (derive-aref-type array))
232
233 (defoptimizer ((setf aref) derive-type) ((new-value array &rest subscripts))
234   (assert-array-rank array (length subscripts))
235   (assert-new-value-type new-value array))
236
237 (macrolet ((define (name)
238              `(defoptimizer (,name derive-type) ((array index))
239                 (derive-aref-type array))))
240   (define hairy-data-vector-ref)
241   (define hairy-data-vector-ref/check-bounds)
242   (define data-vector-ref))
243
244 #!+(or x86 x86-64)
245 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
246   (derive-aref-type array))
247
248 (macrolet ((define (name)
249              `(defoptimizer (,name derive-type) ((array index new-value))
250                 (assert-new-value-type new-value array))))
251   (define hairy-data-vector-set)
252   (define hairy-data-vector-set/check-bounds)
253   (define data-vector-set))
254
255 #!+(or x86 x86-64)
256 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
257   (assert-new-value-type new-value array))
258
259 ;;; Figure out the type of the data vector if we know the argument
260 ;;; element type.
261 (defun derive-%with-array-data/mumble-type (array)
262   (let ((atype (lvar-type array)))
263     (when (array-type-p atype)
264       (specifier-type
265        `(simple-array ,(type-specifier
266                         (array-type-specialized-element-type atype))
267                       (*))))))
268 (defoptimizer (%with-array-data derive-type) ((array start end))
269   (derive-%with-array-data/mumble-type array))
270 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
271   (derive-%with-array-data/mumble-type array))
272
273 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
274   (assert-array-rank array (length indices))
275   *universal-type*)
276
277 (defoptimizer (row-major-aref derive-type) ((array index))
278   (derive-aref-type array))
279
280 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
281   (assert-new-value-type new-value array))
282
283 (defoptimizer (make-array derive-type)
284               ((dims &key initial-element element-type initial-contents
285                 adjustable fill-pointer displaced-index-offset displaced-to))
286   (let* ((simple (and (unsupplied-or-nil adjustable)
287                       (unsupplied-or-nil displaced-to)
288                       (unsupplied-or-nil fill-pointer)))
289          (spec
290           (or `(,(if simple 'simple-array 'array)
291                  ,(cond ((not element-type) t)
292                         ((constant-lvar-p element-type)
293                          (let ((ctype (careful-specifier-type
294                                        (lvar-value element-type))))
295                            (cond
296                              ((or (null ctype) (unknown-type-p ctype)) '*)
297                              (t (sb!xc:upgraded-array-element-type
298                                  (lvar-value element-type))))))
299                         (t
300                          '*))
301                  ,(cond ((constant-lvar-p dims)
302                          (let* ((val (lvar-value dims))
303                                 (cdims (if (listp val) val (list val))))
304                            (if simple
305                                cdims
306                                (length cdims))))
307                         ((csubtypep (lvar-type dims)
308                                     (specifier-type 'integer))
309                          '(*))
310                         (t
311                          '*)))
312               'array)))
313     (if (and (not simple)
314              (or (supplied-and-true adjustable)
315                  (supplied-and-true displaced-to)
316                  (supplied-and-true fill-pointer)))
317         (careful-specifier-type `(and ,spec (not simple-array)))
318         (careful-specifier-type spec))))
319 \f
320 ;;;; constructors
321
322 ;;; Convert VECTOR into a MAKE-ARRAY.
323 (define-source-transform vector (&rest elements)
324   `(make-array ,(length elements) :initial-contents (list ,@elements)))
325
326 ;;; Just convert it into a MAKE-ARRAY.
327 (deftransform make-string ((length &key
328                                    (element-type 'character)
329                                    (initial-element
330                                     #.*default-init-char-form*)))
331   `(the simple-string (make-array (the index length)
332                        :element-type element-type
333                        ,@(when initial-element
334                            '(:initial-element initial-element)))))
335
336 (defun rewrite-initial-contents (rank initial-contents env)
337   (if (plusp rank)
338       (if (and (consp initial-contents)
339                (member (car initial-contents) '(list vector sb!impl::backq-list)))
340           `(list ,@(mapcar (lambda (dim)
341                              (rewrite-initial-contents (1- rank) dim env))
342                            (cdr initial-contents)))
343           initial-contents)
344       ;; This is the important bit: once we are past the level of
345       ;; :INITIAL-CONTENTS that relates to the array structure, reinline LIST
346       ;; and VECTOR so that nested DX isn't screwed up.
347       `(locally (declare (inline list vector))
348          ,initial-contents)))
349
350 ;;; Prevent open coding DIMENSION and :INITIAL-CONTENTS arguments, so that we
351 ;;; can pick them apart in the DEFTRANSFORMS, and transform '(3) style
352 ;;; dimensions to integer args directly.
353 (define-source-transform make-array (dimensions &rest keyargs &environment env)
354   (if (or (and (fun-lexically-notinline-p 'list)
355                (fun-lexically-notinline-p 'vector))
356           (oddp (length keyargs)))
357       (values nil t)
358       (multiple-value-bind (new-dimensions rank)
359           (flet ((constant-dims (dimensions)
360                    (let* ((dims (constant-form-value dimensions env))
361                           (canon (if (listp dims) dims (list dims)))
362                           (rank (length canon)))
363                      (values (if (= rank 1)
364                                  (list 'quote (car canon))
365                                  (list 'quote canon))
366                              rank))))
367             (cond ((sb!xc:constantp dimensions env)
368                    (constant-dims dimensions))
369                   ((and (consp dimensions) (eq 'list dimensions))
370                    (values dimensions (length (cdr dimensions))))
371                   (t
372                    (values dimensions nil))))
373         (let ((initial-contents (getf keyargs :initial-contents)))
374           (when (and initial-contents rank)
375             (setf keyargs (copy-list keyargs)
376                   (getf keyargs :initial-contents)
377                   (rewrite-initial-contents rank initial-contents env))))
378         `(locally (declare (notinline list vector))
379            (make-array ,new-dimensions ,@keyargs)))))
380
381 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
382 ;;; call which creates a vector with a known element type -- and tries
383 ;;; to do a good job with all the different ways it can happen.
384 (defun transform-make-array-vector (length element-type initial-element
385                                     initial-contents call)
386   (aver (or (not element-type) (constant-lvar-p element-type)))
387   (let* ((c-length (when (constant-lvar-p length)
388                      (lvar-value length)))
389          (elt-spec (if element-type
390                        (lvar-value element-type)
391                        t))
392          (elt-ctype (ir1-transform-specifier-type elt-spec))
393          (saetp (if (unknown-type-p elt-ctype)
394                     (give-up-ir1-transform "~S is an unknown type: ~S"
395                                            :element-type elt-spec)
396                     (find-saetp-by-ctype elt-ctype)))
397          (default-initial-element (sb!vm:saetp-initial-element-default saetp))
398          (n-bits (sb!vm:saetp-n-bits saetp))
399          (typecode (sb!vm:saetp-typecode saetp))
400          (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
401          (n-words-form
402           (if c-length
403               (ceiling (* (+ c-length n-pad-elements) n-bits)
404                        sb!vm:n-word-bits)
405               (let ((padded-length-form (if (zerop n-pad-elements)
406                                             'length
407                                             `(+ length ,n-pad-elements))))
408                 (cond
409                   ((= n-bits 0) 0)
410                   ((>= n-bits sb!vm:n-word-bits)
411                    `(* ,padded-length-form
412                        ;; i.e., not RATIO
413                        ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
414                   (t
415                    (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
416                      (declare (type index n-elements-per-word)) ; i.e., not RATIO
417                      `(ceiling (truly-the index ,padded-length-form)
418                                ,n-elements-per-word)))))))
419          (result-spec
420           `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
421          (alloc-form
422            `(truly-the ,result-spec
423                        (allocate-vector ,typecode (the index length) ,n-words-form))))
424     (cond ((and initial-element initial-contents)
425            (abort-ir1-transform "Both ~S and ~S specified."
426                                 :initial-contents :initial-element))
427           ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
428           ;; constant LENGTH.
429           ((and initial-contents c-length
430                 (lvar-matches initial-contents
431                               :fun-names '(list vector sb!impl::backq-list)
432                               :arg-count c-length))
433            (let ((parameters (eliminate-keyword-args
434                               call 1 '((:element-type element-type)
435                                        (:initial-contents initial-contents))))
436                  (elt-vars (make-gensym-list c-length))
437                  (lambda-list '(length)))
438              (splice-fun-args initial-contents :any c-length)
439              (dolist (p parameters)
440                (setf lambda-list
441                      (append lambda-list
442                              (if (eq p 'initial-contents)
443                                  elt-vars
444                                  (list p)))))
445              `(lambda ,lambda-list
446                 (declare (type ,elt-spec ,@elt-vars)
447                          (ignorable ,@lambda-list))
448                 (truly-the ,result-spec
449                  (initialize-vector ,alloc-form ,@elt-vars)))))
450           ;; constant :INITIAL-CONTENTS and LENGTH
451           ((and initial-contents c-length (constant-lvar-p initial-contents))
452            (let ((contents (lvar-value initial-contents)))
453              (unless (= c-length (length contents))
454                (abort-ir1-transform "~S has ~S elements, vector length is ~S."
455                                     :initial-contents (length contents) c-length))
456              (let ((parameters (eliminate-keyword-args
457                                 call 1 '((:element-type element-type)
458                                          (:initial-contents initial-contents)))))
459                `(lambda (length ,@parameters)
460                   (declare (ignorable ,@parameters))
461                   (truly-the ,result-spec
462                    (initialize-vector ,alloc-form
463                                       ,@(map 'list (lambda (elt)
464                                                      `(the ,elt-spec ',elt))
465                                              contents)))))))
466           ;; any other :INITIAL-CONTENTS
467           (initial-contents
468            (let ((parameters (eliminate-keyword-args
469                               call 1 '((:element-type element-type)
470                                        (:initial-contents initial-contents)))))
471              `(lambda (length ,@parameters)
472                 (declare (ignorable ,@parameters))
473                 (unless (= length (length initial-contents))
474                   (error "~S has ~S elements, vector length is ~S."
475                          :initial-contents (length initial-contents) length))
476                 (truly-the ,result-spec
477                            (replace ,alloc-form initial-contents)))))
478           ;; :INITIAL-ELEMENT, not EQL to the default
479           ((and initial-element
480                 (or (not (constant-lvar-p initial-element))
481                     (not (eql default-initial-element (lvar-value initial-element)))))
482            (let ((parameters (eliminate-keyword-args
483                               call 1 '((:element-type element-type)
484                                        (:initial-element initial-element))))
485                  (init (if (constant-lvar-p initial-element)
486                            (list 'quote (lvar-value initial-element))
487                            'initial-element)))
488              `(lambda (length ,@parameters)
489                 (declare (ignorable ,@parameters))
490                 (truly-the ,result-spec
491                            (fill ,alloc-form (the ,elt-spec ,init))))))
492           ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
493           ;; default
494           (t
495            #-sb-xc-host
496            (unless (ctypep default-initial-element elt-ctype)
497              ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
498              ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
499              ;; INITIAL-ELEMENT is not supplied, the consequences of later
500              ;; reading an uninitialized element of new-array are undefined,"
501              ;; so this could be legal code as long as the user plans to
502              ;; write before he reads, and if he doesn't we're free to do
503              ;; anything we like. But in case the user doesn't know to write
504              ;; elements before he reads elements (or to read manuals before
505              ;; he writes code:-), we'll signal a STYLE-WARNING in case he
506              ;; didn't realize this.
507              (if initial-element
508                  (compiler-warn "~S ~S is not a ~S"
509                                 :initial-element default-initial-element
510                                 elt-spec)
511                  (compiler-style-warn "The default initial element ~S is not a ~S."
512                                       default-initial-element
513                                       elt-spec)))
514            (let ((parameters (eliminate-keyword-args
515                               call 1 '((:element-type element-type)
516                                        (:initial-element initial-element)))))
517              `(lambda (length ,@parameters)
518                 (declare (ignorable ,@parameters))
519                 ,alloc-form))))))
520
521 ;;; IMPORTANT: The order of these three MAKE-ARRAY forms matters: the least
522 ;;; specific must come first, otherwise suboptimal transforms will result for
523 ;;; some forms.
524
525 (deftransform make-array ((dims &key initial-element element-type
526                                      adjustable fill-pointer)
527                           (t &rest *))
528   (when (null initial-element)
529     (give-up-ir1-transform))
530   (let* ((eltype (cond ((not element-type) t)
531                        ((not (constant-lvar-p element-type))
532                         (give-up-ir1-transform
533                          "ELEMENT-TYPE is not constant."))
534                        (t
535                         (lvar-value element-type))))
536          (eltype-type (ir1-transform-specifier-type eltype))
537          (saetp (find-if (lambda (saetp)
538                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
539                          sb!vm:*specialized-array-element-type-properties*))
540          (creation-form `(make-array dims
541                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
542                           ,@(when fill-pointer
543                                   '(:fill-pointer fill-pointer))
544                           ,@(when adjustable
545                                   '(:adjustable adjustable)))))
546
547     (unless saetp
548       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
549
550     (cond ((and (constant-lvar-p initial-element)
551                 (eql (lvar-value initial-element)
552                      (sb!vm:saetp-initial-element-default saetp)))
553            creation-form)
554           (t
555            ;; error checking for target, disabled on the host because
556            ;; (CTYPE-OF #\Null) is not possible.
557            #-sb-xc-host
558            (when (constant-lvar-p initial-element)
559              (let ((value (lvar-value initial-element)))
560                (cond
561                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
562                   ;; this case will cause an error at runtime, so we'd
563                   ;; better WARN about it now.
564                   (warn 'array-initial-element-mismatch
565                         :format-control "~@<~S is not a ~S (which is the ~
566                                          ~S of ~S).~@:>"
567                         :format-arguments
568                         (list
569                          value
570                          (type-specifier (sb!vm:saetp-ctype saetp))
571                          'upgraded-array-element-type
572                          eltype)))
573                  ((not (ctypep value eltype-type))
574                   ;; this case will not cause an error at runtime, but
575                   ;; it's still worth STYLE-WARNing about.
576                   (compiler-style-warn "~S is not a ~S."
577                                        value eltype)))))
578            `(let ((array ,creation-form))
579              (multiple-value-bind (vector)
580                  (%data-vector-and-index array 0)
581                (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
582              array)))))
583
584 ;;; The list type restriction does not ensure that the result will be a
585 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
586 ;;; and displaced-to keywords ensures that it will be simple.
587 ;;;
588 ;;; FIXME: should we generalize this transform to non-simple (though
589 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
590 ;;; deal with those? Maybe when the DEFTRANSFORM
591 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
592 ;;; CSR, 2002-07-01
593 (deftransform make-array ((dims &key
594                                 element-type initial-element initial-contents)
595                           (list &key
596                                 (:element-type (constant-arg *))
597                                 (:initial-element *)
598                                 (:initial-contents *))
599                           *
600                           :node call)
601   (block make-array
602     (when (lvar-matches dims :fun-names '(list) :arg-count 1)
603       (let ((length (car (splice-fun-args dims :any 1))))
604         (return-from make-array
605           (transform-make-array-vector length
606                                        element-type
607                                        initial-element
608                                        initial-contents
609                                        call))))
610     (unless (constant-lvar-p dims)
611       (give-up-ir1-transform
612        "The dimension list is not constant; cannot open code array creation."))
613     (let ((dims (lvar-value dims))
614           (element-type-ctype (and (constant-lvar-p element-type)
615                                    (ir1-transform-specifier-type
616                                     (lvar-value element-type)))))
617       (when (unknown-type-p element-type-ctype)
618         (give-up-ir1-transform))
619       (unless (every #'integerp dims)
620         (give-up-ir1-transform
621          "The dimension list contains something other than an integer: ~S"
622          dims))
623       (if (= (length dims) 1)
624           `(make-array ',(car dims)
625                        ,@(when element-type
626                                '(:element-type element-type))
627                        ,@(when initial-element
628                                '(:initial-element initial-element))
629                        ,@(when initial-contents
630                                '(:initial-contents initial-contents)))
631           (let* ((total-size (reduce #'* dims))
632                  (rank (length dims))
633                  (spec `(simple-array
634                          ,(cond ((null element-type) t)
635                                 (element-type-ctype
636                                  (sb!xc:upgraded-array-element-type
637                                   (lvar-value element-type)))
638                                 (t '*))
639                          ,(make-list rank :initial-element '*))))
640             `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
641                    (data (make-array ,total-size
642                                      ,@(when element-type
643                                              '(:element-type element-type))
644                                      ,@(when initial-element
645                                              '(:initial-element initial-element)))))
646                ,@(when initial-contents
647                        ;; FIXME: This is could be open coded at least a bit too
648                        `((sb!impl::fill-data-vector data ',dims initial-contents)))
649                (setf (%array-fill-pointer header) ,total-size)
650                (setf (%array-fill-pointer-p header) nil)
651                (setf (%array-available-elements header) ,total-size)
652                (setf (%array-data-vector header) data)
653                (setf (%array-displaced-p header) nil)
654                (setf (%array-displaced-from header) nil)
655                ,@(let ((axis -1))
656                       (mapcar (lambda (dim)
657                                 `(setf (%array-dimension header ,(incf axis))
658                                        ,dim))
659                               dims))
660                (truly-the ,spec header)))))))
661
662 (deftransform make-array ((dims &key element-type initial-element initial-contents)
663                           (integer &key
664                                    (:element-type (constant-arg *))
665                                    (:initial-element *)
666                                    (:initial-contents *))
667                           *
668                           :node call)
669   (transform-make-array-vector dims
670                                element-type
671                                initial-element
672                                initial-contents
673                                call))
674 \f
675 ;;;; miscellaneous properties of arrays
676
677 ;;; Transforms for various array properties. If the property is know
678 ;;; at compile time because of a type spec, use that constant value.
679
680 ;;; Most of this logic may end up belonging in code/late-type.lisp;
681 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
682 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
683 ;;; 2004-02-18
684 (defun array-type-dimensions-or-give-up (type)
685   (labels ((maybe-array-type-dimensions (type)
686              (typecase type
687                (array-type
688                 (array-type-dimensions type))
689                (union-type
690                 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
691                                                   (union-type-types type))))
692                        (result (car types)))
693                   (dolist (other (cdr types) result)
694                     (unless (equal result other)
695                       (give-up-ir1-transform
696                        "~@<dimensions of arrays in union type ~S do not match~:@>"
697                        (type-specifier type))))))
698                (intersection-type
699                 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
700                                                   (intersection-type-types type))))
701                        (result (car types)))
702                   (dolist (other (cdr types) result)
703                     (unless (equal result other)
704                       (abort-ir1-transform
705                        "~@<dimensions of arrays in intersection type ~S do not match~:@>"
706                        (type-specifier type)))))))))
707     (or (maybe-array-type-dimensions type)
708         (give-up-ir1-transform
709          "~@<don't know how to extract array dimensions from type ~S~:@>"
710          (type-specifier type)))))
711
712 (defun conservative-array-type-complexp (type)
713   (typecase type
714     (array-type (array-type-complexp type))
715     (union-type
716      (let ((types (union-type-types type)))
717        (aver (> (length types) 1))
718        (let ((result (conservative-array-type-complexp (car types))))
719          (dolist (type (cdr types) result)
720            (unless (eq (conservative-array-type-complexp type) result)
721              (return-from conservative-array-type-complexp :maybe))))))
722     ;; FIXME: intersection type
723     (t :maybe)))
724
725 ;;; If we can tell the rank from the type info, use it instead.
726 (deftransform array-rank ((array) (array) * :node node)
727   (let ((array-type (lvar-type array)))
728     (let ((dims (array-type-dimensions-or-give-up array-type)))
729       (cond ((listp dims)
730              (length dims))
731             ((eq t (and (array-type-p array-type)
732                         (array-type-complexp array-type)))
733              '(%array-rank array))
734             (t
735              (delay-ir1-transform node :constraint)
736              `(if (array-header-p array)
737                   (%array-rank array)
738                   1))))))
739
740 ;;; If we know the dimensions at compile time, just use it. Otherwise,
741 ;;; if we can tell that the axis is in bounds, convert to
742 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
743 ;;; (if it's simple and a vector).
744 (deftransform array-dimension ((array axis)
745                                (array index))
746   (unless (constant-lvar-p axis)
747     (give-up-ir1-transform "The axis is not constant."))
748   ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
749   ;; conservative type.
750   (let ((array-type (lvar-conservative-type array))
751         (axis (lvar-value axis)))
752     (let ((dims (array-type-dimensions-or-give-up array-type)))
753       (unless (listp dims)
754         (give-up-ir1-transform
755          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
756       (unless (> (length dims) axis)
757         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
758                              dims
759                              axis))
760       (let ((dim (nth axis dims)))
761         (cond ((integerp dim)
762                dim)
763               ((= (length dims) 1)
764                (ecase (conservative-array-type-complexp array-type)
765                  ((t)
766                   '(%array-dimension array 0))
767                  ((nil)
768                   '(vector-length array))
769                  ((:maybe)
770                   `(if (array-header-p array)
771                        (%array-dimension array axis)
772                        (vector-length array)))))
773               (t
774                '(%array-dimension array axis)))))))
775
776 ;;; If the length has been declared and it's simple, just return it.
777 (deftransform length ((vector)
778                       ((simple-array * (*))))
779   (let ((type (lvar-type vector)))
780     (let ((dims (array-type-dimensions-or-give-up type)))
781       (unless (and (listp dims) (integerp (car dims)))
782         (give-up-ir1-transform
783          "Vector length is unknown, must call LENGTH at runtime."))
784       (car dims))))
785
786 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
787 ;;; simple, it will extract the length slot from the vector. It it's
788 ;;; complex, it will extract the fill pointer slot from the array
789 ;;; header.
790 (deftransform length ((vector) (vector))
791   '(vector-length vector))
792
793 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
794 ;;; compile-time constant.
795 (deftransform vector-length ((vector))
796   (let ((vtype (lvar-type vector)))
797     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
798       (when (eq dim '*)
799         (give-up-ir1-transform))
800       (when (conservative-array-type-complexp vtype)
801         (give-up-ir1-transform))
802       dim)))
803
804 ;;; Again, if we can tell the results from the type, just use it.
805 ;;; Otherwise, if we know the rank, convert into a computation based
806 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
807 ;;; multiplications because we know that the total size must be an
808 ;;; INDEX.
809 (deftransform array-total-size ((array)
810                                 (array))
811   (let ((array-type (lvar-type array)))
812     (let ((dims (array-type-dimensions-or-give-up array-type)))
813       (unless (listp dims)
814         (give-up-ir1-transform "can't tell the rank at compile time"))
815       (if (member '* dims)
816           (do ((form 1 `(truly-the index
817                                    (* (array-dimension array ,i) ,form)))
818                (i 0 (1+ i)))
819               ((= i (length dims)) form))
820           (reduce #'* dims)))))
821
822 ;;; Only complex vectors have fill pointers.
823 (deftransform array-has-fill-pointer-p ((array))
824   (let ((array-type (lvar-type array)))
825     (let ((dims (array-type-dimensions-or-give-up array-type)))
826       (if (and (listp dims) (not (= (length dims) 1)))
827           nil
828           (ecase (conservative-array-type-complexp array-type)
829             ((t)
830              t)
831             ((nil)
832              nil)
833             ((:maybe)
834              (give-up-ir1-transform
835               "The array type is ambiguous; must call ~
836                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
837
838 ;;; Primitive used to verify indices into arrays. If we can tell at
839 ;;; compile-time or we are generating unsafe code, don't bother with
840 ;;; the VOP.
841 (deftransform %check-bound ((array dimension index) * * :node node)
842   (cond ((policy node (= insert-array-bounds-checks 0))
843          'index)
844         ((not (constant-lvar-p dimension))
845          (give-up-ir1-transform))
846         (t
847          (let ((dim (lvar-value dimension)))
848            ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
849            `(the (integer 0 (,dim)) index)))))
850 \f
851 ;;;; WITH-ARRAY-DATA
852
853 ;;; This checks to see whether the array is simple and the start and
854 ;;; end are in bounds. If so, it proceeds with those values.
855 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
856 ;;; may be further optimized.
857 ;;;
858 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
859 ;;; START-VAR and END-VAR to the start and end of the designated
860 ;;; portion of the data vector. SVALUE and EVALUE are any start and
861 ;;; end specified to the original operation, and are factored into the
862 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
863 ;;; offset of all displacements encountered, and does not include
864 ;;; SVALUE.
865 ;;;
866 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
867 ;;; forced to be inline, overriding the ordinary judgment of the
868 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
869 ;;; fairly picky about their arguments, figuring that if you haven't
870 ;;; bothered to get all your ducks in a row, you probably don't care
871 ;;; that much about speed anyway! But in some cases it makes sense to
872 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
873 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
874 ;;; sense to use FORCE-INLINE option in that case.
875 (def!macro with-array-data (((data-var array &key offset-var)
876                              (start-var &optional (svalue 0))
877                              (end-var &optional (evalue nil))
878                              &key force-inline check-fill-pointer)
879                             &body forms
880                             &environment env)
881   (once-only ((n-array array)
882               (n-svalue `(the index ,svalue))
883               (n-evalue `(the (or index null) ,evalue)))
884     (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
885       `(multiple-value-bind (,data-var
886                              ,start-var
887                              ,end-var
888                              ,@(when offset-var `(,offset-var)))
889            (if (not (array-header-p ,n-array))
890                (let ((,n-array ,n-array))
891                  (declare (type (simple-array * (*)) ,n-array))
892                  ,(once-only ((n-len (if check-fill-pointer
893                                          `(length ,n-array)
894                                          `(array-total-size ,n-array)))
895                               (n-end `(or ,n-evalue ,n-len)))
896                              (if check-bounds
897                                  `(if (<= 0 ,n-svalue ,n-end ,n-len)
898                                       (values ,n-array ,n-svalue ,n-end 0)
899                                       ,(if check-fill-pointer
900                                            `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
901                                            `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
902                                  `(values ,n-array ,n-svalue ,n-end 0))))
903                ,(if force-inline
904                     `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
905                                              :check-bounds ,check-bounds
906                                              :check-fill-pointer ,check-fill-pointer)
907                     (if check-fill-pointer
908                         `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
909                         `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
910          ,@forms))))
911
912 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
913 ;;; DEFTRANSFORMs and DEFUNs.
914 (def!macro %with-array-data-macro (array
915                                    start
916                                    end
917                                    &key
918                                    (element-type '*)
919                                    check-bounds
920                                    check-fill-pointer)
921   (with-unique-names (size defaulted-end data cumulative-offset)
922     `(let* ((,size ,(if check-fill-pointer
923                         `(length ,array)
924                         `(array-total-size ,array)))
925             (,defaulted-end (or ,end ,size)))
926        ,@(when check-bounds
927                `((unless (<= ,start ,defaulted-end ,size)
928                    ,(if check-fill-pointer
929                         `(sequence-bounding-indices-bad-error ,array ,start ,end)
930                         `(array-bounding-indices-bad-error ,array ,start ,end)))))
931        (do ((,data ,array (%array-data-vector ,data))
932             (,cumulative-offset 0
933                                 (+ ,cumulative-offset
934                                    (%array-displacement ,data))))
935            ((not (array-header-p ,data))
936             (values (the (simple-array ,element-type 1) ,data)
937                     (the index (+ ,cumulative-offset ,start))
938                     (the index (+ ,cumulative-offset ,defaulted-end))
939                     (the index ,cumulative-offset)))
940          (declare (type index ,cumulative-offset))))))
941
942 (defun transform-%with-array-data/muble (array node check-fill-pointer)
943   (let ((element-type (upgraded-element-type-specifier-or-give-up array))
944         (type (lvar-type array))
945         (check-bounds (policy node (plusp insert-array-bounds-checks))))
946     (if (and (array-type-p type)
947              (not (array-type-complexp type))
948              (listp (array-type-dimensions type))
949              (not (null (cdr (array-type-dimensions type)))))
950         ;; If it's a simple multidimensional array, then just return
951         ;; its data vector directly rather than going through
952         ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
953         ;; code that would use this currently, but we have encouraged
954         ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
955         ;; some point in the future for optimized libraries or
956         ;; similar.
957         (if check-bounds
958             `(let* ((data (truly-the (simple-array ,element-type (*))
959                                      (%array-data-vector array)))
960                     (len (length data))
961                     (real-end (or end len)))
962                (unless (<= 0 start data-end lend)
963                  (sequence-bounding-indices-bad-error array start end))
964                (values data 0 real-end 0))
965             `(let ((data (truly-the (simple-array ,element-type (*))
966                                     (%array-data-vector array))))
967                (values data 0 (or end (length data)) 0)))
968         `(%with-array-data-macro array start end
969                                  :check-fill-pointer ,check-fill-pointer
970                                  :check-bounds ,check-bounds
971                                  :element-type ,element-type))))
972
973 ;; It might very well be reasonable to allow general ARRAY here, I
974 ;; just haven't tried to understand the performance issues involved.
975 ;; -- WHN, and also CSR 2002-05-26
976 (deftransform %with-array-data ((array start end)
977                                 ((or vector simple-array) index (or index null) t)
978                                 *
979                                 :node node
980                                 :policy (> speed space))
981   "inline non-SIMPLE-vector-handling logic"
982   (transform-%with-array-data/muble array node nil))
983 (deftransform %with-array-data/fp ((array start end)
984                                 ((or vector simple-array) index (or index null) t)
985                                 *
986                                 :node node
987                                 :policy (> speed space))
988   "inline non-SIMPLE-vector-handling logic"
989   (transform-%with-array-data/muble array node t))
990 \f
991 ;;;; array accessors
992
993 ;;; We convert all typed array accessors into AREF and (SETF AREF) with type
994 ;;; assertions on the array.
995 (macrolet ((define-bit-frob (reffer simplep)
996              `(progn
997                 (define-source-transform ,reffer (a &rest i)
998                   `(aref (the (,',(if simplep 'simple-array 'array)
999                                   bit
1000                                   ,(mapcar (constantly '*) i))
1001                            ,a) ,@i))
1002                 (define-source-transform (setf ,reffer) (value a &rest i)
1003                   `(setf (aref (the (,',(if simplep 'simple-array 'array)
1004                                      bit
1005                                      ,(mapcar (constantly '*) i))
1006                                     ,a) ,@i)
1007                          ,value)))))
1008   (define-bit-frob sbit t)
1009   (define-bit-frob bit nil))
1010
1011 (macrolet ((define-frob (reffer setter type)
1012              `(progn
1013                 (define-source-transform ,reffer (a i)
1014                   `(aref (the ,',type ,a) ,i))
1015                 (define-source-transform ,setter (a i v)
1016                   `(setf (aref (the ,',type ,a) ,i) ,v)))))
1017   (define-frob schar %scharset simple-string)
1018   (define-frob char %charset string))
1019
1020 ;;; We transform SVREF and %SVSET directly into DATA-VECTOR-REF/SET: this is
1021 ;;; around 100 times faster than going through the general-purpose AREF
1022 ;;; transform which ends up doing a lot of work -- and introducing many
1023 ;;; intermediate lambdas, each meaning a new trip through the compiler -- to
1024 ;;; get the same result.
1025 ;;;
1026 ;;; FIXME: [S]CHAR, and [S]BIT above would almost certainly benefit from a similar
1027 ;;; treatment.
1028 (define-source-transform svref (vector index)
1029   (let ((elt-type (or (when (symbolp vector)
1030                         (let ((var (lexenv-find vector vars)))
1031                           (when (lambda-var-p var)
1032                             (type-specifier
1033                              (array-type-declared-element-type (lambda-var-type var))))))
1034                       t)))
1035     (with-unique-names (n-vector)
1036       `(let ((,n-vector ,vector))
1037          (the ,elt-type (data-vector-ref
1038                          (the simple-vector ,n-vector)
1039                          (%check-bound ,n-vector (length ,n-vector) ,index)))))))
1040
1041 (define-source-transform %svset (vector index value)
1042   (let ((elt-type (or (when (symbolp vector)
1043                         (let ((var (lexenv-find vector vars)))
1044                           (when (lambda-var-p var)
1045                             (type-specifier
1046                              (array-type-declared-element-type (lambda-var-type var))))))
1047                       t)))
1048     (with-unique-names (n-vector)
1049       `(let ((,n-vector ,vector))
1050          (truly-the ,elt-type (data-vector-set
1051                                (the simple-vector ,n-vector)
1052                                (%check-bound ,n-vector (length ,n-vector) ,index)
1053                                (the ,elt-type ,value)))))))
1054
1055 (macrolet (;; This is a handy macro for computing the row-major index
1056            ;; given a set of indices. We wrap each index with a call
1057            ;; to %CHECK-BOUND to ensure that everything works out
1058            ;; correctly. We can wrap all the interior arithmetic with
1059            ;; TRULY-THE INDEX because we know the resultant
1060            ;; row-major index must be an index.
1061            (with-row-major-index ((array indices index &optional new-value)
1062                                   &rest body)
1063              `(let (n-indices dims)
1064                 (dotimes (i (length ,indices))
1065                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
1066                   (push (make-symbol (format nil "DIM-~D" i)) dims))
1067                 (setf n-indices (nreverse n-indices))
1068                 (setf dims (nreverse dims))
1069                 `(lambda (,@',(when new-value (list new-value))
1070                           ,',array ,@n-indices)
1071                    (declare (ignorable ,',array))
1072                    (let* (,@(let ((,index -1))
1073                               (mapcar (lambda (name)
1074                                         `(,name (array-dimension
1075                                                  ,',array
1076                                                  ,(incf ,index))))
1077                                       dims))
1078                             (,',index
1079                              ,(if (null dims)
1080                                   0
1081                                 (do* ((dims dims (cdr dims))
1082                                       (indices n-indices (cdr indices))
1083                                       (last-dim nil (car dims))
1084                                       (form `(%check-bound ,',array
1085                                                            ,(car dims)
1086                                                            ,(car indices))
1087                                             `(truly-the
1088                                               index
1089                                               (+ (truly-the index
1090                                                             (* ,form
1091                                                                ,last-dim))
1092                                                  (%check-bound
1093                                                   ,',array
1094                                                   ,(car dims)
1095                                                   ,(car indices))))))
1096                                     ((null (cdr dims)) form)))))
1097                      ,',@body)))))
1098
1099   ;; Just return the index after computing it.
1100   (deftransform array-row-major-index ((array &rest indices))
1101     (with-row-major-index (array indices index)
1102       index))
1103
1104   ;; Convert AREF and (SETF AREF) into a HAIRY-DATA-VECTOR-REF (or
1105   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
1106   ;; expression for the row major index.
1107   (deftransform aref ((array &rest indices))
1108     (with-row-major-index (array indices index)
1109       (hairy-data-vector-ref array index)))
1110
1111   (deftransform (setf aref) ((new-value array &rest subscripts))
1112     (with-row-major-index (array subscripts index new-value)
1113                           (hairy-data-vector-set array index new-value))))
1114
1115 ;; For AREF of vectors we do the bounds checking in the callee. This
1116 ;; lets us do a significantly more efficient check for simple-arrays
1117 ;; without bloating the code. If we already know the type of the array
1118 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
1119 (deftransform aref ((array index) (t t) * :node node)
1120   (let* ((type (lvar-type array))
1121          (element-ctype (array-type-upgraded-element-type type)))
1122     (cond
1123       ((and (array-type-p type)
1124             (null (array-type-complexp type))
1125             (not (eql element-ctype *wild-type*))
1126             (eql (length (array-type-dimensions type)) 1))
1127        (let* ((declared-element-ctype (array-type-declared-element-type type))
1128               (bare-form
1129                `(data-vector-ref array
1130                  (%check-bound array (array-dimension array 0) index))))
1131          (if (type= declared-element-ctype element-ctype)
1132              bare-form
1133              `(the ,(type-specifier declared-element-ctype) ,bare-form))))
1134       ((policy node (zerop insert-array-bounds-checks))
1135        `(hairy-data-vector-ref array index))
1136       (t `(hairy-data-vector-ref/check-bounds array index)))))
1137
1138 (deftransform (setf aref) ((new-value array index) (t t t) * :node node)
1139   (if (policy node (zerop insert-array-bounds-checks))
1140       `(hairy-data-vector-set array index new-value)
1141       `(hairy-data-vector-set/check-bounds array index new-value)))
1142
1143 ;;; But if we find out later that there's some useful type information
1144 ;;; available, switch back to the normal one to give other transforms
1145 ;;; a stab at it.
1146 (macrolet ((define (name transform-to extra extra-type)
1147              (declare (ignore extra-type))
1148              `(deftransform ,name ((array index ,@extra))
1149                 (let* ((type (lvar-type array))
1150                        (element-type (array-type-upgraded-element-type type))
1151                        (declared-type (type-specifier
1152                                        (array-type-declared-element-type type))))
1153                   ;; If an element type has been declared, we want to
1154                   ;; use that information it for type checking (even
1155                   ;; if the access can't be optimized due to the array
1156                   ;; not being simple).
1157                   (when (and (eql element-type *wild-type*)
1158                              ;; This type logic corresponds to the special
1159                              ;; case for strings in HAIRY-DATA-VECTOR-REF
1160                              ;; (generic/vm-tran.lisp)
1161                              (not (csubtypep type (specifier-type 'simple-string))))
1162                     (when (or (not (array-type-p type))
1163                               ;; If it's a simple array, we might be able
1164                               ;; to inline the access completely.
1165                               (not (null (array-type-complexp type))))
1166                       (give-up-ir1-transform
1167                        "Upgraded element type of array is not known at compile time.")))
1168                   ,(if extra
1169                        ``(truly-the ,declared-type
1170                                     (,',transform-to array
1171                                                      (%check-bound array
1172                                                                    (array-dimension array 0)
1173                                                                    index)
1174                                                      (the ,declared-type ,@',extra)))
1175                        ``(the ,declared-type
1176                            (,',transform-to array
1177                                             (%check-bound array
1178                                                           (array-dimension array 0)
1179                                                           index))))))))
1180   (define hairy-data-vector-ref/check-bounds
1181       hairy-data-vector-ref nil nil)
1182   (define hairy-data-vector-set/check-bounds
1183       hairy-data-vector-set (new-value) (*)))
1184
1185 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
1186 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
1187 ;;; array total size.
1188 (deftransform row-major-aref ((array index))
1189   `(hairy-data-vector-ref array
1190                           (%check-bound array (array-total-size array) index)))
1191 (deftransform %set-row-major-aref ((array index new-value))
1192   `(hairy-data-vector-set array
1193                           (%check-bound array (array-total-size array) index)
1194                           new-value))
1195 \f
1196 ;;;; bit-vector array operation canonicalization
1197 ;;;;
1198 ;;;; We convert all bit-vector operations to have the result array
1199 ;;;; specified. This allows any result allocation to be open-coded,
1200 ;;;; and eliminates the need for any VM-dependent transforms to handle
1201 ;;;; these cases.
1202
1203 (macrolet ((def (fun)
1204              `(progn
1205                (deftransform ,fun ((bit-array-1 bit-array-2
1206                                                 &optional result-bit-array)
1207                                    (bit-vector bit-vector &optional null) *
1208                                    :policy (>= speed space))
1209                  `(,',fun bit-array-1 bit-array-2
1210                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1211                ;; If result is T, make it the first arg.
1212                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1213                                    (bit-vector bit-vector (eql t)) *)
1214                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1215   (def bit-and)
1216   (def bit-ior)
1217   (def bit-xor)
1218   (def bit-eqv)
1219   (def bit-nand)
1220   (def bit-nor)
1221   (def bit-andc1)
1222   (def bit-andc2)
1223   (def bit-orc1)
1224   (def bit-orc2))
1225
1226 ;;; Similar for BIT-NOT, but there is only one arg...
1227 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1228                        (bit-vector &optional null) *
1229                        :policy (>= speed space))
1230   '(bit-not bit-array-1
1231             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1232 (deftransform bit-not ((bit-array-1 result-bit-array)
1233                        (bit-vector (eql t)))
1234   '(bit-not bit-array-1 bit-array-1))
1235 \f
1236 ;;; Pick off some constant cases.
1237 (defoptimizer (array-header-p derive-type) ((array))
1238   (let ((type (lvar-type array)))
1239     (cond ((not (array-type-p type))
1240            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1241            nil)
1242           (t
1243            (let ((dims (array-type-dimensions type)))
1244              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1245                     ;; no array header
1246                     (specifier-type 'null))
1247                    ((and (listp dims) (/= (length dims) 1))
1248                     ;; multi-dimensional array, will have a header
1249                     (specifier-type '(eql t)))
1250                    ((eql (array-type-complexp type) t)
1251                     (specifier-type '(eql t)))
1252                    (t
1253                     nil)))))))