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