0.9.9.9:
[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
28 ;;; type is going to be the array upgraded element type.
29 (defun extract-upgraded-element-type (array)
30   (let ((type (lvar-type array)))
31     (cond
32       ;; Note that this IF mightn't be satisfied even if the runtime
33       ;; value is known to be a subtype of some specialized ARRAY, because
34       ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
35       ;; which are represented in the compiler as INTERSECTION-TYPE, not
36       ;; array type.
37       ((array-type-p type) (array-type-specialized-element-type type))
38       ;; fix for bug #396.  This type logic corresponds to the special
39       ;; case for strings in HAIRY-DATA-VECTOR-REF
40       ;; (generic/vm-tran.lisp)
41       ((csubtypep type (specifier-type 'simple-string))
42        (cond
43          ((csubtypep type (specifier-type '(simple-array character (*))))
44           (specifier-type 'character))
45          #!+sb-unicode
46          ((csubtypep type (specifier-type '(simple-array base-char (*))))
47           (specifier-type 'base-char))
48          ((csubtypep type (specifier-type '(simple-array nil (*))))
49           *empty-type*)
50          ;; see KLUDGE below.
51          (t *wild-type*)))
52       (t
53        ;; KLUDGE: there is no good answer here, but at least
54        ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
55        ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
56        ;; 2002-08-21
57        *wild-type*))))
58
59 (defun extract-declared-element-type (array)
60   (let ((type (lvar-type array)))
61     (if (array-type-p type)
62         (array-type-element-type type)
63         *wild-type*)))
64
65 ;;; The ``new-value'' for array setters must fit in the array, and the
66 ;;; return type is going to be the same as the new-value for SETF
67 ;;; functions.
68 (defun assert-new-value-type (new-value array)
69   (let ((type (lvar-type array)))
70     (when (array-type-p type)
71       (assert-lvar-type
72        new-value
73        (array-type-specialized-element-type type)
74        (lexenv-policy (node-lexenv (lvar-dest new-value))))))
75   (lvar-type new-value))
76
77 (defun assert-array-complex (array)
78   (assert-lvar-type
79    array
80    (make-array-type :complexp t
81                     :element-type *wild-type*)
82    (lexenv-policy (node-lexenv (lvar-dest array))))
83   nil)
84
85 ;;; Return true if ARG is NIL, or is a constant-lvar whose
86 ;;; value is NIL, false otherwise.
87 (defun unsupplied-or-nil (arg)
88   (declare (type (or lvar null) arg))
89   (or (not arg)
90       (and (constant-lvar-p arg)
91            (not (lvar-value arg)))))
92 \f
93 ;;;; DERIVE-TYPE optimizers
94
95 ;;; Array operations that use a specific number of indices implicitly
96 ;;; assert that the array is of that rank.
97 (defun assert-array-rank (array rank)
98   (assert-lvar-type
99    array
100    (specifier-type `(array * ,(make-list rank :initial-element '*)))
101    (lexenv-policy (node-lexenv (lvar-dest array)))))
102
103 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
104   (assert-array-rank array (length indices))
105   *universal-type*)
106
107 (defoptimizer (aref derive-type) ((array &rest indices) node)
108   (assert-array-rank array (length indices))
109   (extract-upgraded-element-type array))
110
111 (defoptimizer (%aset derive-type) ((array &rest stuff))
112   (assert-array-rank array (1- (length stuff)))
113   (assert-new-value-type (car (last stuff)) array))
114
115 (defoptimizer (hairy-data-vector-ref derive-type) ((array index))
116   (extract-upgraded-element-type array))
117 (defoptimizer (data-vector-ref derive-type) ((array index))
118   (extract-upgraded-element-type array))
119
120 (defoptimizer (data-vector-set derive-type) ((array index new-value))
121   (assert-new-value-type new-value array))
122 (defoptimizer (hairy-data-vector-set derive-type) ((array index new-value))
123   (assert-new-value-type new-value array))
124
125 ;;; Figure out the type of the data vector if we know the argument
126 ;;; element type.
127 (defoptimizer (%with-array-data derive-type) ((array start end))
128   (let ((atype (lvar-type array)))
129     (when (array-type-p atype)
130       (specifier-type
131        `(simple-array ,(type-specifier
132                        (array-type-specialized-element-type atype))
133                      (*))))))
134
135 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
136   (assert-array-rank array (length indices))
137   *universal-type*)
138
139 (defoptimizer (row-major-aref derive-type) ((array index))
140   (extract-upgraded-element-type array))
141
142 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
143   (assert-new-value-type new-value array))
144
145 (defoptimizer (make-array derive-type)
146               ((dims &key initial-element element-type initial-contents
147                 adjustable fill-pointer displaced-index-offset displaced-to))
148   (let ((simple (and (unsupplied-or-nil adjustable)
149                      (unsupplied-or-nil displaced-to)
150                      (unsupplied-or-nil fill-pointer))))
151     (or (careful-specifier-type
152          `(,(if simple 'simple-array 'array)
153             ,(cond ((not element-type) t)
154                    ((constant-lvar-p element-type)
155                     (let ((ctype (careful-specifier-type
156                                   (lvar-value element-type))))
157                       (cond
158                         ((or (null ctype) (unknown-type-p ctype)) '*)
159                         (t (sb!xc:upgraded-array-element-type
160                             (lvar-value element-type))))))
161                    (t
162                     '*))
163             ,(cond ((constant-lvar-p dims)
164                     (let* ((val (lvar-value dims))
165                            (cdims (if (listp val) val (list val))))
166                       (if simple
167                           cdims
168                           (length cdims))))
169                    ((csubtypep (lvar-type dims)
170                                (specifier-type 'integer))
171                     '(*))
172                    (t
173                     '*))))
174         (specifier-type 'array))))
175
176 ;;; Complex array operations should assert that their array argument
177 ;;; is complex.  In SBCL, vectors with fill-pointers are complex.
178 (defoptimizer (fill-pointer derive-type) ((vector))
179   (assert-array-complex vector))
180 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
181   (declare (ignorable index))
182   (assert-array-complex vector))
183
184 (defoptimizer (vector-push derive-type) ((object vector))
185   (declare (ignorable object))
186   (assert-array-complex vector))
187 (defoptimizer (vector-push-extend derive-type)
188     ((object vector &optional index))
189   (declare (ignorable object index))
190   (assert-array-complex vector))
191 (defoptimizer (vector-pop derive-type) ((vector))
192   (assert-array-complex vector))
193 \f
194 ;;;; constructors
195
196 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
197 ;;; elements.
198 (define-source-transform vector (&rest elements)
199   (let ((len (length elements))
200         (n -1))
201     (once-only ((n-vec `(make-array ,len)))
202       `(progn
203          ,@(mapcar (lambda (el)
204                      (once-only ((n-val el))
205                        `(locally (declare (optimize (safety 0)))
206                                  (setf (svref ,n-vec ,(incf n))
207                                        ,n-val))))
208                    elements)
209          ,n-vec))))
210
211 ;;; Just convert it into a MAKE-ARRAY.
212 (deftransform make-string ((length &key
213                                    (element-type 'character)
214                                    (initial-element
215                                     #.*default-init-char-form*)))
216   `(the simple-string (make-array (the index length)
217                        :element-type element-type
218                        ,@(when initial-element
219                            '(:initial-element initial-element)))))
220
221 (deftransform make-array ((dims &key initial-element element-type
222                                      adjustable fill-pointer)
223                           (t &rest *))
224   (when (null initial-element)
225     (give-up-ir1-transform))
226   (let* ((eltype (cond ((not element-type) t)
227                        ((not (constant-lvar-p element-type))
228                         (give-up-ir1-transform
229                          "ELEMENT-TYPE is not constant."))
230                        (t
231                         (lvar-value element-type))))
232          (eltype-type (ir1-transform-specifier-type eltype))
233          (saetp (find-if (lambda (saetp)
234                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
235                          sb!vm:*specialized-array-element-type-properties*))
236          (creation-form `(make-array dims
237                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
238                           ,@(when fill-pointer
239                                   '(:fill-pointer fill-pointer))
240                           ,@(when adjustable
241                                   '(:adjustable adjustable)))))
242
243     (unless saetp
244       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
245
246     (cond ((and (constant-lvar-p initial-element)
247                 (eql (lvar-value initial-element)
248                      (sb!vm:saetp-initial-element-default saetp)))
249            creation-form)
250           (t
251            ;; error checking for target, disabled on the host because
252            ;; (CTYPE-OF #\Null) is not possible.
253            #-sb-xc-host
254            (when (constant-lvar-p initial-element)
255              (let ((value (lvar-value initial-element)))
256                (cond
257                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
258                   ;; this case will cause an error at runtime, so we'd
259                   ;; better WARN about it now.
260                   (warn 'array-initial-element-mismatch
261                         :format-control "~@<~S is not a ~S (which is the ~
262                                          ~S of ~S).~@:>"
263                         :format-arguments
264                         (list
265                          value
266                          (type-specifier (sb!vm:saetp-ctype saetp))
267                          'upgraded-array-element-type
268                          eltype)))
269                  ((not (ctypep value eltype-type))
270                   ;; this case will not cause an error at runtime, but
271                   ;; it's still worth STYLE-WARNing about.
272                   (compiler-style-warn "~S is not a ~S."
273                                        value eltype)))))
274            `(let ((array ,creation-form))
275              (multiple-value-bind (vector)
276                  (%data-vector-and-index array 0)
277                (fill vector initial-element))
278              array)))))
279
280 ;;; The integer type restriction on the length ensures that it will be
281 ;;; a vector. The lack of :ADJUSTABLE, :FILL-POINTER, and
282 ;;; :DISPLACED-TO keywords ensures that it will be simple; the lack of
283 ;;; :INITIAL-ELEMENT relies on another transform to deal with that
284 ;;; kind of initialization efficiently.
285 (deftransform make-array ((length &key element-type)
286                           (integer &rest *))
287   (let* ((eltype (cond ((not element-type) t)
288                        ((not (constant-lvar-p element-type))
289                         (give-up-ir1-transform
290                          "ELEMENT-TYPE is not constant."))
291                        (t
292                         (lvar-value element-type))))
293          (len (if (constant-lvar-p length)
294                   (lvar-value length)
295                   '*))
296          (eltype-type (ir1-transform-specifier-type eltype))
297          (result-type-spec
298           `(simple-array
299             ,(if (unknown-type-p eltype-type)
300                  (give-up-ir1-transform
301                   "ELEMENT-TYPE is an unknown type: ~S" eltype)
302                  (sb!xc:upgraded-array-element-type eltype))
303             (,len)))
304          (saetp (find-if (lambda (saetp)
305                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
306                          sb!vm:*specialized-array-element-type-properties*)))
307     (unless saetp
308       (give-up-ir1-transform
309        "cannot open-code creation of ~S" result-type-spec))
310     #-sb-xc-host
311     (unless (ctypep (sb!vm:saetp-initial-element-default saetp) eltype-type)
312       ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
313       ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
314       ;; INITIAL-ELEMENT is not supplied, the consequences of later
315       ;; reading an uninitialized element of new-array are undefined,"
316       ;; so this could be legal code as long as the user plans to
317       ;; write before he reads, and if he doesn't we're free to do
318       ;; anything we like. But in case the user doesn't know to write
319       ;; elements before he reads elements (or to read manuals before
320       ;; he writes code:-), we'll signal a STYLE-WARNING in case he
321       ;; didn't realize this.
322       (compiler-style-warn "The default initial element ~S is not a ~S."
323                            (sb!vm:saetp-initial-element-default saetp)
324                            eltype))
325     (let* ((n-bits-per-element (sb!vm:saetp-n-bits saetp))
326            (typecode (sb!vm:saetp-typecode saetp))
327            (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
328            (padded-length-form (if (zerop n-pad-elements)
329                                    'length
330                                    `(+ length ,n-pad-elements)))
331            (n-words-form
332             (cond
333               ((= n-bits-per-element 0) 0)
334               ((>= n-bits-per-element sb!vm:n-word-bits)
335                `(* ,padded-length-form
336                  (the fixnum ; i.e., not RATIO
337                    ,(/ n-bits-per-element sb!vm:n-word-bits))))
338               (t
339                (let ((n-elements-per-word (/ sb!vm:n-word-bits
340                                              n-bits-per-element)))
341                  (declare (type index n-elements-per-word)) ; i.e., not RATIO
342                  `(ceiling ,padded-length-form ,n-elements-per-word))))))
343       (values
344        `(truly-the ,result-type-spec
345          (allocate-vector ,typecode length ,n-words-form))
346        '((declare (type index length)))))))
347
348 ;;; The list type restriction does not ensure that the result will be a
349 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
350 ;;; and displaced-to keywords ensures that it will be simple.
351 ;;;
352 ;;; FIXME: should we generalize this transform to non-simple (though
353 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
354 ;;; deal with those? Maybe when the DEFTRANSFORM
355 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
356 ;;; CSR, 2002-07-01
357 (deftransform make-array ((dims &key element-type)
358                           (list &rest *))
359   (unless (or (null element-type) (constant-lvar-p element-type))
360     (give-up-ir1-transform
361      "The element-type is not constant; cannot open code array creation."))
362   (unless (constant-lvar-p dims)
363     (give-up-ir1-transform
364      "The dimension list is not constant; cannot open code array creation."))
365   (let ((dims (lvar-value dims)))
366     (unless (every #'integerp dims)
367       (give-up-ir1-transform
368        "The dimension list contains something other than an integer: ~S"
369        dims))
370     (if (= (length dims) 1)
371         `(make-array ',(car dims)
372                      ,@(when element-type
373                          '(:element-type element-type)))
374         (let* ((total-size (reduce #'* dims))
375                (rank (length dims))
376                (spec `(simple-array
377                        ,(cond ((null element-type) t)
378                               ((and (constant-lvar-p element-type)
379                                     (ir1-transform-specifier-type
380                                      (lvar-value element-type)))
381                                (sb!xc:upgraded-array-element-type
382                                 (lvar-value element-type)))
383                               (t '*))
384                            ,(make-list rank :initial-element '*))))
385           `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank)))
386              (setf (%array-fill-pointer header) ,total-size)
387              (setf (%array-fill-pointer-p header) nil)
388              (setf (%array-available-elements header) ,total-size)
389              (setf (%array-data-vector header)
390                    (make-array ,total-size
391                                ,@(when element-type
392                                    '(:element-type element-type))))
393              (setf (%array-displaced-p header) nil)
394              ,@(let ((axis -1))
395                  (mapcar (lambda (dim)
396                            `(setf (%array-dimension header ,(incf axis))
397                                   ,dim))
398                          dims))
399              (truly-the ,spec header))))))
400 \f
401 ;;;; miscellaneous properties of arrays
402
403 ;;; Transforms for various array properties. If the property is know
404 ;;; at compile time because of a type spec, use that constant value.
405
406 ;;; Most of this logic may end up belonging in code/late-type.lisp;
407 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
408 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
409 ;;; 2004-02-18
410 (defun array-type-dimensions-or-give-up (type)
411   (typecase type
412     (array-type (array-type-dimensions type))
413     (union-type
414      (let ((types (union-type-types type)))
415        ;; there are at least two types, right?
416        (aver (> (length types) 1))
417        (let ((result (array-type-dimensions-or-give-up (car types))))
418          (dolist (type (cdr types) result)
419            (unless (equal (array-type-dimensions-or-give-up type) result)
420              (give-up-ir1-transform))))))
421     ;; FIXME: intersection type [e.g. (and (array * (*)) (satisfies foo)) ]
422     (t (give-up-ir1-transform))))
423
424 (defun conservative-array-type-complexp (type)
425   (typecase type
426     (array-type (array-type-complexp type))
427     (union-type
428      (let ((types (union-type-types type)))
429        (aver (> (length types) 1))
430        (let ((result (conservative-array-type-complexp (car types))))
431          (dolist (type (cdr types) result)
432            (unless (eq (conservative-array-type-complexp type) result)
433              (return-from conservative-array-type-complexp :maybe))))))
434     ;; FIXME: intersection type
435     (t :maybe)))
436
437 ;;; If we can tell the rank from the type info, use it instead.
438 (deftransform array-rank ((array))
439   (let ((array-type (lvar-type array)))
440     (let ((dims (array-type-dimensions-or-give-up array-type)))
441       (if (not (listp dims))
442           (give-up-ir1-transform
443            "The array rank is not known at compile time: ~S"
444            dims)
445           (length dims)))))
446
447 ;;; If we know the dimensions at compile time, just use it. Otherwise,
448 ;;; if we can tell that the axis is in bounds, convert to
449 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
450 ;;; (if it's simple and a vector).
451 (deftransform array-dimension ((array axis)
452                                (array index))
453   (unless (constant-lvar-p axis)
454     (give-up-ir1-transform "The axis is not constant."))
455   (let ((array-type (lvar-type array))
456         (axis (lvar-value axis)))
457     (let ((dims (array-type-dimensions-or-give-up array-type)))
458       (unless (listp dims)
459         (give-up-ir1-transform
460          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
461       (unless (> (length dims) axis)
462         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
463                              dims
464                              axis))
465       (let ((dim (nth axis dims)))
466         (cond ((integerp dim)
467                dim)
468               ((= (length dims) 1)
469                (ecase (conservative-array-type-complexp array-type)
470                  ((t)
471                   '(%array-dimension array 0))
472                  ((nil)
473                   '(length array))
474                  ((:maybe)
475                   (give-up-ir1-transform
476                    "can't tell whether array is simple"))))
477               (t
478                '(%array-dimension array axis)))))))
479
480 ;;; If the length has been declared and it's simple, just return it.
481 (deftransform length ((vector)
482                       ((simple-array * (*))))
483   (let ((type (lvar-type vector)))
484     (let ((dims (array-type-dimensions-or-give-up type)))
485       (unless (and (listp dims) (integerp (car dims)))
486         (give-up-ir1-transform
487          "Vector length is unknown, must call LENGTH at runtime."))
488       (car dims))))
489
490 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
491 ;;; simple, it will extract the length slot from the vector. It it's
492 ;;; complex, it will extract the fill pointer slot from the array
493 ;;; header.
494 (deftransform length ((vector) (vector))
495   '(vector-length vector))
496
497 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
498 ;;; compile-time constant.
499 (deftransform vector-length ((vector))
500   (let ((vtype (lvar-type vector)))
501     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
502       (when (eq dim '*)
503         (give-up-ir1-transform))
504       (when (conservative-array-type-complexp vtype)
505         (give-up-ir1-transform))
506       dim)))
507
508 ;;; Again, if we can tell the results from the type, just use it.
509 ;;; Otherwise, if we know the rank, convert into a computation based
510 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
511 ;;; multiplications because we know that the total size must be an
512 ;;; INDEX.
513 (deftransform array-total-size ((array)
514                                 (array))
515   (let ((array-type (lvar-type array)))
516     (let ((dims (array-type-dimensions-or-give-up array-type)))
517       (unless (listp dims)
518         (give-up-ir1-transform "can't tell the rank at compile time"))
519       (if (member '* dims)
520           (do ((form 1 `(truly-the index
521                                    (* (array-dimension array ,i) ,form)))
522                (i 0 (1+ i)))
523               ((= i (length dims)) form))
524           (reduce #'* dims)))))
525
526 ;;; Only complex vectors have fill pointers.
527 (deftransform array-has-fill-pointer-p ((array))
528   (let ((array-type (lvar-type array)))
529     (let ((dims (array-type-dimensions-or-give-up array-type)))
530       (if (and (listp dims) (not (= (length dims) 1)))
531           nil
532           (ecase (conservative-array-type-complexp array-type)
533             ((t)
534              t)
535             ((nil)
536              nil)
537             ((:maybe)
538              (give-up-ir1-transform
539               "The array type is ambiguous; must call ~
540                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
541
542 ;;; Primitive used to verify indices into arrays. If we can tell at
543 ;;; compile-time or we are generating unsafe code, don't bother with
544 ;;; the VOP.
545 (deftransform %check-bound ((array dimension index) * * :node node)
546   (cond ((policy node (and (> speed safety) (= safety 0)))
547          'index)
548         ((not (constant-lvar-p dimension))
549          (give-up-ir1-transform))
550         (t
551          (let ((dim (lvar-value dimension)))
552            `(the (integer 0 (,dim)) index)))))
553 \f
554 ;;;; WITH-ARRAY-DATA
555
556 ;;; This checks to see whether the array is simple and the start and
557 ;;; end are in bounds. If so, it proceeds with those values.
558 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
559 ;;; may be further optimized.
560 ;;;
561 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
562 ;;; START-VAR and END-VAR to the start and end of the designated
563 ;;; portion of the data vector. SVALUE and EVALUE are any start and
564 ;;; end specified to the original operation, and are factored into the
565 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
566 ;;; offset of all displacements encountered, and does not include
567 ;;; SVALUE.
568 ;;;
569 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
570 ;;; forced to be inline, overriding the ordinary judgment of the
571 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
572 ;;; fairly picky about their arguments, figuring that if you haven't
573 ;;; bothered to get all your ducks in a row, you probably don't care
574 ;;; that much about speed anyway! But in some cases it makes sense to
575 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
576 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
577 ;;; sense to use FORCE-INLINE option in that case.
578 (def!macro with-array-data (((data-var array &key offset-var)
579                              (start-var &optional (svalue 0))
580                              (end-var &optional (evalue nil))
581                              &key force-inline)
582                             &body forms)
583   (once-only ((n-array array)
584               (n-svalue `(the index ,svalue))
585               (n-evalue `(the (or index null) ,evalue)))
586     `(multiple-value-bind (,data-var
587                            ,start-var
588                            ,end-var
589                            ,@(when offset-var `(,offset-var)))
590          (if (not (array-header-p ,n-array))
591              (let ((,n-array ,n-array))
592                (declare (type (simple-array * (*)) ,n-array))
593                ,(once-only ((n-len `(length ,n-array))
594                             (n-end `(or ,n-evalue ,n-len)))
595                   `(if (<= ,n-svalue ,n-end ,n-len)
596                        ;; success
597                        (values ,n-array ,n-svalue ,n-end 0)
598                        (failed-%with-array-data ,n-array
599                                                 ,n-svalue
600                                                 ,n-evalue))))
601              (,(if force-inline '%with-array-data-macro '%with-array-data)
602               ,n-array ,n-svalue ,n-evalue))
603        ,@forms)))
604
605 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
606 ;;; DEFTRANSFORMs and DEFUNs.
607 (def!macro %with-array-data-macro (array
608                                    start
609                                    end
610                                    &key
611                                    (element-type '*)
612                                    unsafe?
613                                    fail-inline?)
614   (with-unique-names (size defaulted-end data cumulative-offset)
615     `(let* ((,size (array-total-size ,array))
616             (,defaulted-end
617               (cond (,end
618                      (unless (or ,unsafe? (<= ,end ,size))
619                        ,(if fail-inline?
620                             `(error 'bounding-indices-bad-error
621                               :datum (cons ,start ,end)
622                               :expected-type `(cons (integer 0 ,',size)
623                                                     (integer ,',start ,',size))
624                               :object ,array)
625                             `(failed-%with-array-data ,array ,start ,end)))
626                      ,end)
627                     (t ,size))))
628        (unless (or ,unsafe? (<= ,start ,defaulted-end))
629          ,(if fail-inline?
630               `(error 'bounding-indices-bad-error
631                 :datum (cons ,start ,end)
632                 :expected-type `(cons (integer 0 ,',size)
633                                       (integer ,',start ,',size))
634                 :object ,array)
635               `(failed-%with-array-data ,array ,start ,end)))
636        (do ((,data ,array (%array-data-vector ,data))
637             (,cumulative-offset 0
638                                 (+ ,cumulative-offset
639                                    (%array-displacement ,data))))
640            ((not (array-header-p ,data))
641             (values (the (simple-array ,element-type 1) ,data)
642                     (the index (+ ,cumulative-offset ,start))
643                     (the index (+ ,cumulative-offset ,defaulted-end))
644                     (the index ,cumulative-offset)))
645          (declare (type index ,cumulative-offset))))))
646
647 (deftransform %with-array-data ((array start end)
648                                 ;; It might very well be reasonable to
649                                 ;; allow general ARRAY here, I just
650                                 ;; haven't tried to understand the
651                                 ;; performance issues involved. --
652                                 ;; WHN, and also CSR 2002-05-26
653                                 ((or vector simple-array) index (or index null))
654                                 *
655                                 :node node
656                                 :policy (> speed space))
657   "inline non-SIMPLE-vector-handling logic"
658   (let ((element-type (upgraded-element-type-specifier-or-give-up array)))
659     `(%with-array-data-macro array start end
660                              :unsafe? ,(policy node (= safety 0))
661                              :element-type ,element-type)))
662 \f
663 ;;;; array accessors
664
665 ;;; We convert all typed array accessors into AREF and %ASET with type
666 ;;; assertions on the array.
667 (macrolet ((define-bit-frob (reffer setter simplep)
668              `(progn
669                 (define-source-transform ,reffer (a &rest i)
670                   `(aref (the (,',(if simplep 'simple-array 'array)
671                                   bit
672                                   ,(mapcar (constantly '*) i))
673                            ,a) ,@i))
674                 (define-source-transform ,setter (a &rest i)
675                   `(%aset (the (,',(if simplep 'simple-array 'array)
676                                    bit
677                                    ,(cdr (mapcar (constantly '*) i)))
678                             ,a) ,@i)))))
679   (define-bit-frob sbit %sbitset t)
680   (define-bit-frob bit %bitset nil))
681 (macrolet ((define-frob (reffer setter type)
682              `(progn
683                 (define-source-transform ,reffer (a i)
684                   `(aref (the ,',type ,a) ,i))
685                 (define-source-transform ,setter (a i v)
686                   `(%aset (the ,',type ,a) ,i ,v)))))
687   (define-frob svref %svset simple-vector)
688   (define-frob schar %scharset simple-string)
689   (define-frob char %charset string))
690
691 (macrolet (;; This is a handy macro for computing the row-major index
692            ;; given a set of indices. We wrap each index with a call
693            ;; to %CHECK-BOUND to ensure that everything works out
694            ;; correctly. We can wrap all the interior arithmetic with
695            ;; TRULY-THE INDEX because we know the resultant
696            ;; row-major index must be an index.
697            (with-row-major-index ((array indices index &optional new-value)
698                                   &rest body)
699              `(let (n-indices dims)
700                 (dotimes (i (length ,indices))
701                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
702                   (push (make-symbol (format nil "DIM-~D" i)) dims))
703                 (setf n-indices (nreverse n-indices))
704                 (setf dims (nreverse dims))
705                 `(lambda (,',array ,@n-indices
706                                    ,@',(when new-value (list new-value)))
707                    (let* (,@(let ((,index -1))
708                               (mapcar (lambda (name)
709                                         `(,name (array-dimension
710                                                  ,',array
711                                                  ,(incf ,index))))
712                                       dims))
713                             (,',index
714                              ,(if (null dims)
715                                   0
716                                 (do* ((dims dims (cdr dims))
717                                       (indices n-indices (cdr indices))
718                                       (last-dim nil (car dims))
719                                       (form `(%check-bound ,',array
720                                                            ,(car dims)
721                                                            ,(car indices))
722                                             `(truly-the
723                                               index
724                                               (+ (truly-the index
725                                                             (* ,form
726                                                                ,last-dim))
727                                                  (%check-bound
728                                                   ,',array
729                                                   ,(car dims)
730                                                   ,(car indices))))))
731                                     ((null (cdr dims)) form)))))
732                      ,',@body)))))
733
734   ;; Just return the index after computing it.
735   (deftransform array-row-major-index ((array &rest indices))
736     (with-row-major-index (array indices index)
737       index))
738
739   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
740   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
741   ;; expression for the row major index.
742   (deftransform aref ((array &rest indices))
743     (with-row-major-index (array indices index)
744       (hairy-data-vector-ref array index)))
745   (deftransform %aset ((array &rest stuff))
746     (let ((indices (butlast stuff)))
747       (with-row-major-index (array indices index new-value)
748         (hairy-data-vector-set array index new-value)))))
749
750 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
751 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
752 ;;; array total size.
753 (deftransform row-major-aref ((array index))
754   `(hairy-data-vector-ref array
755                           (%check-bound array (array-total-size array) index)))
756 (deftransform %set-row-major-aref ((array index new-value))
757   `(hairy-data-vector-set array
758                           (%check-bound array (array-total-size array) index)
759                           new-value))
760 \f
761 ;;;; bit-vector array operation canonicalization
762 ;;;;
763 ;;;; We convert all bit-vector operations to have the result array
764 ;;;; specified. This allows any result allocation to be open-coded,
765 ;;;; and eliminates the need for any VM-dependent transforms to handle
766 ;;;; these cases.
767
768 (macrolet ((def (fun)
769              `(progn
770                (deftransform ,fun ((bit-array-1 bit-array-2
771                                                 &optional result-bit-array)
772                                    (bit-vector bit-vector &optional null) *
773                                    :policy (>= speed space))
774                  `(,',fun bit-array-1 bit-array-2
775                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
776                ;; If result is T, make it the first arg.
777                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
778                                    (bit-vector bit-vector (eql t)) *)
779                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
780   (def bit-and)
781   (def bit-ior)
782   (def bit-xor)
783   (def bit-eqv)
784   (def bit-nand)
785   (def bit-nor)
786   (def bit-andc1)
787   (def bit-andc2)
788   (def bit-orc1)
789   (def bit-orc2))
790
791 ;;; Similar for BIT-NOT, but there is only one arg...
792 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
793                        (bit-vector &optional null) *
794                        :policy (>= speed space))
795   '(bit-not bit-array-1
796             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
797 (deftransform bit-not ((bit-array-1 result-bit-array)
798                        (bit-vector (eql t)))
799   '(bit-not bit-array-1 bit-array-1))
800 \f
801 ;;; Pick off some constant cases.
802 (defoptimizer (array-header-p derive-type) ((array))
803   (let ((type (lvar-type array)))
804     (cond ((not (array-type-p type))
805            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
806            nil)
807           (t
808            (let ((dims (array-type-dimensions type)))
809              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
810                     ;; no array header
811                     (specifier-type 'null))
812                    ((and (listp dims) (/= (length dims) 1))
813                     ;; multi-dimensional array, will have a header
814                     (specifier-type '(eql t)))
815                    ((eql (array-type-complexp type) t)
816                     (specifier-type '(eql t)))
817                    (t
818                     nil)))))))