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