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