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))
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 nil)
85 (setf element-type cur-type))
86 ((or (eq cur-type *wild-type*)
87 ;; If each of the two following tests fail, it is not
88 ;; possible to determine the element-type of the array
89 ;; because more than one kind of element-type was provided
90 ;; like in '(or (array foo) (array bar)) although a
91 ;; supertype (or foo bar) may be provided as the second
92 ;; returned value returned. See also the KLUDGE below.
93 (not (csubtypep cur-type element-type))
94 (not (csubtypep element-type cur-type)))
95 (setf element-type *wild-type*)))
96 (push (or cur-supertype (type-*-to-t cur-type))
99 (when (eq *wild-type* element-type)
100 (apply #'type-union element-supertypes)))))
102 ;; Convert member-type to an union-type.
103 (array-type-upgraded-element-type
104 (apply #'type-union (mapcar #'ctype-of (member-type-members type)))))
106 ;; KLUDGE: there is no good answer here, but at least
107 ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
108 ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
110 (values *wild-type* nil))))
112 (defun array-type-declared-element-type (type)
113 (if (array-type-p type)
114 (array-type-element-type type)
117 ;;; The ``new-value'' for array setters must fit in the array, and the
118 ;;; return type is going to be the same as the new-value for SETF
120 (defun assert-new-value-type (new-value array)
121 (let ((type (lvar-type array)))
122 (when (array-type-p type)
125 (array-type-specialized-element-type type)
126 (lexenv-policy (node-lexenv (lvar-dest new-value))))))
127 (lvar-type new-value))
129 ;;; Return true if ARG is NIL, or is a constant-lvar whose
130 ;;; value is NIL, false otherwise.
131 (defun unsupplied-or-nil (arg)
132 (declare (type (or lvar null) arg))
134 (and (constant-lvar-p arg)
135 (not (lvar-value arg)))))
137 (defun supplied-and-true (arg)
139 (constant-lvar-p arg)
143 ;;;; DERIVE-TYPE optimizers
145 ;;; Array operations that use a specific number of indices implicitly
146 ;;; assert that the array is of that rank.
147 (defun assert-array-rank (array rank)
150 (specifier-type `(array * ,(make-list rank :initial-element '*)))
151 (lexenv-policy (node-lexenv (lvar-dest array)))))
153 (defun derive-aref-type (array)
154 (multiple-value-bind (uaet other)
155 (array-type-upgraded-element-type (lvar-type array))
158 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
159 (assert-array-rank array (length indices))
162 (deftransform array-in-bounds-p ((array &rest subscripts))
164 (give-up-ir1-transform
165 "~@<lower array bounds unknown or negative and upper bounds not ~
168 (integerp x))) ; might be NIL or *
170 (let ((dimensions (array-type-dimensions-or-give-up
171 (lvar-conservative-type array))))
172 ;; Might be *. (Note: currently this is never true, because the type
173 ;; derivation infers the rank from the call to ARRAY-IN-BOUNDS-P, but
174 ;; let's keep this future proof.)
175 (when (eq '* dimensions)
176 (give-up-ir1-transform "array bounds unknown"))
177 ;; shortcut for zero dimensions
178 (when (some (lambda (dim)
179 (and (bound-known-p dim) (zerop dim)))
182 ;; we first collect the subscripts LVARs' bounds and see whether
183 ;; we can already decide on the result of the optimization without
184 ;; even taking a look at the dimensions.
185 (flet ((subscript-bounds (subscript)
186 (let* ((type1 (lvar-type subscript))
187 (type2 (if (csubtypep type1 (specifier-type 'integer))
188 (weaken-integer-type type1 :range-only t)
190 (low (if (integer-type-p type2)
191 (numeric-type-low type2)
193 (high (numeric-type-high type2)))
195 ((and (or (not (bound-known-p low)) (minusp low))
196 (or (not (bound-known-p high)) (not (minusp high))))
197 ;; can't be sure about the lower bound and the upper bound
198 ;; does not give us a definite clue either.
200 ((and (bound-known-p high) (minusp high))
201 (return nil)) ; definitely below lower bound (zero).
204 (let* ((subscripts-bounds (mapcar #'subscript-bounds subscripts))
205 (subscripts-lower-bound (mapcar #'car subscripts-bounds))
206 (subscripts-upper-bound (mapcar #'cdr subscripts-bounds))
208 (mapcar (lambda (low high dim)
210 ;; first deal with infinite bounds
211 ((some (complement #'bound-known-p) (list low high dim))
212 (when (and (bound-known-p dim) (bound-known-p low) (<= dim low))
214 ;; now we know all bounds
218 (aver (not (minusp low)))
222 subscripts-lower-bound
223 subscripts-upper-bound
225 (if (eql in-bounds (length dimensions))
229 (defoptimizer (aref derive-type) ((array &rest indices) node)
230 (assert-array-rank array (length indices))
231 (derive-aref-type array))
233 (defoptimizer (%aset derive-type) ((array &rest stuff))
234 (assert-array-rank array (1- (length stuff)))
235 (assert-new-value-type (car (last stuff)) array))
237 (macrolet ((define (name)
238 `(defoptimizer (,name derive-type) ((array index))
239 (derive-aref-type array))))
240 (define hairy-data-vector-ref)
241 (define hairy-data-vector-ref/check-bounds)
242 (define data-vector-ref))
245 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
246 (derive-aref-type array))
248 (macrolet ((define (name)
249 `(defoptimizer (,name derive-type) ((array index new-value))
250 (assert-new-value-type new-value array))))
251 (define hairy-data-vector-set)
252 (define hairy-data-vector-set/check-bounds)
253 (define data-vector-set))
256 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
257 (assert-new-value-type new-value array))
259 ;;; Figure out the type of the data vector if we know the argument
261 (defun derive-%with-array-data/mumble-type (array)
262 (let ((atype (lvar-type array)))
263 (when (array-type-p atype)
265 `(simple-array ,(type-specifier
266 (array-type-specialized-element-type atype))
268 (defoptimizer (%with-array-data derive-type) ((array start end))
269 (derive-%with-array-data/mumble-type array))
270 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
271 (derive-%with-array-data/mumble-type array))
273 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
274 (assert-array-rank array (length indices))
277 (defoptimizer (row-major-aref derive-type) ((array index))
278 (derive-aref-type array))
280 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
281 (assert-new-value-type new-value array))
283 (defoptimizer (make-array derive-type)
284 ((dims &key initial-element element-type initial-contents
285 adjustable fill-pointer displaced-index-offset displaced-to))
286 (let* ((simple (and (unsupplied-or-nil adjustable)
287 (unsupplied-or-nil displaced-to)
288 (unsupplied-or-nil fill-pointer)))
290 (or `(,(if simple 'simple-array 'array)
291 ,(cond ((not element-type) t)
292 ((constant-lvar-p element-type)
293 (let ((ctype (careful-specifier-type
294 (lvar-value element-type))))
296 ((or (null ctype) (unknown-type-p ctype)) '*)
297 (t (sb!xc:upgraded-array-element-type
298 (lvar-value element-type))))))
301 ,(cond ((constant-lvar-p dims)
302 (let* ((val (lvar-value dims))
303 (cdims (if (listp val) val (list val))))
307 ((csubtypep (lvar-type dims)
308 (specifier-type 'integer))
313 (if (and (not simple)
314 (or (supplied-and-true adjustable)
315 (supplied-and-true displaced-to)
316 (supplied-and-true fill-pointer)))
317 (careful-specifier-type `(and ,spec (not simple-array)))
318 (careful-specifier-type spec))))
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 (or (and (fun-lexically-notinline-p 'list)
355 (fun-lexically-notinline-p 'vector))
356 (oddp (length keyargs)))
358 (multiple-value-bind (new-dimensions rank)
359 (flet ((constant-dims (dimensions)
360 (let* ((dims (constant-form-value dimensions env))
361 (canon (if (listp dims) dims (list dims)))
362 (rank (length canon)))
363 (values (if (= rank 1)
364 (list 'quote (car canon))
367 (cond ((sb!xc:constantp dimensions env)
368 (constant-dims dimensions))
369 ((and (consp dimensions) (eq 'list dimensions))
370 (values dimensions (length (cdr dimensions))))
372 (values dimensions nil))))
373 (let ((initial-contents (getf keyargs :initial-contents)))
374 (when (and initial-contents rank)
375 (setf (getf keyargs :initial-contents)
376 (rewrite-initial-contents rank initial-contents env))))
377 `(locally (declare (notinline list vector))
378 (make-array ,new-dimensions ,@keyargs)))))
380 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
381 ;;; call which creates a vector with a known element type -- and tries
382 ;;; to do a good job with all the different ways it can happen.
383 (defun transform-make-array-vector (length element-type initial-element
384 initial-contents call)
385 (aver (or (not element-type) (constant-lvar-p element-type)))
386 (let* ((c-length (when (constant-lvar-p length)
387 (lvar-value length)))
388 (elt-spec (if element-type
389 (lvar-value element-type)
391 (elt-ctype (ir1-transform-specifier-type elt-spec))
392 (saetp (if (unknown-type-p elt-ctype)
393 (give-up-ir1-transform "~S is an unknown type: ~S"
394 :element-type elt-spec)
395 (find-saetp-by-ctype elt-ctype)))
396 (default-initial-element (sb!vm:saetp-initial-element-default saetp))
397 (n-bits (sb!vm:saetp-n-bits saetp))
398 (typecode (sb!vm:saetp-typecode saetp))
399 (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
402 (ceiling (* (+ c-length n-pad-elements) n-bits)
404 (let ((padded-length-form (if (zerop n-pad-elements)
406 `(+ length ,n-pad-elements))))
409 ((>= n-bits sb!vm:n-word-bits)
410 `(* ,padded-length-form
412 ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
414 (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
415 (declare (type index n-elements-per-word)) ; i.e., not RATIO
416 `(ceiling ,padded-length-form ,n-elements-per-word)))))))
418 `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
420 `(truly-the ,result-spec
421 (allocate-vector ,typecode (the index length) ,n-words-form))))
422 (cond ((and initial-element initial-contents)
423 (abort-ir1-transform "Both ~S and ~S specified."
424 :initial-contents :initial-element))
425 ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
427 ((and initial-contents c-length
428 (lvar-matches initial-contents
429 :fun-names '(list vector sb!impl::backq-list)
430 :arg-count c-length))
431 (let ((parameters (eliminate-keyword-args
432 call 1 '((:element-type element-type)
433 (:initial-contents initial-contents))))
434 (elt-vars (make-gensym-list c-length))
435 (lambda-list '(length)))
436 (splice-fun-args initial-contents :any c-length)
437 (dolist (p parameters)
440 (if (eq p 'initial-contents)
443 `(lambda ,lambda-list
444 (declare (type ,elt-spec ,@elt-vars)
445 (ignorable ,@lambda-list))
446 (truly-the ,result-spec
447 (initialize-vector ,alloc-form ,@elt-vars)))))
448 ;; constant :INITIAL-CONTENTS and LENGTH
449 ((and initial-contents c-length (constant-lvar-p initial-contents))
450 (let ((contents (lvar-value initial-contents)))
451 (unless (= c-length (length contents))
452 (abort-ir1-transform "~S has ~S elements, vector length is ~S."
453 :initial-contents (length contents) c-length))
454 (let ((parameters (eliminate-keyword-args
455 call 1 '((:element-type element-type)
456 (:initial-contents initial-contents)))))
457 `(lambda (length ,@parameters)
458 (declare (ignorable ,@parameters))
459 (truly-the ,result-spec
460 (initialize-vector ,alloc-form
461 ,@(map 'list (lambda (elt)
462 `(the ,elt-spec ',elt))
464 ;; any other :INITIAL-CONTENTS
466 (let ((parameters (eliminate-keyword-args
467 call 1 '((:element-type element-type)
468 (:initial-contents initial-contents)))))
469 `(lambda (length ,@parameters)
470 (declare (ignorable ,@parameters))
471 (unless (= length (length initial-contents))
472 (error "~S has ~S elements, vector length is ~S."
473 :initial-contents (length initial-contents) length))
474 (truly-the ,result-spec
475 (replace ,alloc-form initial-contents)))))
476 ;; :INITIAL-ELEMENT, not EQL to the default
477 ((and initial-element
478 (or (not (constant-lvar-p initial-element))
479 (not (eql default-initial-element (lvar-value initial-element)))))
480 (let ((parameters (eliminate-keyword-args
481 call 1 '((:element-type element-type)
482 (:initial-element initial-element))))
483 (init (if (constant-lvar-p initial-element)
484 (list 'quote (lvar-value initial-element))
486 `(lambda (length ,@parameters)
487 (declare (ignorable ,@parameters))
488 (truly-the ,result-spec
489 (fill ,alloc-form (the ,elt-spec ,init))))))
490 ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
494 (unless (ctypep default-initial-element elt-ctype)
495 ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
496 ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
497 ;; INITIAL-ELEMENT is not supplied, the consequences of later
498 ;; reading an uninitialized element of new-array are undefined,"
499 ;; so this could be legal code as long as the user plans to
500 ;; write before he reads, and if he doesn't we're free to do
501 ;; anything we like. But in case the user doesn't know to write
502 ;; elements before he reads elements (or to read manuals before
503 ;; he writes code:-), we'll signal a STYLE-WARNING in case he
504 ;; didn't realize this.
506 (compiler-warn "~S ~S is not a ~S"
507 :initial-element default-initial-element
509 (compiler-style-warn "The default initial element ~S is not a ~S."
510 default-initial-element
512 (let ((parameters (eliminate-keyword-args
513 call 1 '((:element-type element-type)
514 (:initial-element initial-element)))))
515 `(lambda (length ,@parameters)
516 (declare (ignorable ,@parameters))
519 ;;; IMPORTANT: The order of these three MAKE-ARRAY forms matters: the least
520 ;;; specific must come first, otherwise suboptimal transforms will result for
523 (deftransform make-array ((dims &key initial-element element-type
524 adjustable fill-pointer)
526 (when (null initial-element)
527 (give-up-ir1-transform))
528 (let* ((eltype (cond ((not element-type) t)
529 ((not (constant-lvar-p element-type))
530 (give-up-ir1-transform
531 "ELEMENT-TYPE is not constant."))
533 (lvar-value element-type))))
534 (eltype-type (ir1-transform-specifier-type eltype))
535 (saetp (find-if (lambda (saetp)
536 (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
537 sb!vm:*specialized-array-element-type-properties*))
538 (creation-form `(make-array dims
539 :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
541 '(:fill-pointer fill-pointer))
543 '(:adjustable adjustable)))))
546 (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
548 (cond ((and (constant-lvar-p initial-element)
549 (eql (lvar-value initial-element)
550 (sb!vm:saetp-initial-element-default saetp)))
553 ;; error checking for target, disabled on the host because
554 ;; (CTYPE-OF #\Null) is not possible.
556 (when (constant-lvar-p initial-element)
557 (let ((value (lvar-value initial-element)))
559 ((not (ctypep value (sb!vm:saetp-ctype saetp)))
560 ;; this case will cause an error at runtime, so we'd
561 ;; better WARN about it now.
562 (warn 'array-initial-element-mismatch
563 :format-control "~@<~S is not a ~S (which is the ~
568 (type-specifier (sb!vm:saetp-ctype saetp))
569 'upgraded-array-element-type
571 ((not (ctypep value eltype-type))
572 ;; this case will not cause an error at runtime, but
573 ;; it's still worth STYLE-WARNing about.
574 (compiler-style-warn "~S is not a ~S."
576 `(let ((array ,creation-form))
577 (multiple-value-bind (vector)
578 (%data-vector-and-index array 0)
579 (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
582 ;;; The list type restriction does not ensure that the result will be a
583 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
584 ;;; and displaced-to keywords ensures that it will be simple.
586 ;;; FIXME: should we generalize this transform to non-simple (though
587 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
588 ;;; deal with those? Maybe when the DEFTRANSFORM
589 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
591 (deftransform make-array ((dims &key
592 element-type initial-element initial-contents)
594 (:element-type (constant-arg *))
596 (:initial-contents *))
600 (when (lvar-matches dims :fun-names '(list) :arg-count 1)
601 (let ((length (car (splice-fun-args dims :any 1))))
602 (return-from make-array
603 (transform-make-array-vector length
608 (unless (constant-lvar-p dims)
609 (give-up-ir1-transform
610 "The dimension list is not constant; cannot open code array creation."))
611 (let ((dims (lvar-value dims)))
612 (unless (every #'integerp dims)
613 (give-up-ir1-transform
614 "The dimension list contains something other than an integer: ~S"
616 (if (= (length dims) 1)
617 `(make-array ',(car dims)
619 '(:element-type element-type))
620 ,@(when initial-element
621 '(:initial-element initial-element))
622 ,@(when initial-contents
623 '(:initial-contents initial-contents)))
624 (let* ((total-size (reduce #'* dims))
627 ,(cond ((null element-type) t)
628 ((and (constant-lvar-p element-type)
629 (ir1-transform-specifier-type
630 (lvar-value element-type)))
631 (sb!xc:upgraded-array-element-type
632 (lvar-value element-type)))
634 ,(make-list rank :initial-element '*))))
635 `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
636 (data (make-array ,total-size
638 '(:element-type element-type))
639 ,@(when initial-element
640 '(:initial-element initial-element)))))
641 ,@(when initial-contents
642 ;; FIXME: This is could be open coded at least a bit too
643 `((sb!impl::fill-data-vector data ',dims initial-contents)))
644 (setf (%array-fill-pointer header) ,total-size)
645 (setf (%array-fill-pointer-p header) nil)
646 (setf (%array-available-elements header) ,total-size)
647 (setf (%array-data-vector header) data)
648 (setf (%array-displaced-p header) nil)
649 (setf (%array-displaced-from header) nil)
651 (mapcar (lambda (dim)
652 `(setf (%array-dimension header ,(incf axis))
655 (truly-the ,spec header)))))))
657 (deftransform make-array ((dims &key element-type initial-element initial-contents)
659 (:element-type (constant-arg *))
661 (:initial-contents *))
664 (transform-make-array-vector dims
670 ;;;; miscellaneous properties of arrays
672 ;;; Transforms for various array properties. If the property is know
673 ;;; at compile time because of a type spec, use that constant value.
675 ;;; Most of this logic may end up belonging in code/late-type.lisp;
676 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
677 ;;; maybe this is just too sloppy for actual type logic. -- CSR,
679 (defun array-type-dimensions-or-give-up (type)
680 (labels ((maybe-array-type-dimensions (type)
683 (array-type-dimensions type))
685 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
686 (union-type-types type))))
687 (result (car types)))
688 (dolist (other (cdr types) result)
689 (unless (equal result other)
690 (give-up-ir1-transform
691 "~@<dimensions of arrays in union type ~S do not match~:@>"
692 (type-specifier type))))))
694 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
695 (intersection-type-types type))))
696 (result (car types)))
697 (dolist (other (cdr types) result)
698 (unless (equal result other)
700 "~@<dimensions of arrays in intersection type ~S do not match~:@>"
701 (type-specifier type)))))))))
702 (or (maybe-array-type-dimensions type)
703 (give-up-ir1-transform
704 "~@<don't know how to extract array dimensions from type ~S~:@>"
705 (type-specifier type)))))
707 (defun conservative-array-type-complexp (type)
709 (array-type (array-type-complexp type))
711 (let ((types (union-type-types type)))
712 (aver (> (length types) 1))
713 (let ((result (conservative-array-type-complexp (car types))))
714 (dolist (type (cdr types) result)
715 (unless (eq (conservative-array-type-complexp type) result)
716 (return-from conservative-array-type-complexp :maybe))))))
717 ;; FIXME: intersection type
720 ;;; If we can tell the rank from the type info, use it instead.
721 (deftransform array-rank ((array))
722 (let ((array-type (lvar-type array)))
723 (let ((dims (array-type-dimensions-or-give-up array-type)))
726 ((eq t (array-type-complexp array-type))
727 '(%array-rank array))
729 `(if (array-header-p array)
733 ;;; If we know the dimensions at compile time, just use it. Otherwise,
734 ;;; if we can tell that the axis is in bounds, convert to
735 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
736 ;;; (if it's simple and a vector).
737 (deftransform array-dimension ((array axis)
739 (unless (constant-lvar-p axis)
740 (give-up-ir1-transform "The axis is not constant."))
741 ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
742 ;; conservative type.
743 (let ((array-type (lvar-conservative-type array))
744 (axis (lvar-value axis)))
745 (let ((dims (array-type-dimensions-or-give-up array-type)))
747 (give-up-ir1-transform
748 "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
749 (unless (> (length dims) axis)
750 (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
753 (let ((dim (nth axis dims)))
754 (cond ((integerp dim)
757 (ecase (conservative-array-type-complexp array-type)
759 '(%array-dimension array 0))
761 '(vector-length array))
763 `(if (array-header-p array)
764 (%array-dimension array axis)
765 (vector-length array)))))
767 '(%array-dimension array axis)))))))
769 ;;; If the length has been declared and it's simple, just return it.
770 (deftransform length ((vector)
771 ((simple-array * (*))))
772 (let ((type (lvar-type vector)))
773 (let ((dims (array-type-dimensions-or-give-up type)))
774 (unless (and (listp dims) (integerp (car dims)))
775 (give-up-ir1-transform
776 "Vector length is unknown, must call LENGTH at runtime."))
779 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
780 ;;; simple, it will extract the length slot from the vector. It it's
781 ;;; complex, it will extract the fill pointer slot from the array
783 (deftransform length ((vector) (vector))
784 '(vector-length vector))
786 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
787 ;;; compile-time constant.
788 (deftransform vector-length ((vector))
789 (let ((vtype (lvar-type vector)))
790 (let ((dim (first (array-type-dimensions-or-give-up vtype))))
792 (give-up-ir1-transform))
793 (when (conservative-array-type-complexp vtype)
794 (give-up-ir1-transform))
797 ;;; Again, if we can tell the results from the type, just use it.
798 ;;; Otherwise, if we know the rank, convert into a computation based
799 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
800 ;;; multiplications because we know that the total size must be an
802 (deftransform array-total-size ((array)
804 (let ((array-type (lvar-type array)))
805 (let ((dims (array-type-dimensions-or-give-up array-type)))
807 (give-up-ir1-transform "can't tell the rank at compile time"))
809 (do ((form 1 `(truly-the index
810 (* (array-dimension array ,i) ,form)))
812 ((= i (length dims)) form))
813 (reduce #'* dims)))))
815 ;;; Only complex vectors have fill pointers.
816 (deftransform array-has-fill-pointer-p ((array))
817 (let ((array-type (lvar-type array)))
818 (let ((dims (array-type-dimensions-or-give-up array-type)))
819 (if (and (listp dims) (not (= (length dims) 1)))
821 (ecase (conservative-array-type-complexp array-type)
827 (give-up-ir1-transform
828 "The array type is ambiguous; must call ~
829 ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
831 ;;; Primitive used to verify indices into arrays. If we can tell at
832 ;;; compile-time or we are generating unsafe code, don't bother with
834 (deftransform %check-bound ((array dimension index) * * :node node)
835 (cond ((policy node (= insert-array-bounds-checks 0))
837 ((not (constant-lvar-p dimension))
838 (give-up-ir1-transform))
840 (let ((dim (lvar-value dimension)))
841 ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
842 `(the (integer 0 (,dim)) index)))))
846 ;;; This checks to see whether the array is simple and the start and
847 ;;; end are in bounds. If so, it proceeds with those values.
848 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
849 ;;; may be further optimized.
851 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
852 ;;; START-VAR and END-VAR to the start and end of the designated
853 ;;; portion of the data vector. SVALUE and EVALUE are any start and
854 ;;; end specified to the original operation, and are factored into the
855 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
856 ;;; offset of all displacements encountered, and does not include
859 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
860 ;;; forced to be inline, overriding the ordinary judgment of the
861 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
862 ;;; fairly picky about their arguments, figuring that if you haven't
863 ;;; bothered to get all your ducks in a row, you probably don't care
864 ;;; that much about speed anyway! But in some cases it makes sense to
865 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
866 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
867 ;;; sense to use FORCE-INLINE option in that case.
868 (def!macro with-array-data (((data-var array &key offset-var)
869 (start-var &optional (svalue 0))
870 (end-var &optional (evalue nil))
871 &key force-inline check-fill-pointer)
874 (once-only ((n-array array)
875 (n-svalue `(the index ,svalue))
876 (n-evalue `(the (or index null) ,evalue)))
877 (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
878 `(multiple-value-bind (,data-var
881 ,@(when offset-var `(,offset-var)))
882 (if (not (array-header-p ,n-array))
883 (let ((,n-array ,n-array))
884 (declare (type (simple-array * (*)) ,n-array))
885 ,(once-only ((n-len (if check-fill-pointer
887 `(array-total-size ,n-array)))
888 (n-end `(or ,n-evalue ,n-len)))
890 `(if (<= 0 ,n-svalue ,n-end ,n-len)
891 (values ,n-array ,n-svalue ,n-end 0)
892 ,(if check-fill-pointer
893 `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
894 `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
895 `(values ,n-array ,n-svalue ,n-end 0))))
897 `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
898 :check-bounds ,check-bounds
899 :check-fill-pointer ,check-fill-pointer)
900 (if check-fill-pointer
901 `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
902 `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
905 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
906 ;;; DEFTRANSFORMs and DEFUNs.
907 (def!macro %with-array-data-macro (array
914 (with-unique-names (size defaulted-end data cumulative-offset)
915 `(let* ((,size ,(if check-fill-pointer
917 `(array-total-size ,array)))
918 (,defaulted-end (or ,end ,size)))
920 `((unless (<= ,start ,defaulted-end ,size)
921 ,(if check-fill-pointer
922 `(sequence-bounding-indices-bad-error ,array ,start ,end)
923 `(array-bounding-indices-bad-error ,array ,start ,end)))))
924 (do ((,data ,array (%array-data-vector ,data))
925 (,cumulative-offset 0
926 (+ ,cumulative-offset
927 (%array-displacement ,data))))
928 ((not (array-header-p ,data))
929 (values (the (simple-array ,element-type 1) ,data)
930 (the index (+ ,cumulative-offset ,start))
931 (the index (+ ,cumulative-offset ,defaulted-end))
932 (the index ,cumulative-offset)))
933 (declare (type index ,cumulative-offset))))))
935 (defun transform-%with-array-data/muble (array node check-fill-pointer)
936 (let ((element-type (upgraded-element-type-specifier-or-give-up array))
937 (type (lvar-type array))
938 (check-bounds (policy node (plusp insert-array-bounds-checks))))
939 (if (and (array-type-p type)
940 (not (array-type-complexp type))
941 (listp (array-type-dimensions type))
942 (not (null (cdr (array-type-dimensions type)))))
943 ;; If it's a simple multidimensional array, then just return
944 ;; its data vector directly rather than going through
945 ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
946 ;; code that would use this currently, but we have encouraged
947 ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
948 ;; some point in the future for optimized libraries or
951 `(let* ((data (truly-the (simple-array ,element-type (*))
952 (%array-data-vector array)))
954 (real-end (or end len)))
955 (unless (<= 0 start data-end lend)
956 (sequence-bounding-indices-bad-error array start end))
957 (values data 0 real-end 0))
958 `(let ((data (truly-the (simple-array ,element-type (*))
959 (%array-data-vector array))))
960 (values data 0 (or end (length data)) 0)))
961 `(%with-array-data-macro array start end
962 :check-fill-pointer ,check-fill-pointer
963 :check-bounds ,check-bounds
964 :element-type ,element-type))))
966 ;; It might very well be reasonable to allow general ARRAY here, I
967 ;; just haven't tried to understand the performance issues involved.
968 ;; -- WHN, and also CSR 2002-05-26
969 (deftransform %with-array-data ((array start end)
970 ((or vector simple-array) index (or index null) t)
973 :policy (> speed space))
974 "inline non-SIMPLE-vector-handling logic"
975 (transform-%with-array-data/muble array node nil))
976 (deftransform %with-array-data/fp ((array start end)
977 ((or vector simple-array) index (or index null) t)
980 :policy (> speed space))
981 "inline non-SIMPLE-vector-handling logic"
982 (transform-%with-array-data/muble array node t))
986 ;;; We convert all typed array accessors into AREF and %ASET with type
987 ;;; assertions on the array.
988 (macrolet ((define-bit-frob (reffer setter simplep)
990 (define-source-transform ,reffer (a &rest i)
991 `(aref (the (,',(if simplep 'simple-array 'array)
993 ,(mapcar (constantly '*) i))
995 (define-source-transform ,setter (a &rest i)
996 `(%aset (the (,',(if simplep 'simple-array 'array)
998 ,(cdr (mapcar (constantly '*) i)))
1000 (define-bit-frob sbit %sbitset t)
1001 (define-bit-frob bit %bitset nil))
1002 (macrolet ((define-frob (reffer setter type)
1004 (define-source-transform ,reffer (a i)
1005 `(aref (the ,',type ,a) ,i))
1006 (define-source-transform ,setter (a i v)
1007 `(%aset (the ,',type ,a) ,i ,v)))))
1008 (define-frob svref %svset simple-vector)
1009 (define-frob schar %scharset simple-string)
1010 (define-frob char %charset string))
1012 (macrolet (;; This is a handy macro for computing the row-major index
1013 ;; given a set of indices. We wrap each index with a call
1014 ;; to %CHECK-BOUND to ensure that everything works out
1015 ;; correctly. We can wrap all the interior arithmetic with
1016 ;; TRULY-THE INDEX because we know the resultant
1017 ;; row-major index must be an index.
1018 (with-row-major-index ((array indices index &optional new-value)
1020 `(let (n-indices dims)
1021 (dotimes (i (length ,indices))
1022 (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
1023 (push (make-symbol (format nil "DIM-~D" i)) dims))
1024 (setf n-indices (nreverse n-indices))
1025 (setf dims (nreverse dims))
1026 `(lambda (,',array ,@n-indices
1027 ,@',(when new-value (list new-value)))
1028 (let* (,@(let ((,index -1))
1029 (mapcar (lambda (name)
1030 `(,name (array-dimension
1037 (do* ((dims dims (cdr dims))
1038 (indices n-indices (cdr indices))
1039 (last-dim nil (car dims))
1040 (form `(%check-bound ,',array
1052 ((null (cdr dims)) form)))))
1055 ;; Just return the index after computing it.
1056 (deftransform array-row-major-index ((array &rest indices))
1057 (with-row-major-index (array indices index)
1060 ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
1061 ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
1062 ;; expression for the row major index.
1063 (deftransform aref ((array &rest indices))
1064 (with-row-major-index (array indices index)
1065 (hairy-data-vector-ref array index)))
1067 (deftransform %aset ((array &rest stuff))
1068 (let ((indices (butlast stuff)))
1069 (with-row-major-index (array indices index new-value)
1070 (hairy-data-vector-set array index new-value)))))
1072 ;; For AREF of vectors we do the bounds checking in the callee. This
1073 ;; lets us do a significantly more efficient check for simple-arrays
1074 ;; without bloating the code. If we already know the type of the array
1075 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
1076 (deftransform aref ((array index) (t t) * :node node)
1077 (let* ((type (lvar-type array))
1078 (element-ctype (array-type-upgraded-element-type type)))
1080 ((and (array-type-p type)
1081 (null (array-type-complexp type))
1082 (not (eql element-ctype *wild-type*))
1083 (eql (length (array-type-dimensions type)) 1))
1084 (let* ((declared-element-ctype (array-type-declared-element-type type))
1086 `(data-vector-ref array
1087 (%check-bound array (array-dimension array 0) index))))
1088 (if (type= declared-element-ctype element-ctype)
1090 `(the ,(type-specifier declared-element-ctype) ,bare-form))))
1091 ((policy node (zerop insert-array-bounds-checks))
1092 `(hairy-data-vector-ref array index))
1093 (t `(hairy-data-vector-ref/check-bounds array index)))))
1095 (deftransform %aset ((array index new-value) (t t t) * :node node)
1096 (if (policy node (zerop insert-array-bounds-checks))
1097 `(hairy-data-vector-set array index new-value)
1098 `(hairy-data-vector-set/check-bounds array index new-value)))
1100 ;;; But if we find out later that there's some useful type information
1101 ;;; available, switch back to the normal one to give other transforms
1103 (macrolet ((define (name transform-to extra extra-type)
1104 (declare (ignore extra-type))
1105 `(deftransform ,name ((array index ,@extra))
1106 (let* ((type (lvar-type array))
1107 (element-type (array-type-upgraded-element-type type))
1108 (declared-type (type-specifier
1109 (array-type-declared-element-type type))))
1110 ;; If an element type has been declared, we want to
1111 ;; use that information it for type checking (even
1112 ;; if the access can't be optimized due to the array
1113 ;; not being simple).
1114 (when (and (eql element-type *wild-type*)
1115 ;; This type logic corresponds to the special
1116 ;; case for strings in HAIRY-DATA-VECTOR-REF
1117 ;; (generic/vm-tran.lisp)
1118 (not (csubtypep type (specifier-type 'simple-string))))
1119 (when (or (not (array-type-p type))
1120 ;; If it's a simple array, we might be able
1121 ;; to inline the access completely.
1122 (not (null (array-type-complexp type))))
1123 (give-up-ir1-transform
1124 "Upgraded element type of array is not known at compile time.")))
1126 ``(truly-the ,declared-type
1127 (,',transform-to array
1129 (array-dimension array 0)
1131 (the ,declared-type ,@',extra)))
1132 ``(the ,declared-type
1133 (,',transform-to array
1135 (array-dimension array 0)
1137 (define hairy-data-vector-ref/check-bounds
1138 hairy-data-vector-ref nil nil)
1139 (define hairy-data-vector-set/check-bounds
1140 hairy-data-vector-set (new-value) (*)))
1142 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
1143 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
1144 ;;; array total size.
1145 (deftransform row-major-aref ((array index))
1146 `(hairy-data-vector-ref array
1147 (%check-bound array (array-total-size array) index)))
1148 (deftransform %set-row-major-aref ((array index new-value))
1149 `(hairy-data-vector-set array
1150 (%check-bound array (array-total-size array) index)
1153 ;;;; bit-vector array operation canonicalization
1155 ;;;; We convert all bit-vector operations to have the result array
1156 ;;;; specified. This allows any result allocation to be open-coded,
1157 ;;;; and eliminates the need for any VM-dependent transforms to handle
1160 (macrolet ((def (fun)
1162 (deftransform ,fun ((bit-array-1 bit-array-2
1163 &optional result-bit-array)
1164 (bit-vector bit-vector &optional null) *
1165 :policy (>= speed space))
1166 `(,',fun bit-array-1 bit-array-2
1167 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1168 ;; If result is T, make it the first arg.
1169 (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1170 (bit-vector bit-vector (eql t)) *)
1171 `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1183 ;;; Similar for BIT-NOT, but there is only one arg...
1184 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1185 (bit-vector &optional null) *
1186 :policy (>= speed space))
1187 '(bit-not bit-array-1
1188 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1189 (deftransform bit-not ((bit-array-1 result-bit-array)
1190 (bit-vector (eql t)))
1191 '(bit-not bit-array-1 bit-array-1))
1193 ;;; Pick off some constant cases.
1194 (defoptimizer (array-header-p derive-type) ((array))
1195 (let ((type (lvar-type array)))
1196 (cond ((not (array-type-p type))
1197 ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1200 (let ((dims (array-type-dimensions type)))
1201 (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1203 (specifier-type 'null))
1204 ((and (listp dims) (/= (length dims) 1))
1205 ;; multi-dimensional array, will have a header
1206 (specifier-type '(eql t)))
1207 ((eql (array-type-complexp type) t)
1208 (specifier-type '(eql t)))