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