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