1 ;;;; array-specific optimizers and transforms
3 ;;;; This software is part of the SBCL system. See the README file for
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.
14 ;;;; utilities for optimizing array operations
16 ;;; Return UPGRADED-ARRAY-ELEMENT-TYPE for LVAR, or do
17 ;;; GIVE-UP-IR1-TRANSFORM if the upgraded element type can't be
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)))
26 (defun upgraded-element-type-specifier (lvar)
27 (type-specifier (array-type-upgraded-element-type (lvar-type lvar))))
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
34 (defun array-type-upgraded-element-type (type)
36 ;; Note that this IF mightn't be satisfied even if the runtime
37 ;; value is known to be a subtype of some specialized ARRAY, because
38 ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
39 ;; which are represented in the compiler as INTERSECTION-TYPE, not
42 (values (array-type-specialized-element-type type) nil))
43 ;; Deal with intersection types (bug #316078)
45 (let ((intersection-types (intersection-type-types type))
46 (element-type *wild-type*)
47 (element-supertypes nil))
48 (dolist (intersection-type intersection-types)
49 (multiple-value-bind (cur-type cur-supertype)
50 (array-type-upgraded-element-type intersection-type)
51 ;; According to ANSI, an array may have only one specialized
52 ;; element type - e.g. '(and (array foo) (array bar))
53 ;; is not a valid type unless foo and bar upgrade to the
56 ((eq cur-type *wild-type*)
58 ((eq element-type *wild-type*)
59 (setf element-type cur-type))
60 ((or (not (csubtypep cur-type element-type))
61 (not (csubtypep element-type cur-type)))
62 ;; At least two different element types where given, the array
63 ;; is valid iff they represent the same type.
65 ;; FIXME: TYPE-INTERSECTION already takes care of disjoint array
66 ;; types, so I believe this code should be unreachable. Maybe
67 ;; signal a warning / error instead?
68 (setf element-type *empty-type*)))
69 (push (or cur-supertype (type-*-to-t cur-type))
72 (when (and (eq *wild-type* element-type) element-supertypes)
73 (apply #'type-intersection element-supertypes)))))
75 (let ((union-types (union-type-types type))
76 (element-type *empty-type*)
77 (element-supertypes nil))
78 (dolist (union-type union-types)
79 (multiple-value-bind (cur-type cur-supertype)
80 (array-type-upgraded-element-type union-type)
82 ((eq element-type *wild-type*)
84 ((eq element-type *empty-type*)
85 (setf element-type cur-type))
86 ((or (eq cur-type *wild-type*)
87 ;; If each of the two following tests fail, it is not
88 ;; possible to determine the element-type of the array
89 ;; because more than one kind of element-type was provided
90 ;; like in '(or (array foo) (array bar)) although a
91 ;; supertype (or foo bar) may be provided as the second
92 ;; returned value returned. See also the KLUDGE below.
93 (not (csubtypep cur-type element-type))
94 (not (csubtypep element-type cur-type)))
95 (setf element-type *wild-type*)))
96 (push (or cur-supertype (type-*-to-t cur-type))
99 (when (eq *wild-type* element-type)
100 (apply #'type-union element-supertypes)))))
102 ;; KLUDGE: there is no good answer here, but at least
103 ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
104 ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
106 (values *wild-type* nil))))
108 (defun array-type-declared-element-type (type)
109 (if (array-type-p type)
110 (array-type-element-type type)
113 ;;; The ``new-value'' for array setters must fit in the array, and the
114 ;;; return type is going to be the same as the new-value for SETF
116 (defun assert-new-value-type (new-value array)
117 (let ((type (lvar-type array)))
118 (when (array-type-p type)
121 (array-type-specialized-element-type type)
122 (lexenv-policy (node-lexenv (lvar-dest new-value))))))
123 (lvar-type new-value))
125 (defun assert-array-complex (array)
128 (make-array-type :complexp t
129 :element-type *wild-type*)
130 (lexenv-policy (node-lexenv (lvar-dest array))))
133 ;;; Return true if ARG is NIL, or is a constant-lvar whose
134 ;;; value is NIL, false otherwise.
135 (defun unsupplied-or-nil (arg)
136 (declare (type (or lvar null) arg))
138 (and (constant-lvar-p arg)
139 (not (lvar-value arg)))))
141 ;;;; DERIVE-TYPE optimizers
143 ;;; Array operations that use a specific number of indices implicitly
144 ;;; assert that the array is of that rank.
145 (defun assert-array-rank (array rank)
148 (specifier-type `(array * ,(make-list rank :initial-element '*)))
149 (lexenv-policy (node-lexenv (lvar-dest array)))))
151 (defun derive-aref-type (array)
152 (multiple-value-bind (uaet other)
153 (array-type-upgraded-element-type (lvar-type array))
156 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
157 (assert-array-rank array (length indices))
160 (deftransform array-in-bounds-p ((array &rest subscripts))
162 (give-up-ir1-transform
163 "~@<lower array bounds unknown or negative and upper bounds not ~
166 (integerp x))) ; might be NIL or *
168 (let ((dimensions (array-type-dimensions-or-give-up
169 (lvar-conservative-type array))))
170 ;; shortcut for zero dimensions
171 (when (some (lambda (dim)
172 (and (bound-known-p dim) (zerop dim)))
175 ;; we first collect the subscripts LVARs' bounds and see whether
176 ;; we can already decide on the result of the optimization without
177 ;; even taking a look at the dimensions.
178 (flet ((subscript-bounds (subscript)
179 (let* ((type (lvar-type subscript))
180 (low (numeric-type-low type))
181 (high (numeric-type-high type)))
183 ((and (or (not (bound-known-p low)) (minusp low))
184 (or (not (bound-known-p high)) (not (minusp high))))
185 ;; can't be sure about the lower bound and the upper bound
186 ;; does not give us a definite clue either.
188 ((and (bound-known-p high) (minusp high))
189 (return nil)) ; definitely below lower bound (zero).
192 (let* ((subscripts-bounds (mapcar #'subscript-bounds subscripts))
193 (subscripts-lower-bound (mapcar #'car subscripts-bounds))
194 (subscripts-upper-bound (mapcar #'cdr subscripts-bounds))
196 (mapcar (lambda (low high dim)
198 ;; first deal with infinite bounds
199 ((some (complement #'bound-known-p) (list low high dim))
200 (when (and (bound-known-p dim) (bound-known-p low) (<= dim low))
202 ;; now we know all bounds
206 (aver (not (minusp low)))
210 subscripts-lower-bound
211 subscripts-upper-bound
213 (if (eql in-bounds (length dimensions))
217 (defoptimizer (aref derive-type) ((array &rest indices) node)
218 (assert-array-rank array (length indices))
219 (derive-aref-type array))
221 (defoptimizer (%aset derive-type) ((array &rest stuff))
222 (assert-array-rank array (1- (length stuff)))
223 (assert-new-value-type (car (last stuff)) array))
225 (macrolet ((define (name)
226 `(defoptimizer (,name derive-type) ((array index))
227 (derive-aref-type array))))
228 (define hairy-data-vector-ref)
229 (define hairy-data-vector-ref/check-bounds)
230 (define data-vector-ref))
233 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
234 (derive-aref-type array))
236 (macrolet ((define (name)
237 `(defoptimizer (,name derive-type) ((array index new-value))
238 (assert-new-value-type new-value array))))
239 (define hairy-data-vector-set)
240 (define hairy-data-vector-set/check-bounds)
241 (define data-vector-set))
244 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
245 (assert-new-value-type new-value array))
247 ;;; Figure out the type of the data vector if we know the argument
249 (defun derive-%with-array-data/mumble-type (array)
250 (let ((atype (lvar-type array)))
251 (when (array-type-p atype)
253 `(simple-array ,(type-specifier
254 (array-type-specialized-element-type atype))
256 (defoptimizer (%with-array-data derive-type) ((array start end))
257 (derive-%with-array-data/mumble-type array))
258 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
259 (derive-%with-array-data/mumble-type array))
261 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
262 (assert-array-rank array (length indices))
265 (defoptimizer (row-major-aref derive-type) ((array index))
266 (derive-aref-type array))
268 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
269 (assert-new-value-type new-value array))
271 (defoptimizer (make-array derive-type)
272 ((dims &key initial-element element-type initial-contents
273 adjustable fill-pointer displaced-index-offset displaced-to))
274 (let ((simple (and (unsupplied-or-nil adjustable)
275 (unsupplied-or-nil displaced-to)
276 (unsupplied-or-nil fill-pointer))))
277 (or (careful-specifier-type
278 `(,(if simple 'simple-array 'array)
279 ,(cond ((not element-type) t)
280 ((constant-lvar-p element-type)
281 (let ((ctype (careful-specifier-type
282 (lvar-value element-type))))
284 ((or (null ctype) (unknown-type-p ctype)) '*)
285 (t (sb!xc:upgraded-array-element-type
286 (lvar-value element-type))))))
289 ,(cond ((constant-lvar-p dims)
290 (let* ((val (lvar-value dims))
291 (cdims (if (listp val) val (list val))))
295 ((csubtypep (lvar-type dims)
296 (specifier-type 'integer))
300 (specifier-type 'array))))
302 ;;; Complex array operations should assert that their array argument
303 ;;; is complex. In SBCL, vectors with fill-pointers are complex.
304 (defoptimizer (fill-pointer derive-type) ((vector))
305 (assert-array-complex vector))
306 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
307 (declare (ignorable index))
308 (assert-array-complex vector))
310 (defoptimizer (vector-push derive-type) ((object vector))
311 (declare (ignorable object))
312 (assert-array-complex vector))
313 (defoptimizer (vector-push-extend derive-type)
314 ((object vector &optional index))
315 (declare (ignorable object index))
316 (assert-array-complex vector))
317 (defoptimizer (vector-pop derive-type) ((vector))
318 (assert-array-complex vector))
322 ;;; Convert VECTOR into a MAKE-ARRAY.
323 (define-source-transform vector (&rest elements)
324 `(make-array ,(length elements) :initial-contents (list ,@elements)))
326 ;;; Just convert it into a MAKE-ARRAY.
327 (deftransform make-string ((length &key
328 (element-type 'character)
330 #.*default-init-char-form*)))
331 `(the simple-string (make-array (the index length)
332 :element-type element-type
333 ,@(when initial-element
334 '(:initial-element initial-element)))))
336 (defun rewrite-initial-contents (rank initial-contents env)
338 (if (and (consp initial-contents)
339 (member (car initial-contents) '(list vector sb!impl::backq-list)))
340 `(list ,@(mapcar (lambda (dim)
341 (rewrite-initial-contents (1- rank) dim env))
342 (cdr initial-contents)))
344 ;; This is the important bit: once we are past the level of
345 ;; :INITIAL-CONTENTS that relates to the array structure, reinline LIST
346 ;; and VECTOR so that nested DX isn't screwed up.
347 `(locally (declare (inline list vector))
350 ;;; Prevent open coding DIMENSION and :INITIAL-CONTENTS arguments, so that we
351 ;;; can pick them apart in the DEFTRANSFORMS, and transform '(3) style
352 ;;; dimensions to integer args directly.
353 (define-source-transform make-array (dimensions &rest keyargs &environment env)
354 (if (and (fun-lexically-notinline-p 'list)
355 (fun-lexically-notinline-p 'vector))
357 (multiple-value-bind (new-dimensions rank)
358 (flet ((constant-dims (dimensions)
359 (let* ((dims (constant-form-value dimensions env))
360 (canon (if (listp dims) dims (list dims)))
361 (rank (length canon)))
362 (values (if (= rank 1)
363 (list 'quote (car canon))
366 (cond ((sb!xc:constantp dimensions env)
367 (constant-dims dimensions))
368 ((and (consp dimensions) (eq 'list dimensions))
369 (values dimensions (length (cdr dimensions))))
371 (values dimensions nil))))
372 (let ((initial-contents (getf keyargs :initial-contents)))
373 (when (and initial-contents rank)
374 (setf (getf keyargs :initial-contents)
375 (rewrite-initial-contents rank initial-contents env))))
376 `(locally (declare (notinline list vector))
377 (make-array ,new-dimensions ,@keyargs)))))
379 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
380 ;;; call which creates a vector with a known element type -- and tries
381 ;;; to do a good job with all the different ways it can happen.
382 (defun transform-make-array-vector (length element-type initial-element
383 initial-contents call)
384 (aver (or (not element-type) (constant-lvar-p element-type)))
385 (let* ((c-length (when (constant-lvar-p length)
386 (lvar-value length)))
387 (elt-spec (if element-type
388 (lvar-value element-type)
390 (elt-ctype (ir1-transform-specifier-type elt-spec))
391 (saetp (if (unknown-type-p elt-ctype)
392 (give-up-ir1-transform "~S is an unknown type: ~S"
393 :element-type elt-spec)
394 (find-saetp-by-ctype elt-ctype)))
395 (default-initial-element (sb!vm:saetp-initial-element-default saetp))
396 (n-bits (sb!vm:saetp-n-bits saetp))
397 (typecode (sb!vm:saetp-typecode saetp))
398 (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
401 (ceiling (* (+ c-length n-pad-elements) n-bits)
403 (let ((padded-length-form (if (zerop n-pad-elements)
405 `(+ length ,n-pad-elements))))
408 ((>= n-bits sb!vm:n-word-bits)
409 `(* ,padded-length-form
411 ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
413 (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
414 (declare (type index n-elements-per-word)) ; i.e., not RATIO
415 `(ceiling ,padded-length-form ,n-elements-per-word)))))))
417 `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
419 `(truly-the ,result-spec
420 (allocate-vector ,typecode (the index length) ,n-words-form))))
421 (cond ((and initial-element initial-contents)
422 (abort-ir1-transform "Both ~S and ~S specified."
423 :initial-contents :initial-element))
424 ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
426 ((and initial-contents c-length
427 (lvar-matches initial-contents
428 :fun-names '(list vector sb!impl::backq-list)
429 :arg-count c-length))
430 (let ((parameters (eliminate-keyword-args
431 call 1 '((:element-type element-type)
432 (:initial-contents initial-contents))))
433 (elt-vars (make-gensym-list c-length))
434 (lambda-list '(length)))
435 (splice-fun-args initial-contents :any c-length)
436 (dolist (p parameters)
439 (if (eq p 'initial-contents)
442 `(lambda ,lambda-list
443 (declare (type ,elt-spec ,@elt-vars)
444 (ignorable ,@lambda-list))
445 (truly-the ,result-spec
446 (initialize-vector ,alloc-form ,@elt-vars)))))
447 ;; constant :INITIAL-CONTENTS and LENGTH
448 ((and initial-contents c-length (constant-lvar-p initial-contents))
449 (let ((contents (lvar-value initial-contents)))
450 (unless (= c-length (length contents))
451 (abort-ir1-transform "~S has ~S elements, vector length is ~S."
452 :initial-contents (length contents) c-length))
453 (let ((parameters (eliminate-keyword-args
454 call 1 '((:element-type element-type)
455 (:initial-contents initial-contents)))))
456 `(lambda (length ,@parameters)
457 (declare (ignorable ,@parameters))
458 (truly-the ,result-spec
459 (initialize-vector ,alloc-form
460 ,@(map 'list (lambda (elt)
461 `(the ,elt-spec ',elt))
463 ;; any other :INITIAL-CONTENTS
465 (let ((parameters (eliminate-keyword-args
466 call 1 '((:element-type element-type)
467 (:initial-contents initial-contents)))))
468 `(lambda (length ,@parameters)
469 (declare (ignorable ,@parameters))
470 (unless (= length (length initial-contents))
471 (error "~S has ~S elements, vector length is ~S."
472 :initial-contents (length initial-contents) length))
473 (truly-the ,result-spec
474 (replace ,alloc-form initial-contents)))))
475 ;; :INITIAL-ELEMENT, not EQL to the default
476 ((and initial-element
477 (or (not (constant-lvar-p initial-element))
478 (not (eql default-initial-element (lvar-value initial-element)))))
479 (let ((parameters (eliminate-keyword-args
480 call 1 '((:element-type element-type)
481 (:initial-element initial-element))))
482 (init (if (constant-lvar-p initial-element)
483 (list 'quote (lvar-value initial-element))
485 `(lambda (length ,@parameters)
486 (declare (ignorable ,@parameters))
487 (truly-the ,result-spec
488 (fill ,alloc-form (the ,elt-spec ,init))))))
489 ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
493 (unless (ctypep default-initial-element elt-ctype)
494 ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
495 ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
496 ;; INITIAL-ELEMENT is not supplied, the consequences of later
497 ;; reading an uninitialized element of new-array are undefined,"
498 ;; so this could be legal code as long as the user plans to
499 ;; write before he reads, and if he doesn't we're free to do
500 ;; anything we like. But in case the user doesn't know to write
501 ;; elements before he reads elements (or to read manuals before
502 ;; he writes code:-), we'll signal a STYLE-WARNING in case he
503 ;; didn't realize this.
505 (compiler-warn "~S ~S is not a ~S"
506 :initial-element default-initial-element
508 (compiler-style-warn "The default initial element ~S is not a ~S."
509 default-initial-element
511 (let ((parameters (eliminate-keyword-args
512 call 1 '((:element-type element-type)
513 (:initial-element initial-element)))))
514 `(lambda (length ,@parameters)
515 (declare (ignorable ,@parameters))
518 ;;; IMPORTANT: The order of these three MAKE-ARRAY forms matters: the least
519 ;;; specific must come first, otherwise suboptimal transforms will result for
522 (deftransform make-array ((dims &key initial-element element-type
523 adjustable fill-pointer)
525 (when (null initial-element)
526 (give-up-ir1-transform))
527 (let* ((eltype (cond ((not element-type) t)
528 ((not (constant-lvar-p element-type))
529 (give-up-ir1-transform
530 "ELEMENT-TYPE is not constant."))
532 (lvar-value element-type))))
533 (eltype-type (ir1-transform-specifier-type eltype))
534 (saetp (find-if (lambda (saetp)
535 (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
536 sb!vm:*specialized-array-element-type-properties*))
537 (creation-form `(make-array dims
538 :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
540 '(:fill-pointer fill-pointer))
542 '(:adjustable adjustable)))))
545 (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
547 (cond ((and (constant-lvar-p initial-element)
548 (eql (lvar-value initial-element)
549 (sb!vm:saetp-initial-element-default saetp)))
552 ;; error checking for target, disabled on the host because
553 ;; (CTYPE-OF #\Null) is not possible.
555 (when (constant-lvar-p initial-element)
556 (let ((value (lvar-value initial-element)))
558 ((not (ctypep value (sb!vm:saetp-ctype saetp)))
559 ;; this case will cause an error at runtime, so we'd
560 ;; better WARN about it now.
561 (warn 'array-initial-element-mismatch
562 :format-control "~@<~S is not a ~S (which is the ~
567 (type-specifier (sb!vm:saetp-ctype saetp))
568 'upgraded-array-element-type
570 ((not (ctypep value eltype-type))
571 ;; this case will not cause an error at runtime, but
572 ;; it's still worth STYLE-WARNing about.
573 (compiler-style-warn "~S is not a ~S."
575 `(let ((array ,creation-form))
576 (multiple-value-bind (vector)
577 (%data-vector-and-index array 0)
578 (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
581 ;;; The list type restriction does not ensure that the result will be a
582 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
583 ;;; and displaced-to keywords ensures that it will be simple.
585 ;;; FIXME: should we generalize this transform to non-simple (though
586 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
587 ;;; deal with those? Maybe when the DEFTRANSFORM
588 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
590 (deftransform make-array ((dims &key
591 element-type initial-element initial-contents)
593 (:element-type (constant-arg *))
595 (:initial-contents *))
599 (when (lvar-matches dims :fun-names '(list) :arg-count 1)
600 (let ((length (car (splice-fun-args dims :any 1))))
601 (return-from make-array
602 (transform-make-array-vector length
607 (unless (constant-lvar-p dims)
608 (give-up-ir1-transform
609 "The dimension list is not constant; cannot open code array creation."))
610 (let ((dims (lvar-value dims)))
611 (unless (every #'integerp dims)
612 (give-up-ir1-transform
613 "The dimension list contains something other than an integer: ~S"
615 (if (= (length dims) 1)
616 `(make-array ',(car dims)
618 '(:element-type element-type))
619 ,@(when initial-element
620 '(:initial-element initial-element))
621 ,@(when initial-contents
622 '(:initial-contents initial-contents)))
623 (let* ((total-size (reduce #'* dims))
626 ,(cond ((null element-type) t)
627 ((and (constant-lvar-p element-type)
628 (ir1-transform-specifier-type
629 (lvar-value element-type)))
630 (sb!xc:upgraded-array-element-type
631 (lvar-value element-type)))
633 ,(make-list rank :initial-element '*))))
634 `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
635 (data (make-array ,total-size
637 '(:element-type element-type))
638 ,@(when initial-element
639 '(:initial-element initial-element)))))
640 ,@(when initial-contents
641 ;; FIXME: This is could be open coded at least a bit too
642 `((sb!impl::fill-data-vector data ',dims initial-contents)))
643 (setf (%array-fill-pointer header) ,total-size)
644 (setf (%array-fill-pointer-p header) nil)
645 (setf (%array-available-elements header) ,total-size)
646 (setf (%array-data-vector header) data)
647 (setf (%array-displaced-p header) nil)
648 (setf (%array-displaced-from header) nil)
650 (mapcar (lambda (dim)
651 `(setf (%array-dimension header ,(incf axis))
654 (truly-the ,spec header)))))))
656 (deftransform make-array ((dims &key element-type initial-element initial-contents)
658 (:element-type (constant-arg *))
660 (:initial-contents *))
663 (transform-make-array-vector dims
669 ;;;; miscellaneous properties of arrays
671 ;;; Transforms for various array properties. If the property is know
672 ;;; at compile time because of a type spec, use that constant value.
674 ;;; Most of this logic may end up belonging in code/late-type.lisp;
675 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
676 ;;; maybe this is just too sloppy for actual type logic. -- CSR,
678 (defun array-type-dimensions-or-give-up (type)
679 (labels ((maybe-array-type-dimensions (type)
682 (array-type-dimensions type))
684 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
685 (union-type-types type))))
686 (result (car types)))
687 (dolist (other (cdr types) result)
688 (unless (equal result other)
689 (give-up-ir1-transform
690 "~@<dimensions of arrays in union type ~S do not match~:@>"
691 (type-specifier type))))))
693 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
694 (intersection-type-types type))))
695 (result (car types)))
696 (dolist (other (cdr types) result)
697 (unless (equal result other)
699 "~@<dimensions of arrays in intersection type ~S do not match~:@>"
700 (type-specifier type)))))))))
701 (or (maybe-array-type-dimensions type)
702 (give-up-ir1-transform
703 "~@<don't know how to extract array dimensions from type ~S~:@>"
704 (type-specifier type)))))
706 (defun conservative-array-type-complexp (type)
708 (array-type (array-type-complexp type))
710 (let ((types (union-type-types type)))
711 (aver (> (length types) 1))
712 (let ((result (conservative-array-type-complexp (car types))))
713 (dolist (type (cdr types) result)
714 (unless (eq (conservative-array-type-complexp type) result)
715 (return-from conservative-array-type-complexp :maybe))))))
716 ;; FIXME: intersection type
719 ;;; If we can tell the rank from the type info, use it instead.
720 (deftransform array-rank ((array))
721 (let ((array-type (lvar-type array)))
722 (let ((dims (array-type-dimensions-or-give-up array-type)))
725 ((eq t (array-type-complexp array-type))
726 '(%array-rank array))
728 `(if (array-header-p array)
732 ;;; If we know the dimensions at compile time, just use it. Otherwise,
733 ;;; if we can tell that the axis is in bounds, convert to
734 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
735 ;;; (if it's simple and a vector).
736 (deftransform array-dimension ((array axis)
738 (unless (constant-lvar-p axis)
739 (give-up-ir1-transform "The axis is not constant."))
740 ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
741 ;; conservative type.
742 (let ((array-type (lvar-conservative-type array))
743 (axis (lvar-value axis)))
744 (let ((dims (array-type-dimensions-or-give-up array-type)))
746 (give-up-ir1-transform
747 "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
748 (unless (> (length dims) axis)
749 (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
752 (let ((dim (nth axis dims)))
753 (cond ((integerp dim)
756 (ecase (conservative-array-type-complexp array-type)
758 '(%array-dimension array 0))
760 '(vector-length array))
762 `(if (array-header-p array)
763 (%array-dimension array axis)
764 (vector-length array)))))
766 '(%array-dimension array axis)))))))
768 ;;; If the length has been declared and it's simple, just return it.
769 (deftransform length ((vector)
770 ((simple-array * (*))))
771 (let ((type (lvar-type vector)))
772 (let ((dims (array-type-dimensions-or-give-up type)))
773 (unless (and (listp dims) (integerp (car dims)))
774 (give-up-ir1-transform
775 "Vector length is unknown, must call LENGTH at runtime."))
778 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
779 ;;; simple, it will extract the length slot from the vector. It it's
780 ;;; complex, it will extract the fill pointer slot from the array
782 (deftransform length ((vector) (vector))
783 '(vector-length vector))
785 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
786 ;;; compile-time constant.
787 (deftransform vector-length ((vector))
788 (let ((vtype (lvar-type vector)))
789 (let ((dim (first (array-type-dimensions-or-give-up vtype))))
791 (give-up-ir1-transform))
792 (when (conservative-array-type-complexp vtype)
793 (give-up-ir1-transform))
796 ;;; Again, if we can tell the results from the type, just use it.
797 ;;; Otherwise, if we know the rank, convert into a computation based
798 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
799 ;;; multiplications because we know that the total size must be an
801 (deftransform array-total-size ((array)
803 (let ((array-type (lvar-type array)))
804 (let ((dims (array-type-dimensions-or-give-up array-type)))
806 (give-up-ir1-transform "can't tell the rank at compile time"))
808 (do ((form 1 `(truly-the index
809 (* (array-dimension array ,i) ,form)))
811 ((= i (length dims)) form))
812 (reduce #'* dims)))))
814 ;;; Only complex vectors have fill pointers.
815 (deftransform array-has-fill-pointer-p ((array))
816 (let ((array-type (lvar-type array)))
817 (let ((dims (array-type-dimensions-or-give-up array-type)))
818 (if (and (listp dims) (not (= (length dims) 1)))
820 (ecase (conservative-array-type-complexp array-type)
826 (give-up-ir1-transform
827 "The array type is ambiguous; must call ~
828 ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
830 ;;; Primitive used to verify indices into arrays. If we can tell at
831 ;;; compile-time or we are generating unsafe code, don't bother with
833 (deftransform %check-bound ((array dimension index) * * :node node)
834 (cond ((policy node (= insert-array-bounds-checks 0))
836 ((not (constant-lvar-p dimension))
837 (give-up-ir1-transform))
839 (let ((dim (lvar-value dimension)))
840 ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
841 `(the (integer 0 (,dim)) index)))))
845 ;;; This checks to see whether the array is simple and the start and
846 ;;; end are in bounds. If so, it proceeds with those values.
847 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
848 ;;; may be further optimized.
850 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
851 ;;; START-VAR and END-VAR to the start and end of the designated
852 ;;; portion of the data vector. SVALUE and EVALUE are any start and
853 ;;; end specified to the original operation, and are factored into the
854 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
855 ;;; offset of all displacements encountered, and does not include
858 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
859 ;;; forced to be inline, overriding the ordinary judgment of the
860 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
861 ;;; fairly picky about their arguments, figuring that if you haven't
862 ;;; bothered to get all your ducks in a row, you probably don't care
863 ;;; that much about speed anyway! But in some cases it makes sense to
864 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
865 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
866 ;;; sense to use FORCE-INLINE option in that case.
867 (def!macro with-array-data (((data-var array &key offset-var)
868 (start-var &optional (svalue 0))
869 (end-var &optional (evalue nil))
870 &key force-inline check-fill-pointer)
873 (once-only ((n-array array)
874 (n-svalue `(the index ,svalue))
875 (n-evalue `(the (or index null) ,evalue)))
876 (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
877 `(multiple-value-bind (,data-var
880 ,@(when offset-var `(,offset-var)))
881 (if (not (array-header-p ,n-array))
882 (let ((,n-array ,n-array))
883 (declare (type (simple-array * (*)) ,n-array))
884 ,(once-only ((n-len (if check-fill-pointer
886 `(array-total-size ,n-array)))
887 (n-end `(or ,n-evalue ,n-len)))
889 `(if (<= 0 ,n-svalue ,n-end ,n-len)
890 (values ,n-array ,n-svalue ,n-end 0)
891 ,(if check-fill-pointer
892 `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
893 `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
894 `(values ,n-array ,n-svalue ,n-end 0))))
896 `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
897 :check-bounds ,check-bounds
898 :check-fill-pointer ,check-fill-pointer)
899 (if check-fill-pointer
900 `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
901 `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
904 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
905 ;;; DEFTRANSFORMs and DEFUNs.
906 (def!macro %with-array-data-macro (array
913 (with-unique-names (size defaulted-end data cumulative-offset)
914 `(let* ((,size ,(if check-fill-pointer
916 `(array-total-size ,array)))
917 (,defaulted-end (or ,end ,size)))
919 `((unless (<= ,start ,defaulted-end ,size)
920 ,(if check-fill-pointer
921 `(sequence-bounding-indices-bad-error ,array ,start ,end)
922 `(array-bounding-indices-bad-error ,array ,start ,end)))))
923 (do ((,data ,array (%array-data-vector ,data))
924 (,cumulative-offset 0
925 (+ ,cumulative-offset
926 (%array-displacement ,data))))
927 ((not (array-header-p ,data))
928 (values (the (simple-array ,element-type 1) ,data)
929 (the index (+ ,cumulative-offset ,start))
930 (the index (+ ,cumulative-offset ,defaulted-end))
931 (the index ,cumulative-offset)))
932 (declare (type index ,cumulative-offset))))))
934 (defun transform-%with-array-data/muble (array node check-fill-pointer)
935 (let ((element-type (upgraded-element-type-specifier-or-give-up array))
936 (type (lvar-type array))
937 (check-bounds (policy node (plusp insert-array-bounds-checks))))
938 (if (and (array-type-p type)
939 (not (array-type-complexp type))
940 (listp (array-type-dimensions type))
941 (not (null (cdr (array-type-dimensions type)))))
942 ;; If it's a simple multidimensional array, then just return
943 ;; its data vector directly rather than going through
944 ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
945 ;; code that would use this currently, but we have encouraged
946 ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
947 ;; some point in the future for optimized libraries or
950 `(let* ((data (truly-the (simple-array ,element-type (*))
951 (%array-data-vector array)))
953 (real-end (or end len)))
954 (unless (<= 0 start data-end lend)
955 (sequence-bounding-indices-bad-error array start end))
956 (values data 0 real-end 0))
957 `(let ((data (truly-the (simple-array ,element-type (*))
958 (%array-data-vector array))))
959 (values data 0 (or end (length data)) 0)))
960 `(%with-array-data-macro array start end
961 :check-fill-pointer ,check-fill-pointer
962 :check-bounds ,check-bounds
963 :element-type ,element-type))))
965 ;; It might very well be reasonable to allow general ARRAY here, I
966 ;; just haven't tried to understand the performance issues involved.
967 ;; -- WHN, and also CSR 2002-05-26
968 (deftransform %with-array-data ((array start end)
969 ((or vector simple-array) index (or index null) t)
972 :policy (> speed space))
973 "inline non-SIMPLE-vector-handling logic"
974 (transform-%with-array-data/muble array node nil))
975 (deftransform %with-array-data/fp ((array start end)
976 ((or vector simple-array) index (or index null) t)
979 :policy (> speed space))
980 "inline non-SIMPLE-vector-handling logic"
981 (transform-%with-array-data/muble array node t))
985 ;;; We convert all typed array accessors into AREF and %ASET with type
986 ;;; assertions on the array.
987 (macrolet ((define-bit-frob (reffer setter simplep)
989 (define-source-transform ,reffer (a &rest i)
990 `(aref (the (,',(if simplep 'simple-array 'array)
992 ,(mapcar (constantly '*) i))
994 (define-source-transform ,setter (a &rest i)
995 `(%aset (the (,',(if simplep 'simple-array 'array)
997 ,(cdr (mapcar (constantly '*) i)))
999 (define-bit-frob sbit %sbitset t)
1000 (define-bit-frob bit %bitset nil))
1001 (macrolet ((define-frob (reffer setter type)
1003 (define-source-transform ,reffer (a i)
1004 `(aref (the ,',type ,a) ,i))
1005 (define-source-transform ,setter (a i v)
1006 `(%aset (the ,',type ,a) ,i ,v)))))
1007 (define-frob svref %svset simple-vector)
1008 (define-frob schar %scharset simple-string)
1009 (define-frob char %charset string))
1011 (macrolet (;; This is a handy macro for computing the row-major index
1012 ;; given a set of indices. We wrap each index with a call
1013 ;; to %CHECK-BOUND to ensure that everything works out
1014 ;; correctly. We can wrap all the interior arithmetic with
1015 ;; TRULY-THE INDEX because we know the resultant
1016 ;; row-major index must be an index.
1017 (with-row-major-index ((array indices index &optional new-value)
1019 `(let (n-indices dims)
1020 (dotimes (i (length ,indices))
1021 (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
1022 (push (make-symbol (format nil "DIM-~D" i)) dims))
1023 (setf n-indices (nreverse n-indices))
1024 (setf dims (nreverse dims))
1025 `(lambda (,',array ,@n-indices
1026 ,@',(when new-value (list new-value)))
1027 (let* (,@(let ((,index -1))
1028 (mapcar (lambda (name)
1029 `(,name (array-dimension
1036 (do* ((dims dims (cdr dims))
1037 (indices n-indices (cdr indices))
1038 (last-dim nil (car dims))
1039 (form `(%check-bound ,',array
1051 ((null (cdr dims)) form)))))
1054 ;; Just return the index after computing it.
1055 (deftransform array-row-major-index ((array &rest indices))
1056 (with-row-major-index (array indices index)
1059 ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
1060 ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
1061 ;; expression for the row major index.
1062 (deftransform aref ((array &rest indices))
1063 (with-row-major-index (array indices index)
1064 (hairy-data-vector-ref array index)))
1066 (deftransform %aset ((array &rest stuff))
1067 (let ((indices (butlast stuff)))
1068 (with-row-major-index (array indices index new-value)
1069 (hairy-data-vector-set array index new-value)))))
1071 ;; For AREF of vectors we do the bounds checking in the callee. This
1072 ;; lets us do a significantly more efficient check for simple-arrays
1073 ;; without bloating the code. If we already know the type of the array
1074 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
1075 (deftransform aref ((array index) (t t) * :node node)
1076 (let* ((type (lvar-type array))
1077 (element-ctype (array-type-upgraded-element-type type)))
1079 ((and (array-type-p type)
1080 (null (array-type-complexp type))
1081 (not (eql element-ctype *wild-type*))
1082 (eql (length (array-type-dimensions type)) 1))
1083 (let* ((declared-element-ctype (array-type-declared-element-type type))
1085 `(data-vector-ref array
1086 (%check-bound array (array-dimension array 0) index))))
1087 (if (type= declared-element-ctype element-ctype)
1089 `(the ,(type-specifier declared-element-ctype) ,bare-form))))
1090 ((policy node (zerop insert-array-bounds-checks))
1091 `(hairy-data-vector-ref array index))
1092 (t `(hairy-data-vector-ref/check-bounds array index)))))
1094 (deftransform %aset ((array index new-value) (t t t) * :node node)
1095 (if (policy node (zerop insert-array-bounds-checks))
1096 `(hairy-data-vector-set array index new-value)
1097 `(hairy-data-vector-set/check-bounds array index new-value)))
1099 ;;; But if we find out later that there's some useful type information
1100 ;;; available, switch back to the normal one to give other transforms
1102 (macrolet ((define (name transform-to extra extra-type)
1103 (declare (ignore extra-type))
1104 `(deftransform ,name ((array index ,@extra))
1105 (let* ((type (lvar-type array))
1106 (element-type (array-type-upgraded-element-type type))
1107 (declared-type (array-type-declared-element-type type)))
1108 ;; If an element type has been declared, we want to
1109 ;; use that information it for type checking (even
1110 ;; if the access can't be optimized due to the array
1111 ;; not being simple).
1112 (when (and (eql element-type *wild-type*)
1113 ;; This type logic corresponds to the special
1114 ;; case for strings in HAIRY-DATA-VECTOR-REF
1115 ;; (generic/vm-tran.lisp)
1116 (not (csubtypep type (specifier-type 'simple-string))))
1117 (when (or (not (array-type-p type))
1118 ;; If it's a simple array, we might be able
1119 ;; to inline the access completely.
1120 (not (null (array-type-complexp type))))
1121 (give-up-ir1-transform
1122 "Upgraded element type of array is not known at compile time.")))
1124 ``(truly-the ,declared-type
1125 (,',transform-to array
1127 (array-dimension array 0)
1129 (the ,declared-type ,@',extra)))
1130 ``(the ,declared-type
1131 (,',transform-to array
1133 (array-dimension array 0)
1135 (define hairy-data-vector-ref/check-bounds
1136 hairy-data-vector-ref nil nil)
1137 (define hairy-data-vector-set/check-bounds
1138 hairy-data-vector-set (new-value) (*)))
1140 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
1141 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
1142 ;;; array total size.
1143 (deftransform row-major-aref ((array index))
1144 `(hairy-data-vector-ref array
1145 (%check-bound array (array-total-size array) index)))
1146 (deftransform %set-row-major-aref ((array index new-value))
1147 `(hairy-data-vector-set array
1148 (%check-bound array (array-total-size array) index)
1151 ;;;; bit-vector array operation canonicalization
1153 ;;;; We convert all bit-vector operations to have the result array
1154 ;;;; specified. This allows any result allocation to be open-coded,
1155 ;;;; and eliminates the need for any VM-dependent transforms to handle
1158 (macrolet ((def (fun)
1160 (deftransform ,fun ((bit-array-1 bit-array-2
1161 &optional result-bit-array)
1162 (bit-vector bit-vector &optional null) *
1163 :policy (>= speed space))
1164 `(,',fun bit-array-1 bit-array-2
1165 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1166 ;; If result is T, make it the first arg.
1167 (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1168 (bit-vector bit-vector (eql t)) *)
1169 `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1181 ;;; Similar for BIT-NOT, but there is only one arg...
1182 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1183 (bit-vector &optional null) *
1184 :policy (>= speed space))
1185 '(bit-not bit-array-1
1186 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1187 (deftransform bit-not ((bit-array-1 result-bit-array)
1188 (bit-vector (eql t)))
1189 '(bit-not bit-array-1 bit-array-1))
1191 ;;; Pick off some constant cases.
1192 (defoptimizer (array-header-p derive-type) ((array))
1193 (let ((type (lvar-type array)))
1194 (cond ((not (array-type-p type))
1195 ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1198 (let ((dims (array-type-dimensions type)))
1199 (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1201 (specifier-type 'null))
1202 ((and (listp dims) (/= (length dims) 1))
1203 ;; multi-dimensional array, will have a header
1204 (specifier-type '(eql t)))
1205 ((eql (array-type-complexp type) t)
1206 (specifier-type '(eql t)))