1.0.28.48: fix regressions from 1.0.28.47
[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 (defoptimizer (aref derive-type) ((array &rest indices) node)
116   (assert-array-rank array (length indices))
117   (derive-aref-type array))
118
119 (defoptimizer (%aset derive-type) ((array &rest stuff))
120   (assert-array-rank array (1- (length stuff)))
121   (assert-new-value-type (car (last stuff)) array))
122
123 (macrolet ((define (name)
124              `(defoptimizer (,name derive-type) ((array index))
125                 (derive-aref-type array))))
126   (define hairy-data-vector-ref)
127   (define hairy-data-vector-ref/check-bounds)
128   (define data-vector-ref))
129
130 #!+(or x86 x86-64)
131 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
132   (derive-aref-type array))
133
134 (macrolet ((define (name)
135              `(defoptimizer (,name derive-type) ((array index new-value))
136                 (assert-new-value-type new-value array))))
137   (define hairy-data-vector-set)
138   (define hairy-data-vector-set/check-bounds)
139   (define data-vector-set))
140
141 #!+(or x86 x86-64)
142 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
143   (assert-new-value-type new-value array))
144
145 ;;; Figure out the type of the data vector if we know the argument
146 ;;; element type.
147 (defun derive-%with-array-data/mumble-type (array)
148   (let ((atype (lvar-type array)))
149     (when (array-type-p atype)
150       (specifier-type
151        `(simple-array ,(type-specifier
152                         (array-type-specialized-element-type atype))
153                       (*))))))
154 (defoptimizer (%with-array-data derive-type) ((array start end))
155   (derive-%with-array-data/mumble-type array))
156 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
157   (derive-%with-array-data/mumble-type array))
158
159 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
160   (assert-array-rank array (length indices))
161   *universal-type*)
162
163 (defoptimizer (row-major-aref derive-type) ((array index))
164   (derive-aref-type array))
165
166 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
167   (assert-new-value-type new-value array))
168
169 (defoptimizer (make-array derive-type)
170               ((dims &key initial-element element-type initial-contents
171                 adjustable fill-pointer displaced-index-offset displaced-to))
172   (let ((simple (and (unsupplied-or-nil adjustable)
173                      (unsupplied-or-nil displaced-to)
174                      (unsupplied-or-nil fill-pointer))))
175     (or (careful-specifier-type
176          `(,(if simple 'simple-array 'array)
177             ,(cond ((not element-type) t)
178                    ((constant-lvar-p element-type)
179                     (let ((ctype (careful-specifier-type
180                                   (lvar-value element-type))))
181                       (cond
182                         ((or (null ctype) (unknown-type-p ctype)) '*)
183                         (t (sb!xc:upgraded-array-element-type
184                             (lvar-value element-type))))))
185                    (t
186                     '*))
187             ,(cond ((constant-lvar-p dims)
188                     (let* ((val (lvar-value dims))
189                            (cdims (if (listp val) val (list val))))
190                       (if simple
191                           cdims
192                           (length cdims))))
193                    ((csubtypep (lvar-type dims)
194                                (specifier-type 'integer))
195                     '(*))
196                    (t
197                     '*))))
198         (specifier-type 'array))))
199
200 ;;; Complex array operations should assert that their array argument
201 ;;; is complex.  In SBCL, vectors with fill-pointers are complex.
202 (defoptimizer (fill-pointer derive-type) ((vector))
203   (assert-array-complex vector))
204 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
205   (declare (ignorable index))
206   (assert-array-complex vector))
207
208 (defoptimizer (vector-push derive-type) ((object vector))
209   (declare (ignorable object))
210   (assert-array-complex vector))
211 (defoptimizer (vector-push-extend derive-type)
212     ((object vector &optional index))
213   (declare (ignorable object index))
214   (assert-array-complex vector))
215 (defoptimizer (vector-pop derive-type) ((vector))
216   (assert-array-complex vector))
217 \f
218 ;;;; constructors
219
220 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
221 ;;; elements.
222 (define-source-transform vector (&rest elements)
223   (let ((len (length elements))
224         (n -1))
225     (once-only ((n-vec `(make-array ,len)))
226       `(progn
227          ,@(mapcar (lambda (el)
228                      (once-only ((n-val el))
229                        `(locally (declare (optimize (safety 0)))
230                           (setf (svref ,n-vec ,(incf n)) ,n-val))))
231                    elements)
232          ,n-vec))))
233
234 ;;; Just convert it into a MAKE-ARRAY.
235 (deftransform make-string ((length &key
236                                    (element-type 'character)
237                                    (initial-element
238                                     #.*default-init-char-form*)))
239   `(the simple-string (make-array (the index length)
240                        :element-type element-type
241                        ,@(when initial-element
242                            '(:initial-element initial-element)))))
243
244 (deftransform make-array ((dims &key initial-element element-type
245                                      adjustable fill-pointer)
246                           (t &rest *))
247   (when (null initial-element)
248     (give-up-ir1-transform))
249   (let* ((eltype (cond ((not element-type) t)
250                        ((not (constant-lvar-p element-type))
251                         (give-up-ir1-transform
252                          "ELEMENT-TYPE is not constant."))
253                        (t
254                         (lvar-value element-type))))
255          (eltype-type (ir1-transform-specifier-type eltype))
256          (saetp (find-if (lambda (saetp)
257                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
258                          sb!vm:*specialized-array-element-type-properties*))
259          (creation-form `(make-array dims
260                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
261                           ,@(when fill-pointer
262                                   '(:fill-pointer fill-pointer))
263                           ,@(when adjustable
264                                   '(:adjustable adjustable)))))
265
266     (unless saetp
267       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
268
269     (cond ((and (constant-lvar-p initial-element)
270                 (eql (lvar-value initial-element)
271                      (sb!vm:saetp-initial-element-default saetp)))
272            creation-form)
273           (t
274            ;; error checking for target, disabled on the host because
275            ;; (CTYPE-OF #\Null) is not possible.
276            #-sb-xc-host
277            (when (constant-lvar-p initial-element)
278              (let ((value (lvar-value initial-element)))
279                (cond
280                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
281                   ;; this case will cause an error at runtime, so we'd
282                   ;; better WARN about it now.
283                   (warn 'array-initial-element-mismatch
284                         :format-control "~@<~S is not a ~S (which is the ~
285                                          ~S of ~S).~@:>"
286                         :format-arguments
287                         (list
288                          value
289                          (type-specifier (sb!vm:saetp-ctype saetp))
290                          'upgraded-array-element-type
291                          eltype)))
292                  ((not (ctypep value eltype-type))
293                   ;; this case will not cause an error at runtime, but
294                   ;; it's still worth STYLE-WARNing about.
295                   (compiler-style-warn "~S is not a ~S."
296                                        value eltype)))))
297            `(let ((array ,creation-form))
298              (multiple-value-bind (vector)
299                  (%data-vector-and-index array 0)
300                (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
301              array)))))
302
303 ;;; The integer type restriction on the length ensures that it will be
304 ;;; a vector. The lack of :ADJUSTABLE, :FILL-POINTER, and
305 ;;; :DISPLACED-TO keywords ensures that it will be simple; the lack of
306 ;;; :INITIAL-ELEMENT relies on another transform to deal with that
307 ;;; kind of initialization efficiently.
308 (deftransform make-array ((length &key element-type)
309                           (integer &rest *))
310   (let* ((eltype (cond ((not element-type) t)
311                        ((not (constant-lvar-p element-type))
312                         (give-up-ir1-transform
313                          "ELEMENT-TYPE is not constant."))
314                        (t
315                         (lvar-value element-type))))
316          (len (if (constant-lvar-p length)
317                   (lvar-value length)
318                   '*))
319          (eltype-type (ir1-transform-specifier-type eltype))
320          (result-type-spec
321           `(simple-array
322             ,(if (unknown-type-p eltype-type)
323                  (give-up-ir1-transform
324                   "ELEMENT-TYPE is an unknown type: ~S" eltype)
325                  (sb!xc:upgraded-array-element-type eltype))
326             (,len)))
327          (saetp (find-if (lambda (saetp)
328                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
329                          sb!vm:*specialized-array-element-type-properties*)))
330     (unless saetp
331       (give-up-ir1-transform
332        "cannot open-code creation of ~S" result-type-spec))
333     #-sb-xc-host
334     (unless (ctypep (sb!vm:saetp-initial-element-default saetp) eltype-type)
335       ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
336       ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
337       ;; INITIAL-ELEMENT is not supplied, the consequences of later
338       ;; reading an uninitialized element of new-array are undefined,"
339       ;; so this could be legal code as long as the user plans to
340       ;; write before he reads, and if he doesn't we're free to do
341       ;; anything we like. But in case the user doesn't know to write
342       ;; elements before he reads elements (or to read manuals before
343       ;; he writes code:-), we'll signal a STYLE-WARNING in case he
344       ;; didn't realize this.
345       (compiler-style-warn "The default initial element ~S is not a ~S."
346                            (sb!vm:saetp-initial-element-default saetp)
347                            eltype))
348     (let* ((n-bits-per-element (sb!vm:saetp-n-bits saetp))
349            (typecode (sb!vm:saetp-typecode saetp))
350            (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
351            (padded-length-form (if (zerop n-pad-elements)
352                                    'length
353                                    `(+ length ,n-pad-elements)))
354            (n-words-form
355             (cond
356               ((= n-bits-per-element 0) 0)
357               ((>= n-bits-per-element sb!vm:n-word-bits)
358                `(* ,padded-length-form
359                  (the fixnum ; i.e., not RATIO
360                    ,(/ n-bits-per-element sb!vm:n-word-bits))))
361               (t
362                (let ((n-elements-per-word (/ sb!vm:n-word-bits
363                                              n-bits-per-element)))
364                  (declare (type index n-elements-per-word)) ; i.e., not RATIO
365                  `(ceiling ,padded-length-form ,n-elements-per-word))))))
366       (values
367        `(truly-the ,result-type-spec
368          (allocate-vector ,typecode length ,n-words-form))
369        '((declare (type index length)))))))
370
371 ;;; The list type restriction does not ensure that the result will be a
372 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
373 ;;; and displaced-to keywords ensures that it will be simple.
374 ;;;
375 ;;; FIXME: should we generalize this transform to non-simple (though
376 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
377 ;;; deal with those? Maybe when the DEFTRANSFORM
378 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
379 ;;; CSR, 2002-07-01
380 (deftransform make-array ((dims &key element-type)
381                           (list &rest *))
382   (unless (or (null element-type) (constant-lvar-p element-type))
383     (give-up-ir1-transform
384      "The element-type is not constant; cannot open code array creation."))
385   (unless (constant-lvar-p dims)
386     (give-up-ir1-transform
387      "The dimension list is not constant; cannot open code array creation."))
388   (let ((dims (lvar-value dims)))
389     (unless (every #'integerp dims)
390       (give-up-ir1-transform
391        "The dimension list contains something other than an integer: ~S"
392        dims))
393     (if (= (length dims) 1)
394         `(make-array ',(car dims)
395                      ,@(when element-type
396                          '(:element-type element-type)))
397         (let* ((total-size (reduce #'* dims))
398                (rank (length dims))
399                (spec `(simple-array
400                        ,(cond ((null element-type) t)
401                               ((and (constant-lvar-p element-type)
402                                     (ir1-transform-specifier-type
403                                      (lvar-value element-type)))
404                                (sb!xc:upgraded-array-element-type
405                                 (lvar-value element-type)))
406                               (t '*))
407                            ,(make-list rank :initial-element '*))))
408           `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank)))
409              (setf (%array-fill-pointer header) ,total-size)
410              (setf (%array-fill-pointer-p header) nil)
411              (setf (%array-available-elements header) ,total-size)
412              (setf (%array-data-vector header)
413                    (make-array ,total-size
414                                ,@(when element-type
415                                    '(:element-type element-type))))
416              (setf (%array-displaced-p header) nil)
417              (setf (%array-displaced-from header) nil)
418              ,@(let ((axis -1))
419                  (mapcar (lambda (dim)
420                            `(setf (%array-dimension header ,(incf axis))
421                                   ,dim))
422                          dims))
423              (truly-the ,spec header))))))
424 \f
425 ;;;; miscellaneous properties of arrays
426
427 ;;; Transforms for various array properties. If the property is know
428 ;;; at compile time because of a type spec, use that constant value.
429
430 ;;; Most of this logic may end up belonging in code/late-type.lisp;
431 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
432 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
433 ;;; 2004-02-18
434 (defun array-type-dimensions-or-give-up (type)
435   (typecase type
436     (array-type (array-type-dimensions type))
437     (union-type
438      (let ((types (union-type-types type)))
439        ;; there are at least two types, right?
440        (aver (> (length types) 1))
441        (let ((result (array-type-dimensions-or-give-up (car types))))
442          (dolist (type (cdr types) result)
443            (unless (equal (array-type-dimensions-or-give-up type) result)
444              (give-up-ir1-transform))))))
445     ;; FIXME: intersection type [e.g. (and (array * (*)) (satisfies foo)) ]
446     (t (give-up-ir1-transform))))
447
448 (defun conservative-array-type-complexp (type)
449   (typecase type
450     (array-type (array-type-complexp type))
451     (union-type
452      (let ((types (union-type-types type)))
453        (aver (> (length types) 1))
454        (let ((result (conservative-array-type-complexp (car types))))
455          (dolist (type (cdr types) result)
456            (unless (eq (conservative-array-type-complexp type) result)
457              (return-from conservative-array-type-complexp :maybe))))))
458     ;; FIXME: intersection type
459     (t :maybe)))
460
461 ;;; If we can tell the rank from the type info, use it instead.
462 (deftransform array-rank ((array))
463   (let ((array-type (lvar-type array)))
464     (let ((dims (array-type-dimensions-or-give-up array-type)))
465       (cond ((listp dims)
466              (length dims))
467             ((eq t (array-type-complexp array-type))
468              '(%array-rank array))
469             (t
470              `(if (array-header-p array)
471                   (%array-rank array)
472                   1))))))
473
474 ;;; If we know the dimensions at compile time, just use it. Otherwise,
475 ;;; if we can tell that the axis is in bounds, convert to
476 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
477 ;;; (if it's simple and a vector).
478 (deftransform array-dimension ((array axis)
479                                (array index))
480   (unless (constant-lvar-p axis)
481     (give-up-ir1-transform "The axis is not constant."))
482   ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
483   ;; conservative type.
484   (let ((array-type (lvar-conservative-type array))
485         (axis (lvar-value axis)))
486     (let ((dims (array-type-dimensions-or-give-up array-type)))
487       (unless (listp dims)
488         (give-up-ir1-transform
489          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
490       (unless (> (length dims) axis)
491         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
492                              dims
493                              axis))
494       (let ((dim (nth axis dims)))
495         (cond ((integerp dim)
496                dim)
497               ((= (length dims) 1)
498                (ecase (conservative-array-type-complexp array-type)
499                  ((t)
500                   '(%array-dimension array 0))
501                  ((nil)
502                   '(vector-length array))
503                  ((:maybe)
504                   `(if (array-header-p array)
505                        (%array-dimension array axis)
506                        (vector-length array)))))
507               (t
508                '(%array-dimension array axis)))))))
509
510 ;;; If the length has been declared and it's simple, just return it.
511 (deftransform length ((vector)
512                       ((simple-array * (*))))
513   (let ((type (lvar-type vector)))
514     (let ((dims (array-type-dimensions-or-give-up type)))
515       (unless (and (listp dims) (integerp (car dims)))
516         (give-up-ir1-transform
517          "Vector length is unknown, must call LENGTH at runtime."))
518       (car dims))))
519
520 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
521 ;;; simple, it will extract the length slot from the vector. It it's
522 ;;; complex, it will extract the fill pointer slot from the array
523 ;;; header.
524 (deftransform length ((vector) (vector))
525   '(vector-length vector))
526
527 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
528 ;;; compile-time constant.
529 (deftransform vector-length ((vector))
530   (let ((vtype (lvar-type vector)))
531     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
532       (when (eq dim '*)
533         (give-up-ir1-transform))
534       (when (conservative-array-type-complexp vtype)
535         (give-up-ir1-transform))
536       dim)))
537
538 ;;; Again, if we can tell the results from the type, just use it.
539 ;;; Otherwise, if we know the rank, convert into a computation based
540 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
541 ;;; multiplications because we know that the total size must be an
542 ;;; INDEX.
543 (deftransform array-total-size ((array)
544                                 (array))
545   (let ((array-type (lvar-type array)))
546     (let ((dims (array-type-dimensions-or-give-up array-type)))
547       (unless (listp dims)
548         (give-up-ir1-transform "can't tell the rank at compile time"))
549       (if (member '* dims)
550           (do ((form 1 `(truly-the index
551                                    (* (array-dimension array ,i) ,form)))
552                (i 0 (1+ i)))
553               ((= i (length dims)) form))
554           (reduce #'* dims)))))
555
556 ;;; Only complex vectors have fill pointers.
557 (deftransform array-has-fill-pointer-p ((array))
558   (let ((array-type (lvar-type array)))
559     (let ((dims (array-type-dimensions-or-give-up array-type)))
560       (if (and (listp dims) (not (= (length dims) 1)))
561           nil
562           (ecase (conservative-array-type-complexp array-type)
563             ((t)
564              t)
565             ((nil)
566              nil)
567             ((:maybe)
568              (give-up-ir1-transform
569               "The array type is ambiguous; must call ~
570                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
571
572 ;;; Primitive used to verify indices into arrays. If we can tell at
573 ;;; compile-time or we are generating unsafe code, don't bother with
574 ;;; the VOP.
575 (deftransform %check-bound ((array dimension index) * * :node node)
576   (cond ((policy node (= insert-array-bounds-checks 0))
577          'index)
578         ((not (constant-lvar-p dimension))
579          (give-up-ir1-transform))
580         (t
581          (let ((dim (lvar-value dimension)))
582            ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
583            `(the (integer 0 (,dim)) index)))))
584 \f
585 ;;;; WITH-ARRAY-DATA
586
587 ;;; This checks to see whether the array is simple and the start and
588 ;;; end are in bounds. If so, it proceeds with those values.
589 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
590 ;;; may be further optimized.
591 ;;;
592 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
593 ;;; START-VAR and END-VAR to the start and end of the designated
594 ;;; portion of the data vector. SVALUE and EVALUE are any start and
595 ;;; end specified to the original operation, and are factored into the
596 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
597 ;;; offset of all displacements encountered, and does not include
598 ;;; SVALUE.
599 ;;;
600 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
601 ;;; forced to be inline, overriding the ordinary judgment of the
602 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
603 ;;; fairly picky about their arguments, figuring that if you haven't
604 ;;; bothered to get all your ducks in a row, you probably don't care
605 ;;; that much about speed anyway! But in some cases it makes sense to
606 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
607 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
608 ;;; sense to use FORCE-INLINE option in that case.
609 (def!macro with-array-data (((data-var array &key offset-var)
610                              (start-var &optional (svalue 0))
611                              (end-var &optional (evalue nil))
612                              &key force-inline check-fill-pointer)
613                             &body forms
614                             &environment env)
615   (once-only ((n-array array)
616               (n-svalue `(the index ,svalue))
617               (n-evalue `(the (or index null) ,evalue)))
618     (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
619       `(multiple-value-bind (,data-var
620                              ,start-var
621                              ,end-var
622                              ,@(when offset-var `(,offset-var)))
623            (if (not (array-header-p ,n-array))
624                (let ((,n-array ,n-array))
625                  (declare (type (simple-array * (*)) ,n-array))
626                  ,(once-only ((n-len (if check-fill-pointer
627                                          `(length ,n-array)
628                                          `(array-total-size ,n-array)))
629                               (n-end `(or ,n-evalue ,n-len)))
630                              (if check-bounds
631                                  `(if (<= 0 ,n-svalue ,n-end ,n-len)
632                                       (values ,n-array ,n-svalue ,n-end 0)
633                                       ,(if check-fill-pointer
634                                            `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
635                                            `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
636                                  `(values ,n-array ,n-svalue ,n-end 0))))
637                ,(if force-inline
638                     `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
639                                              :check-bounds ,check-bounds
640                                              :check-fill-pointer ,check-fill-pointer)
641                     (if check-fill-pointer
642                         `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
643                         `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
644          ,@forms))))
645
646 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
647 ;;; DEFTRANSFORMs and DEFUNs.
648 (def!macro %with-array-data-macro (array
649                                    start
650                                    end
651                                    &key
652                                    (element-type '*)
653                                    check-bounds
654                                    check-fill-pointer)
655   (with-unique-names (size defaulted-end data cumulative-offset)
656     `(let* ((,size ,(if check-fill-pointer
657                         `(length ,array)
658                         `(array-total-size ,array)))
659             (,defaulted-end (or ,end ,size)))
660        ,@(when check-bounds
661                `((unless (<= ,start ,defaulted-end ,size)
662                    ,(if check-fill-pointer
663                         `(sequence-bounding-indices-bad-error ,array ,start ,end)
664                         `(array-bounding-indices-bad-error ,array ,start ,end)))))
665        (do ((,data ,array (%array-data-vector ,data))
666             (,cumulative-offset 0
667                                 (+ ,cumulative-offset
668                                    (%array-displacement ,data))))
669            ((not (array-header-p ,data))
670             (values (the (simple-array ,element-type 1) ,data)
671                     (the index (+ ,cumulative-offset ,start))
672                     (the index (+ ,cumulative-offset ,defaulted-end))
673                     (the index ,cumulative-offset)))
674          (declare (type index ,cumulative-offset))))))
675
676 (defun transform-%with-array-data/muble (array node check-fill-pointer)
677   (let ((element-type (upgraded-element-type-specifier-or-give-up array))
678         (type (lvar-type array))
679         (check-bounds (policy node (plusp insert-array-bounds-checks))))
680     (if (and (array-type-p type)
681              (not (array-type-complexp type))
682              (listp (array-type-dimensions type))
683              (not (null (cdr (array-type-dimensions type)))))
684         ;; If it's a simple multidimensional array, then just return
685         ;; its data vector directly rather than going through
686         ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
687         ;; code that would use this currently, but we have encouraged
688         ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
689         ;; some point in the future for optimized libraries or
690         ;; similar.
691         (if check-bounds
692             `(let* ((data (truly-the (simple-array ,element-type (*))
693                                      (%array-data-vector array)))
694                     (len (length data))
695                     (real-end (or end len)))
696                (unless (<= 0 start data-end lend)
697                  (sequence-bounding-indices-bad-error array start end))
698                (values data 0 real-end 0))
699             `(let ((data (truly-the (simple-array ,element-type (*))
700                                     (%array-data-vector array))))
701                (values data 0 (or end (length data)) 0)))
702         `(%with-array-data-macro array start end
703                                  :check-fill-pointer ,check-fill-pointer
704                                  :check-bounds ,check-bounds
705                                  :element-type ,element-type))))
706
707 ;; It might very well be reasonable to allow general ARRAY here, I
708 ;; just haven't tried to understand the performance issues involved.
709 ;; -- WHN, and also CSR 2002-05-26
710 (deftransform %with-array-data ((array start end)
711                                 ((or vector simple-array) index (or index null) t)
712                                 *
713                                 :node node
714                                 :policy (> speed space))
715   "inline non-SIMPLE-vector-handling logic"
716   (transform-%with-array-data/muble array node nil))
717 (deftransform %with-array-data/fp ((array start end)
718                                 ((or vector simple-array) index (or index null) t)
719                                 *
720                                 :node node
721                                 :policy (> speed space))
722   "inline non-SIMPLE-vector-handling logic"
723   (transform-%with-array-data/muble array node t))
724 \f
725 ;;;; array accessors
726
727 ;;; We convert all typed array accessors into AREF and %ASET with type
728 ;;; assertions on the array.
729 (macrolet ((define-bit-frob (reffer setter simplep)
730              `(progn
731                 (define-source-transform ,reffer (a &rest i)
732                   `(aref (the (,',(if simplep 'simple-array 'array)
733                                   bit
734                                   ,(mapcar (constantly '*) i))
735                            ,a) ,@i))
736                 (define-source-transform ,setter (a &rest i)
737                   `(%aset (the (,',(if simplep 'simple-array 'array)
738                                    bit
739                                    ,(cdr (mapcar (constantly '*) i)))
740                             ,a) ,@i)))))
741   (define-bit-frob sbit %sbitset t)
742   (define-bit-frob bit %bitset nil))
743 (macrolet ((define-frob (reffer setter type)
744              `(progn
745                 (define-source-transform ,reffer (a i)
746                   `(aref (the ,',type ,a) ,i))
747                 (define-source-transform ,setter (a i v)
748                   `(%aset (the ,',type ,a) ,i ,v)))))
749   (define-frob svref %svset simple-vector)
750   (define-frob schar %scharset simple-string)
751   (define-frob char %charset string))
752
753 (macrolet (;; This is a handy macro for computing the row-major index
754            ;; given a set of indices. We wrap each index with a call
755            ;; to %CHECK-BOUND to ensure that everything works out
756            ;; correctly. We can wrap all the interior arithmetic with
757            ;; TRULY-THE INDEX because we know the resultant
758            ;; row-major index must be an index.
759            (with-row-major-index ((array indices index &optional new-value)
760                                   &rest body)
761              `(let (n-indices dims)
762                 (dotimes (i (length ,indices))
763                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
764                   (push (make-symbol (format nil "DIM-~D" i)) dims))
765                 (setf n-indices (nreverse n-indices))
766                 (setf dims (nreverse dims))
767                 `(lambda (,',array ,@n-indices
768                                    ,@',(when new-value (list new-value)))
769                    (let* (,@(let ((,index -1))
770                               (mapcar (lambda (name)
771                                         `(,name (array-dimension
772                                                  ,',array
773                                                  ,(incf ,index))))
774                                       dims))
775                             (,',index
776                              ,(if (null dims)
777                                   0
778                                 (do* ((dims dims (cdr dims))
779                                       (indices n-indices (cdr indices))
780                                       (last-dim nil (car dims))
781                                       (form `(%check-bound ,',array
782                                                            ,(car dims)
783                                                            ,(car indices))
784                                             `(truly-the
785                                               index
786                                               (+ (truly-the index
787                                                             (* ,form
788                                                                ,last-dim))
789                                                  (%check-bound
790                                                   ,',array
791                                                   ,(car dims)
792                                                   ,(car indices))))))
793                                     ((null (cdr dims)) form)))))
794                      ,',@body)))))
795
796   ;; Just return the index after computing it.
797   (deftransform array-row-major-index ((array &rest indices))
798     (with-row-major-index (array indices index)
799       index))
800
801   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
802   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
803   ;; expression for the row major index.
804   (deftransform aref ((array &rest indices))
805     (with-row-major-index (array indices index)
806       (hairy-data-vector-ref array index)))
807
808   (deftransform %aset ((array &rest stuff))
809     (let ((indices (butlast stuff)))
810       (with-row-major-index (array indices index new-value)
811         (hairy-data-vector-set array index new-value)))))
812
813 ;; For AREF of vectors we do the bounds checking in the callee. This
814 ;; lets us do a significantly more efficient check for simple-arrays
815 ;; without bloating the code. If we already know the type of the array
816 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
817 (deftransform aref ((array index) (t t) * :node node)
818   (let* ((type (lvar-type array))
819          (element-ctype (extract-upgraded-element-type array)))
820     (cond
821       ((and (array-type-p type)
822             (null (array-type-complexp type))
823             (not (eql element-ctype *wild-type*))
824             (eql (length (array-type-dimensions type)) 1))
825        (let* ((declared-element-ctype (extract-declared-element-type array))
826               (bare-form
827                `(data-vector-ref array
828                  (%check-bound array (array-dimension array 0) index))))
829          (if (type= declared-element-ctype element-ctype)
830              bare-form
831              `(the ,(type-specifier declared-element-ctype) ,bare-form))))
832       ((policy node (zerop insert-array-bounds-checks))
833        `(hairy-data-vector-ref array index))
834       (t `(hairy-data-vector-ref/check-bounds array index)))))
835
836 (deftransform %aset ((array index new-value) (t t t) * :node node)
837   (if (policy node (zerop insert-array-bounds-checks))
838       `(hairy-data-vector-set array index new-value)
839       `(hairy-data-vector-set/check-bounds array index new-value)))
840
841 ;;; But if we find out later that there's some useful type information
842 ;;; available, switch back to the normal one to give other transforms
843 ;;; a stab at it.
844 (macrolet ((define (name transform-to extra extra-type)
845              (declare (ignore extra-type))
846              `(deftransform ,name ((array index ,@extra))
847                 (let ((type (lvar-type array))
848                       (element-type (extract-upgraded-element-type array))
849                       (declared-type (extract-declared-element-type array)))
850                   ;; If an element type has been declared, we want to
851                   ;; use that information it for type checking (even
852                   ;; if the access can't be optimized due to the array
853                   ;; not being simple).
854                   (when (and (eql element-type *wild-type*)
855                              ;; This type logic corresponds to the special
856                              ;; case for strings in HAIRY-DATA-VECTOR-REF
857                              ;; (generic/vm-tran.lisp)
858                              (not (csubtypep type (specifier-type 'simple-string))))
859                     (when (or (not (array-type-p type))
860                               ;; If it's a simple array, we might be able
861                               ;; to inline the access completely.
862                               (not (null (array-type-complexp type))))
863                       (give-up-ir1-transform
864                        "Upgraded element type of array is not known at compile time.")))
865                   ,(if extra
866                        ``(truly-the ,declared-type
867                                     (,',transform-to array
868                                                      (%check-bound array
869                                                                    (array-dimension array 0)
870                                                                    index)
871                                                      (the ,declared-type ,@',extra)))
872                        ``(the ,declared-type
873                            (,',transform-to array
874                                             (%check-bound array
875                                                           (array-dimension array 0)
876                                                           index))))))))
877   (define hairy-data-vector-ref/check-bounds
878       hairy-data-vector-ref nil nil)
879   (define hairy-data-vector-set/check-bounds
880       hairy-data-vector-set (new-value) (*)))
881
882 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
883 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
884 ;;; array total size.
885 (deftransform row-major-aref ((array index))
886   `(hairy-data-vector-ref array
887                           (%check-bound array (array-total-size array) index)))
888 (deftransform %set-row-major-aref ((array index new-value))
889   `(hairy-data-vector-set array
890                           (%check-bound array (array-total-size array) index)
891                           new-value))
892 \f
893 ;;;; bit-vector array operation canonicalization
894 ;;;;
895 ;;;; We convert all bit-vector operations to have the result array
896 ;;;; specified. This allows any result allocation to be open-coded,
897 ;;;; and eliminates the need for any VM-dependent transforms to handle
898 ;;;; these cases.
899
900 (macrolet ((def (fun)
901              `(progn
902                (deftransform ,fun ((bit-array-1 bit-array-2
903                                                 &optional result-bit-array)
904                                    (bit-vector bit-vector &optional null) *
905                                    :policy (>= speed space))
906                  `(,',fun bit-array-1 bit-array-2
907                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
908                ;; If result is T, make it the first arg.
909                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
910                                    (bit-vector bit-vector (eql t)) *)
911                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
912   (def bit-and)
913   (def bit-ior)
914   (def bit-xor)
915   (def bit-eqv)
916   (def bit-nand)
917   (def bit-nor)
918   (def bit-andc1)
919   (def bit-andc2)
920   (def bit-orc1)
921   (def bit-orc2))
922
923 ;;; Similar for BIT-NOT, but there is only one arg...
924 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
925                        (bit-vector &optional null) *
926                        :policy (>= speed space))
927   '(bit-not bit-array-1
928             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
929 (deftransform bit-not ((bit-array-1 result-bit-array)
930                        (bit-vector (eql t)))
931   '(bit-not bit-array-1 bit-array-1))
932 \f
933 ;;; Pick off some constant cases.
934 (defoptimizer (array-header-p derive-type) ((array))
935   (let ((type (lvar-type array)))
936     (cond ((not (array-type-p type))
937            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
938            nil)
939           (t
940            (let ((dims (array-type-dimensions type)))
941              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
942                     ;; no array header
943                     (specifier-type 'null))
944                    ((and (listp dims) (/= (length dims) 1))
945                     ;; multi-dimensional array, will have a header
946                     (specifier-type '(eql t)))
947                    ((eql (array-type-complexp type) t)
948                     (specifier-type '(eql t)))
949                    (t
950                     nil)))))))