0.7.12.56:
[sbcl.git] / src / compiler / seqtran.lisp
1 ;;;; optimizers for list and sequence functions
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 ;;;; mapping onto lists: the MAPFOO functions
15
16 (defun mapfoo-transform (fn arglists accumulate take-car)
17   (collect ((do-clauses)
18             (args-to-fn)
19             (tests))
20     (let ((n-first (gensym)))
21       (dolist (a (if accumulate
22                      arglists
23                      `(,n-first ,@(rest arglists))))
24         (let ((v (gensym)))
25           (do-clauses `(,v ,a (cdr ,v)))
26           (tests `(endp ,v))
27           (args-to-fn (if take-car `(car ,v) v))))
28
29       (let* ((fn-sym (gensym))  ; for ONCE-ONLY-ish purposes
30              (call `(funcall ,fn-sym . ,(args-to-fn)))
31              (endtest `(or ,@(tests))))
32         (ecase accumulate
33           (:nconc
34            (let ((temp (gensym))
35                  (map-result (gensym)))
36              `(let ((,fn-sym ,fn)
37                     (,map-result (list nil)))
38                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
39                               (,endtest (cdr ,map-result))
40                   (setq ,temp (last (nconc ,temp ,call)))))))
41           (:list
42            (let ((temp (gensym))
43                  (map-result (gensym)))
44              `(let ((,fn-sym ,fn)
45                     (,map-result (list nil)))
46                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
47                               (,endtest (cdr ,map-result))
48                   (rplacd ,temp (setq ,temp (list ,call)))))))
49           ((nil)
50            `(let ((,fn-sym ,fn)
51                   (,n-first ,(first arglists)))
52               (do-anonymous ,(do-clauses)
53                             (,endtest ,n-first) ,call))))))))
54
55 (define-source-transform mapc (function list &rest more-lists)
56   (mapfoo-transform function (cons list more-lists) nil t))
57
58 (define-source-transform mapcar (function list &rest more-lists)
59   (mapfoo-transform function (cons list more-lists) :list t))
60
61 (define-source-transform mapcan (function list &rest more-lists)
62   (mapfoo-transform function (cons list more-lists) :nconc t))
63
64 (define-source-transform mapl (function list &rest more-lists)
65   (mapfoo-transform function (cons list more-lists) nil nil))
66
67 (define-source-transform maplist (function list &rest more-lists)
68   (mapfoo-transform function (cons list more-lists) :list nil))
69
70 (define-source-transform mapcon (function list &rest more-lists)
71   (mapfoo-transform function (cons list more-lists) :nconc nil))
72 \f
73 ;;;; mapping onto sequences: the MAP function
74
75 ;;; MAP is %MAP plus a check to make sure that any length specified in
76 ;;; the result type matches the actual result. We also wrap it in a
77 ;;; TRULY-THE for the most specific type we can determine.
78 (deftransform map ((result-type-arg fun &rest seqs) * * :node node)
79   (let* ((seq-names (make-gensym-list (length seqs)))
80          (bare `(%map result-type-arg fun ,@seq-names))
81          (constant-result-type-arg-p (constant-continuation-p result-type-arg))
82          ;; what we know about the type of the result. (Note that the
83          ;; "result type" argument is not necessarily the type of the
84          ;; result, since NIL means the result has NULL type.)
85          (result-type (if (not constant-result-type-arg-p)
86                           'consed-sequence
87                           (let ((result-type-arg-value
88                                  (continuation-value result-type-arg)))
89                             (if (null result-type-arg-value)
90                                 'null
91                                 result-type-arg-value)))))
92     `(lambda (result-type-arg fun ,@seq-names)
93        (truly-the ,result-type
94          ,(cond ((policy node (< safety 3))
95                  ;; ANSI requires the length-related type check only
96                  ;; when the SAFETY quality is 3... in other cases, we
97                  ;; skip it, because it could be expensive.
98                  bare)
99                 ((not constant-result-type-arg-p)
100                  `(sequence-of-checked-length-given-type ,bare
101                                                          result-type-arg))
102                 (t
103                  (let ((result-ctype (ir1-transform-specifier-type
104                                       result-type)))
105                    (if (array-type-p result-ctype)
106                        (let ((dims (array-type-dimensions result-ctype)))
107                          (unless (and (listp dims) (= (length dims) 1))
108                            (give-up-ir1-transform "invalid sequence type"))
109                          (let ((dim (first dims)))
110                            (if (eq dim '*)
111                                bare
112                                `(vector-of-checked-length-given-length ,bare
113                                                                        ,dim))))
114                        ;; FIXME: this is wrong, as not all subtypes of
115                        ;; VECTOR are ARRAY-TYPEs [consider, for
116                        ;; example, (OR (VECTOR T 3) (VECTOR T
117                        ;; 4))]. However, it's difficult to see what we
118                        ;; should put here... maybe we should
119                        ;; GIVE-UP-IR1-TRANSFORM if the type is a
120                        ;; subtype of VECTOR but not an ARRAY-TYPE?
121                        bare))))))))
122
123 ;;; Try to compile %MAP efficiently when we can determine sequence
124 ;;; argument types at compile time.
125 ;;;
126 ;;; Note: This transform was written to allow open coding of
127 ;;; quantifiers by expressing them in terms of (MAP NIL ..). For
128 ;;; non-NIL values of RESULT-TYPE, it's still useful, but not
129 ;;; necessarily as efficient as possible. In particular, it will be
130 ;;; inefficient when RESULT-TYPE is a SIMPLE-ARRAY with specialized
131 ;;; numeric element types. It should be straightforward to make it
132 ;;; handle that case more efficiently, but it's left as an exercise to
133 ;;; the reader, because the code is complicated enough already and I
134 ;;; don't happen to need that functionality right now. -- WHN 20000410
135 (deftransform %map ((result-type fun &rest seqs) * * :policy (>= speed space))
136   "open code"
137   (unless seqs (abort-ir1-transform "no sequence args"))
138   (unless (constant-continuation-p result-type)
139     (give-up-ir1-transform "RESULT-TYPE argument not constant"))
140   (labels (;; 1-valued SUBTYPEP, fails unless second value of SUBTYPEP is true
141            (fn-1subtypep (fn x y)
142              (multiple-value-bind (subtype-p valid-p) (funcall fn x y)
143                (if valid-p
144                    subtype-p
145                    (give-up-ir1-transform
146                     "can't analyze sequence type relationship"))))
147            (1subtypep (x y) (fn-1subtypep #'sb!xc:subtypep x y))
148            (1csubtypep (x y) (fn-1subtypep #'csubtypep x y))
149            (seq-supertype (seq)
150              (let ((ctype (continuation-type seq)))
151                (cond ((1csubtypep ctype (specifier-type 'vector)) 'vector)
152                      ((1csubtypep ctype (specifier-type 'list)) 'list)
153                      (t
154                       (give-up-ir1-transform
155                        "can't determine sequence argument type"))))))
156     (let* ((result-type-value (continuation-value result-type))
157            (result-supertype (cond ((null result-type-value) 'null)
158                                    ((1subtypep result-type-value 'vector)
159                                     'vector)
160                                    ((1subtypep result-type-value 'list)
161                                     'list)
162                                    (t
163                                     (give-up-ir1-transform
164                                      "can't determine result type"))))
165            (seq-supertypes (mapcar #'seq-supertype seqs)))
166       (cond ((and result-type-value (= 1 (length seqs)))
167              ;; The consing arity-1 cases can be implemented
168              ;; reasonably efficiently as function calls, and the cost
169              ;; of consing should be significantly larger than
170              ;; function call overhead, so we always compile these
171              ;; cases as full calls regardless of speed-versus-space
172              ;; optimization policy.
173              (cond ((subtypep 'list result-type-value)
174                     '(apply #'%map-to-list-arity-1 fun seqs))
175                    (;; (This one can be inefficient due to COERCE, but
176                     ;; the current open-coded implementation has the
177                     ;; same problem.)
178                     (subtypep result-type-value 'vector)
179                     `(coerce (apply #'%map-to-simple-vector-arity-1 fun seqs)
180                              ',result-type-value))
181                    (t (bug "impossible (?) sequence type"))))
182             (t
183              (let* ((seq-args (make-gensym-list (length seqs)))
184                     (index-bindingoids
185                      (mapcar (lambda (seq-arg seq-supertype)
186                                (let ((i (gensym "I"))) 
187                                  (ecase seq-supertype
188                                    (vector `(,i 0 (1+ ,i)))
189                                    (list `(,i ,seq-arg (rest ,i))))))
190                              seq-args seq-supertypes))
191                     (indices (mapcar #'first index-bindingoids))
192                     (index-decls (mapcar (lambda (index seq-supertype)
193                                            `(type ,(ecase seq-supertype
194                                                      (vector 'index)
195                                                      (list 'list))
196                                                   ,index))
197                                          indices seq-supertypes))
198                     (tests (mapcar (lambda (seq-arg seq-supertype index)
199                                      (ecase seq-supertype
200                                        (vector `(>= ,index (length ,seq-arg)))
201                                        (list `(endp ,index))))
202                                    seq-args seq-supertypes indices))
203                     (values (mapcar (lambda (seq-arg seq-supertype index)
204                                       (ecase seq-supertype
205                                         (vector `(aref ,seq-arg ,index))
206                                         (list `(first ,index))))
207                                     seq-args seq-supertypes indices)))
208                (multiple-value-bind (push-dacc final-result)
209                    (ecase result-supertype
210                      (null (values nil nil))
211                      (list (values `(push dacc acc) `(nreverse acc)))
212                      (vector (values `(push dacc acc)
213                                      `(coerce (nreverse acc)
214                                               ',result-type-value))))
215                  ;; (We use the same idiom, of returning a LAMBDA from
216                  ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
217                  ;; FUNCALL and ALIEN-FUNCALL, and for the same
218                  ;; reason: we need to get the runtime values of each
219                  ;; of the &REST vars.)
220                  `(lambda (result-type fun ,@seq-args)
221                     (declare (ignore result-type))
222                     (do ((really-fun (%coerce-callable-to-fun fun))
223                          ,@index-bindingoids
224                          (acc nil))
225                     ((or ,@tests)
226                      ,final-result)
227                     (declare ,@index-decls)
228                     (declare (type list acc))
229                     (declare (ignorable acc))
230                     (let ((dacc (funcall really-fun ,@values)))
231                       (declare (ignorable dacc))
232                       ,push-dacc))))))))))
233 \f
234 ;;; FIXME: once the confusion over doing transforms with known-complex
235 ;;; arrays is over, we should also transform the calls to (AND (ARRAY
236 ;;; * (*)) (NOT (SIMPLE-ARRAY * (*)))) objects.
237 (deftransform elt ((s i) ((simple-array * (*)) *) *)
238   '(aref s i))
239
240 (deftransform elt ((s i) (list *) * :policy (< safety 3))
241   '(nth i s))
242
243 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) *)
244   '(%aset s i v))
245
246 (deftransform %setelt ((s i v) (list * *) * :policy (< safety 3))
247   '(setf (car (nthcdr i s)) v))
248
249 (deftransform %check-vector-sequence-bounds ((vector start end)
250                                              (vector * *) *
251                                              :node node)
252   (if (policy node (< safety speed))
253       '(or end (length vector))
254       '(let ((length (length vector)))
255         (if (<= 0 start (or end length) length)
256             (or end length)
257             (sb!impl::signal-bounding-indices-bad-error vector start end)))))
258
259 (macrolet ((def (name)
260              `(deftransform ,name ((e l &key (test #'eql)) * *
261                                    :node node)
262                 (unless (constant-continuation-p l)
263                   (give-up-ir1-transform))
264
265                 (let ((val (continuation-value l)))
266                   (unless (policy node
267                                   (or (= speed 3)
268                                       (and (>= speed space)
269                                            (<= (length val) 5))))
270                     (give-up-ir1-transform))
271
272                   (labels ((frob (els)
273                              (if els
274                                  `(if (funcall test e ',(car els))
275                                       ',els
276                                       ,(frob (cdr els)))
277                                  nil)))
278                     (frob val))))))
279   (def member)
280   (def memq))
281
282 ;;; FIXME: We have rewritten the original code that used DOLIST to this
283 ;;; more natural MACROLET.  However, the original code suggested that when
284 ;;; this was done, a few bytes could be saved by a call to a shared
285 ;;; function.  This remains to be done.
286 (macrolet ((def (fun eq-fun)
287              `(deftransform ,fun ((item list &key test) (t list &rest t) *)
288                 "convert to EQ test"
289                 ;; FIXME: The scope of this transformation could be
290                 ;; widened somewhat, letting it work whenever the test is
291                 ;; 'EQL and we know from the type of ITEM that it #'EQ
292                 ;; works like #'EQL on it. (E.g. types FIXNUM, CHARACTER,
293                 ;; and SYMBOL.)
294                 ;;   If TEST is EQ, apply transform, else
295                 ;;   if test is not EQL, then give up on transform, else
296                 ;;   if ITEM is not a NUMBER or is a FIXNUM, apply
297                 ;;   transform, else give up on transform.
298                 (cond (test
299                        (unless (continuation-fun-is test '(eq))
300                          (give-up-ir1-transform)))
301                       ((types-equal-or-intersect (continuation-type item)
302                                                  (specifier-type 'number))
303                        (give-up-ir1-transform "Item might be a number.")))
304                 `(,',eq-fun item list))))
305   (def delete delq)
306   (def assoc assq)
307   (def member memq))
308
309 (deftransform delete-if ((pred list) (t list))
310   "open code"
311   '(do ((x list (cdr x))
312         (splice '()))
313        ((endp x) list)
314      (cond ((funcall pred (car x))
315             (if (null splice)
316                 (setq list (cdr x))
317                 (rplacd splice (cdr x))))
318            (T (setq splice x)))))
319
320 (deftransform fill ((seq item &key (start 0) (end (length seq)))
321                     (vector t &key (:start t) (:end index))
322                     *
323                     :policy (> speed space))
324   "open code"
325   (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
326     (values 
327      `(with-array-data ((data seq)
328                         (start start)
329                         (end end))
330        (declare (type (simple-array ,element-type 1) data))
331        (declare (type fixnum start end))
332        (do ((i start (1+ i)))
333            ((= i end) seq)
334          (declare (type index i))
335          ;; WITH-ARRAY-DATA did our range checks once and for all, so
336          ;; it'd be wasteful to check again on every AREF...
337          (declare (optimize (safety 0))) 
338          (setf (aref data i) item)))
339      ;; ... though we still need to check that the new element can fit
340      ;; into the vector in safe code. -- CSR, 2002-07-05
341      `((declare (type ,element-type item))))))
342 \f
343 ;;;; utilities
344
345 ;;; Return true if CONT's only use is a non-NOTINLINE reference to a
346 ;;; global function with one of the specified NAMES.
347 (defun continuation-fun-is (cont names)
348   (declare (type continuation cont) (list names))
349   (let ((use (continuation-use cont)))
350     (and (ref-p use)
351          (let ((leaf (ref-leaf use)))
352            (and (global-var-p leaf)
353                 (eq (global-var-kind leaf) :global-function)
354                 (not (null (member (leaf-source-name leaf) names
355                                    :test #'equal))))))))
356
357 ;;; If CONT is a constant continuation, the return the constant value.
358 ;;; If it is null, then return default, otherwise quietly give up the
359 ;;; IR1 transform.
360 ;;;
361 ;;; ### Probably should take an ARG and flame using the NAME.
362 (defun constant-value-or-lose (cont &optional default)
363   (declare (type (or continuation null) cont))
364   (cond ((not cont) default)
365         ((constant-continuation-p cont)
366          (continuation-value cont))
367         (t
368          (give-up-ir1-transform))))
369
370 ;;; FIXME: Why is this code commented out? (Why *was* it commented
371 ;;; out? We inherited this situation from cmucl-2.4.8, with no
372 ;;; explanation.) Should we just delete this code?
373 #|
374 ;;; This is a frob whose job it is to make it easier to pass around
375 ;;; the arguments to IR1 transforms. It bundles together the name of
376 ;;; the argument (which should be referenced in any expansion), and
377 ;;; the continuation for that argument (or NIL if unsupplied.)
378 (defstruct (arg (:constructor %make-arg (name cont))
379                 (:copier nil))
380   (name nil :type symbol)
381   (cont nil :type (or continuation null)))
382 (defmacro make-arg (name)
383   `(%make-arg ',name ,name))
384
385 ;;; If Arg is null or its CONT is null, then return Default, otherwise
386 ;;; return Arg's NAME.
387 (defun default-arg (arg default)
388   (declare (type (or arg null) arg))
389   (if (and arg (arg-cont arg))
390       (arg-name arg)
391       default))
392
393 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
394 ;;; CONT must be a constant continuation whose value we return. If not, we
395 ;;; give up.
396 (defun arg-constant-value (arg default)
397   (declare (type (or arg null) arg))
398   (if (and arg (arg-cont arg))
399       (let ((cont (arg-cont arg)))
400         (unless (constant-continuation-p cont)
401           (give-up-ir1-transform "Argument is not constant: ~S."
402                                  (arg-name arg)))
403         (continuation-value from-end))
404       default))
405
406 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
407 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
408 (defun arg-eql (arg default x)
409   (declare (type (or arg null) x))
410   (if (and arg (arg-cont arg))
411       (let ((cont (arg-cont arg)))
412         (and (constant-continuation-p cont)
413              (eql (continuation-value cont) x)))
414       (eql default x)))
415
416 (defstruct (iterator (:copier nil))
417   ;; The kind of iterator.
418   (kind nil (member :normal :result))
419   ;; A list of LET* bindings to create the initial state.
420   (binds nil :type list)
421   ;; A list of declarations for Binds.
422   (decls nil :type list)
423   ;; A form that returns the current value. This may be set with SETF to set
424   ;; the current value.
425   (current (error "Must specify CURRENT."))
426   ;; In a :NORMAL iterator, a form that tests whether there is a current value.
427   (done nil)
428   ;; In a :RESULT iterator, a form that truncates the result at the current
429   ;; position and returns it.
430   (result nil)
431   ;; A form that returns the initial total number of values. The result is
432   ;; undefined after NEXT has been evaluated.
433   (length (error "Must specify LENGTH."))
434   ;; A form that advances the state to the next value. It is an error to call
435   ;; this when the iterator is Done.
436   (next (error "Must specify NEXT.")))
437
438 ;;; Type of an index var that can go negative (in the from-end case.)
439 (deftype neg-index ()
440   `(integer -1 ,most-positive-fixnum))
441
442 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
443 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
444 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
445 ;;; the index of the current element in the sequence.
446 ;;;
447 ;;; If we can't tell whether the sequence is a list or a vector, or whether
448 ;;; the iteration is forward or backward, then GIVE-UP.
449 (defun make-sequence-iterator (sequence type &key start end from-end index)
450   (declare (symbol sequence) (type ctype type)
451            (type (or arg null) start end from-end)
452            (type (or symbol null) index))
453   (let ((from-end (arg-constant-value from-end nil)))
454     (cond ((csubtypep type (specifier-type 'vector))
455            (let* ((n-stop (gensym))
456                   (n-idx (or index (gensym)))
457                   (start (default-arg 0 start))
458                   (end (default-arg `(length ,sequence) end)))
459              (make-iterator
460               :kind :normal
461               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
462                        (,n-stop ,(if from-end `(1- ,start) ,end)))
463               :decls `((type neg-index ,n-idx ,n-stop))
464               :current `(aref ,sequence ,n-idx)
465               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
466               :next `(setq ,n-idx
467                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
468               :length (if from-end
469                           `(- ,n-idx ,n-stop)
470                           `(- ,n-stop ,n-idx)))))
471           ((csubtypep type (specifier-type 'list))
472            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
473                   (n-current (gensym))
474                   (start-p (not (arg-eql start 0 0)))
475                   (end-p (not (arg-eql end nil nil)))
476                   (start (default-arg start 0))
477                   (end (default-arg end nil)))
478              (make-iterator
479               :binds `((,n-current
480                         ,(if from-end
481                              (if (or start-p end-p)
482                                  `(nreverse (subseq ,sequence ,start
483                                                     ,@(when end `(,end))))
484                                  `(reverse ,sequence))
485                              (if start-p
486                                  `(nthcdr ,start ,sequence)
487                                  sequence)))
488                        ,@(when n-stop
489                            `((,n-stop (nthcdr (the index
490                                                    (- ,end ,start))
491                                               ,n-current))))
492                        ,@(when index
493                            `((,index ,(if from-end `(1- ,end) start)))))
494               :kind :normal
495               :decls `((list ,n-current ,n-end)
496                        ,@(when index `((type neg-index ,index))))
497               :current `(car ,n-current)
498               :done `(eq ,n-current ,n-stop)
499               :length `(- ,(or end `(length ,sequence)) ,start)
500               :next `(progn
501                        (setq ,n-current (cdr ,n-current))
502                        ,@(when index
503                            `((setq ,n-idx
504                                    ,(if from-end
505                                         `(1- ,index)
506                                         `(1+ ,index)))))))))
507           (t
508            (give-up-ir1-transform
509             "can't tell whether sequence is a list or a vector")))))
510
511 ;;; Make an iterator used for constructing result sequences. Name is a
512 ;;; variable to be bound to the result sequence. Type is the type of result
513 ;;; sequence to make. Length is an expression to be evaluated to get the
514 ;;; maximum length of the result (not evaluated in list case.)
515 (defun make-result-sequence-iterator (name type length)
516   (declare (symbol name) (type ctype type))
517
518 ;;; Define each NAME as a local macro that will call the value of the
519 ;;; function arg with the given arguments. If the argument isn't known to be a
520 ;;; function, give them an efficiency note and reference a coerced version.
521 (defmacro coerce-funs (specs &body body)
522   #!+sb-doc
523   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
524   (collect ((binds)
525             (defs))
526     (dolist (spec specs)
527       `(let ((body (progn ,@body))
528              (n-fun (arg-name ,(second spec)))
529              (fun-cont (arg-cont ,(second spec))))
530          (cond ((not fun-cont)
531                 `(macrolet ((,',(first spec) (&rest args)
532                              `(,',',(third spec) ,@args)))
533                    ,body))
534                ((not (csubtypep (continuation-type fun-cont)
535                                 (specifier-type 'function)))
536                 (when (policy *compiler-error-context*
537                               (> speed inhibit-warnings))
538                   (compiler-note
539                    "~S may not be a function, so must coerce at run-time."
540                    n-fun))
541                 (once-only ((n-fun `(if (functionp ,n-fun)
542                                         ,n-fun
543                                         (symbol-function ,n-fun))))
544                   `(macrolet ((,',(first spec) (&rest args)
545                                `(funcall ,',n-fun ,@args)))
546                      ,body)))
547                (t
548                 `(macrolet ((,',(first spec) (&rest args)
549                               `(funcall ,',n-fun ,@args)))
550                    ,body)))))))
551
552 ;;; Wrap code around the result of the body to define Name as a local macro
553 ;;; that returns true when its arguments satisfy the test according to the Args
554 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
555 ;;; transform.
556 (defmacro with-sequence-test ((name test test-not) &body body)
557   `(let ((not-p (arg-cont ,test-not)))
558      (when (and (arg-cont ,test) not-p)
559        (abort-ir1-transform "Both ~S and ~S were supplied."
560                             (arg-name ,test)
561                             (arg-name ,test-not)))
562      (coerce-funs ((,name (if not-p ,test-not ,test) eql))
563        ,@body)))
564 |#
565 \f
566 ;;;; hairy sequence transforms
567
568 ;;; FIXME: no hairy sequence transforms in SBCL?
569 \f
570 ;;;; string operations
571
572 ;;; We transform the case-sensitive string predicates into a non-keyword
573 ;;; version. This is an IR1 transform so that we don't have to worry about
574 ;;; changing the order of evaluation.
575 (macrolet ((def (fun pred*)
576              `(deftransform ,fun ((string1 string2 &key (start1 0) end1
577                                                          (start2 0) end2)
578                                    * *)
579                 `(,',pred* string1 string2 start1 end1 start2 end2))))
580   (def string< string<*)
581   (def string> string>*)
582   (def string<= string<=*)
583   (def string>= string>=*)
584   (def string= string=*)
585   (def string/= string/=*))
586
587 ;;; Return a form that tests the free variables STRING1 and STRING2
588 ;;; for the ordering relationship specified by LESSP and EQUALP. The
589 ;;; start and end are also gotten from the environment. Both strings
590 ;;; must be SIMPLE-STRINGs.
591 (macrolet ((def (name lessp equalp)
592              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
593                                     (simple-string simple-string t t t t) *)
594                 `(let* ((end1 (if (not end1) (length string1) end1))
595                         (end2 (if (not end2) (length string2) end2))
596                         (index (sb!impl::%sp-string-compare
597                                 string1 start1 end1 string2 start2 end2)))
598                   (if index
599                       (cond ((= index ,(if ',lessp 'end1 'end2)) index)
600                             ((= index ,(if ',lessp 'end2 'end1)) nil)
601                             ((,(if ',lessp 'char< 'char>)
602                                (schar string1 index)
603                                (schar string2
604                                       (truly-the index
605                                                  (+ index
606                                                     (truly-the fixnum
607                                                                (- start2
608                                                                   start1))))))
609                              index)
610                             (t nil))
611                       ,(if ',equalp 'end1 nil))))))
612   (def string<* t nil)
613   (def string<=* t t)
614   (def string>* nil nil)
615   (def string>=* nil t))
616
617 (macrolet ((def (name result-fun)
618              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
619                                    (simple-string simple-string t t t t) *)
620                 `(,',result-fun
621                   (sb!impl::%sp-string-compare
622                    string1 start1 (or end1 (length string1))
623                    string2 start2 (or end2 (length string2)))))))
624   (def string=* not)
625   (def string/=* identity))
626
627 \f
628 ;;;; string-only transforms for sequence functions
629 ;;;;
630 ;;;; Note: CMU CL had more of these, including transforms for
631 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
632 ;;;; transforms for functions which cons, since our GC overhead is
633 ;;;; sufficiently large that it doesn't seem worth it to try to
634 ;;;; economize on function call overhead or on the overhead of runtime
635 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
636 ;;;; a full call to CONCATENATE would have to look up the sequence
637 ;;;; type, which can be really slow.
638 ;;;;
639 ;;;; FIXME: It would be nicer for these transforms to work for any
640 ;;;; calls when all arguments are vectors with the same element type,
641 ;;;; rather than restricting them to STRINGs only.
642
643 ;;; Moved here from generic/vm-tran.lisp to satisfy clisp
644 ;;;
645 ;;; FIXME: Add a comment telling whether this holds for all vectors
646 ;;; or only for vectors based on simple arrays (non-adjustable, etc.).
647 (def!constant vector-data-bit-offset
648   (* sb!vm:vector-data-offset sb!vm:n-word-bits))
649
650 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
651                                 end1 end2)
652                        (simple-string simple-string &rest t)
653                        *
654                        ;; FIXME: consider replacing this policy test
655                        ;; with some tests for the STARTx and ENDx
656                        ;; indices being valid, conditional on high
657                        ;; SAFETY code.
658                        ;;
659                        ;; FIXME: It turns out that this transform is
660                        ;; critical for the performance of string
661                        ;; streams.  Make this more explicit.
662                        :policy (< (max safety space) 3))
663   `(locally
664      (declare (optimize (safety 0)))
665      (bit-bash-copy string2
666                     (the index
667                          (+ (the index (* start2 sb!vm:n-byte-bits))
668                             ,vector-data-bit-offset))
669                     string1
670                     (the index
671                          (+ (the index (* start1 sb!vm:n-byte-bits))
672                             ,vector-data-bit-offset))
673                     (the index
674                          (* (min (the index (- (or end1 (length string1))
675                                                start1))
676                                  (the index (- (or end2 (length string2))
677                                                start2)))
678                             sb!vm:n-byte-bits)))
679      string1))
680
681 ;;; FIXME: It seems as though it should be possible to make a DEFUN
682 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
683 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
684 ;;; at least once DYNAMIC-EXTENT works.
685 ;;;
686 ;;; FIXME: currently KLUDGEed because of bug 188
687 (deftransform concatenate ((rtype &rest sequences)
688                            (t &rest simple-string)
689                            simple-string
690                            :policy (< safety 3))
691   (collect ((lets)
692             (forms)
693             (all-lengths)
694             (args))
695     (dolist (seq sequences)
696       (declare (ignorable seq))
697       (let ((n-seq (gensym))
698             (n-length (gensym)))
699         (args n-seq)
700         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
701         (all-lengths n-length)
702         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
703                                res start
704                                ,n-length))
705         (forms `(setq start (opaque-identity (+ start ,n-length))))))
706     `(lambda (rtype ,@(args))
707        (declare (ignore rtype))
708        ;; KLUDGE
709        (flet ((opaque-identity (x) x))
710          (declare (notinline opaque-identity))
711          (let* (,@(lets)
712                   (res (make-string (truncate (the index (+ ,@(all-lengths)))
713                                               sb!vm:n-byte-bits)))
714                   (start ,vector-data-bit-offset))
715            (declare (type index start ,@(all-lengths)))
716            ,@(forms)
717            res)))))
718 \f
719 ;;;; CONS accessor DERIVE-TYPE optimizers
720
721 (defoptimizer (car derive-type) ((cons))
722   (let ((type (continuation-type cons))
723         (null-type (specifier-type 'null)))
724     (cond ((eq type null-type)
725            null-type)
726           ((cons-type-p type)
727            (cons-type-car-type type)))))
728
729 (defoptimizer (cdr derive-type) ((cons))
730   (let ((type (continuation-type cons))
731         (null-type (specifier-type 'null)))
732     (cond ((eq type null-type)
733            null-type)
734           ((cons-type-p type)
735            (cons-type-cdr-type type)))))
736 \f
737 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
738
739 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
740 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
741 ;;; expansion, so we factor out the condition into this function.
742 (defun check-inlineability-of-find-position-if (sequence from-end)
743   (let ((ctype (continuation-type sequence)))
744     (cond ((csubtypep ctype (specifier-type 'vector))
745            ;; It's not worth trying to inline vector code unless we
746            ;; know a fair amount about it at compile time.
747            (upgraded-element-type-specifier-or-give-up sequence)
748            (unless (constant-continuation-p from-end)
749              (give-up-ir1-transform
750               "FROM-END argument value not known at compile time")))
751           ((csubtypep ctype (specifier-type 'list))
752            ;; Inlining on lists is generally worthwhile.
753            ) 
754           (t
755            (give-up-ir1-transform
756             "sequence type not known at compile time")))))
757
758 ;;; %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for LIST data
759 (macrolet ((def (name condition)
760              `(deftransform ,name ((predicate sequence from-end start end key)
761                                    (function list t t t function)
762                                    *
763                                    :policy (> speed space)
764                                    :important t)
765                 "expand inline"
766                 `(let ((index 0)
767                        (find nil)
768                        (position nil))
769                    (declare (type index index))
770                    (dolist (i sequence
771                             (if (and end (> end index))
772                                 (sb!impl::signal-bounding-indices-bad-error
773                                  sequence start end)
774                                 (values find position)))
775                      (let ((key-i (funcall key i)))
776                        (when (and end (>= index end))
777                          (return (values find position)))
778                        (when (>= index start)
779                          (,',condition (funcall predicate key-i)
780                           ;; This hack of dealing with non-NIL
781                           ;; FROM-END for list data by iterating
782                           ;; forward through the list and keeping
783                           ;; track of the last time we found a match
784                           ;; might be more screwy than what the user
785                           ;; expects, but it seems to be allowed by
786                           ;; the ANSI standard. (And if the user is
787                           ;; screwy enough to ask for FROM-END
788                           ;; behavior on list data, turnabout is
789                           ;; fair play.)
790                           ;;
791                           ;; It's also not enormously efficient,
792                           ;; calling PREDICATE and KEY more often
793                           ;; than necessary; but all the
794                           ;; alternatives seem to have their own
795                           ;; efficiency problems.
796                           (if from-end
797                               (setf find i
798                                     position index)
799                               (return (values i index))))))
800                      (incf index))))))
801   (def %find-position-if when)
802   (def %find-position-if-not unless))
803                       
804 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
805 ;;; without loss of efficiency. (I.e., the optimizer should be able
806 ;;; to straighten everything out.)
807 (deftransform %find-position ((item sequence from-end start end key test)
808                               (t list t t t t t)
809                               *
810                               :policy (> speed space)
811                               :important t)
812   "expand inline"
813   '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
814                         ;; The order of arguments for asymmetric tests
815                         ;; (e.g. #'<, as opposed to order-independent
816                         ;; tests like #'=) is specified in the spec
817                         ;; section 17.2.1 -- the O/Zi stuff there.
818                         (lambda (i)
819                           (funcall test-fun item i)))
820                       sequence
821                       from-end
822                       start
823                       end
824                       (%coerce-callable-to-fun key)))
825
826 ;;; The inline expansions for the VECTOR case are saved as macros so
827 ;;; that we can share them between the DEFTRANSFORMs and the default
828 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
829 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
830 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
831                                                             from-end
832                                                             start
833                                                             end-arg
834                                                             element
835                                                             done-p-expr)
836   (let ((offset (gensym "OFFSET"))
837         (block (gensym "BLOCK"))
838         (index (gensym "INDEX"))
839         (n-sequence (gensym "N-SEQUENCE-"))
840         (sequence (gensym "SEQUENCE"))
841         (n-end (gensym "N-END-"))
842         (end (gensym "END-")))
843     `(let ((,n-sequence ,sequence-arg)
844            (,n-end ,end-arg))
845        (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
846                          (,start ,start)
847                          (,end (%check-vector-sequence-bounds
848                                 ,n-sequence ,start ,n-end)))
849          (block ,block
850            (macrolet ((maybe-return ()
851                         '(let ((,element (aref ,sequence ,index)))
852                            (when ,done-p-expr
853                              (return-from ,block
854                                (values ,element
855                                        (- ,index ,offset)))))))
856              (if ,from-end
857                  (loop for ,index
858                        ;; (If we aren't fastidious about declaring that 
859                        ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
860                        ;; can send us off into never-never land, since
861                        ;; INDEX is initialized to -1.)
862                        of-type index-or-minus-1
863                        from (1- ,end) downto ,start do
864                        (maybe-return))
865                  (loop for ,index of-type index from ,start below ,end do
866                        (maybe-return))))
867            (values nil nil))))))
868
869 (def!macro %find-position-vector-macro (item sequence
870                                              from-end start end key test)
871   (let ((element (gensym "ELEMENT")))
872     (%find-position-or-find-position-if-vector-expansion
873      sequence
874      from-end
875      start
876      end
877      element
878      ;; (See the LIST transform for a discussion of the correct
879      ;; argument order, i.e. whether the searched-for ,ITEM goes before
880      ;; or after the checked sequence element.)
881      `(funcall ,test ,item (funcall ,key ,element)))))
882
883 (def!macro %find-position-if-vector-macro (predicate sequence
884                                                      from-end start end key)
885   (let ((element (gensym "ELEMENT")))
886     (%find-position-or-find-position-if-vector-expansion
887      sequence
888      from-end
889      start
890      end
891      element
892      `(funcall ,predicate (funcall ,key ,element)))))
893
894 (def!macro %find-position-if-not-vector-macro (predicate sequence
895                                                          from-end start end key)
896   (let ((element (gensym "ELEMENT")))
897     (%find-position-or-find-position-if-vector-expansion
898      sequence
899      from-end
900      start
901      end
902      element
903      `(not (funcall ,predicate (funcall ,key ,element))))))
904
905 ;;; %FIND-POSITION, %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for
906 ;;; VECTOR data
907 (deftransform %find-position-if ((predicate sequence from-end start end key)
908                                  (function vector t t t function)
909                                  *
910                                  :policy (> speed space)
911                                  :important t)
912   "expand inline"
913   (check-inlineability-of-find-position-if sequence from-end)
914   '(%find-position-if-vector-macro predicate sequence
915                                    from-end start end key))
916
917 (deftransform %find-position-if-not ((predicate sequence from-end start end key)
918                                      (function vector t t t function)
919                                      *
920                                      :policy (> speed space)
921                                      :important t)
922   "expand inline"
923   (check-inlineability-of-find-position-if sequence from-end)
924   '(%find-position-if-not-vector-macro predicate sequence
925                                        from-end start end key))
926
927 (deftransform %find-position ((item sequence from-end start end key test)
928                               (t vector t t t function function)
929                               *
930                               :policy (> speed space)
931                               :important t)
932   "expand inline"
933   (check-inlineability-of-find-position-if sequence from-end)
934   '(%find-position-vector-macro item sequence
935                                 from-end start end key test))
936
937 ;;; logic to unravel :TEST, :TEST-NOT, and :KEY options in FIND,
938 ;;; POSITION-IF, etc.
939 (define-source-transform effective-find-position-test (test test-not)
940   (once-only ((test test)
941               (test-not test-not))
942     `(cond
943       ((and ,test ,test-not)
944        (error "can't specify both :TEST and :TEST-NOT"))
945       (,test (%coerce-callable-to-fun ,test))
946       (,test-not
947        ;; (Without DYNAMIC-EXTENT, this is potentially horribly
948        ;; inefficient, but since the TEST-NOT option is deprecated
949        ;; anyway, we don't care.)
950        (complement (%coerce-callable-to-fun ,test-not)))
951       (t #'eql))))
952 (define-source-transform effective-find-position-key (key)
953   (once-only ((key key))
954     `(if ,key
955          (%coerce-callable-to-fun ,key)
956          #'identity)))
957
958 (macrolet ((define-find-position (fun-name values-index)
959              `(deftransform ,fun-name ((item sequence &key
960                                              from-end (start 0) end
961                                              key test test-not))
962                 '(nth-value ,values-index
963                             (%find-position item sequence
964                                             from-end start
965                                             end
966                                             (effective-find-position-key key)
967                                             (effective-find-position-test
968                                              test test-not))))))
969   (define-find-position find 0)
970   (define-find-position position 1))
971
972 (macrolet ((define-find-position-if (fun-name values-index)
973              `(deftransform ,fun-name ((predicate sequence &key
974                                                   from-end (start 0)
975                                                   end key))
976                 '(nth-value
977                   ,values-index
978                   (%find-position-if (%coerce-callable-to-fun predicate)
979                                      sequence from-end
980                                      start end
981                                      (effective-find-position-key key))))))
982   (define-find-position-if find-if 0)
983   (define-find-position-if position-if 1))
984
985 ;;; the deprecated functions FIND-IF-NOT and POSITION-IF-NOT. We
986 ;;; didn't bother to worry about optimizing them, except note that on
987 ;;; Sat, Oct 06, 2001 at 04:22:38PM +0100, Christophe Rhodes wrote on
988 ;;; sbcl-devel
989 ;;;
990 ;;;     My understanding is that while the :test-not argument is
991 ;;;     deprecated in favour of :test (complement #'foo) because of
992 ;;;     semantic difficulties (what happens if both :test and :test-not
993 ;;;     are supplied, etc) the -if-not variants, while officially
994 ;;;     deprecated, would be undeprecated were X3J13 actually to produce
995 ;;;     a revised standard, as there are perfectly legitimate idiomatic
996 ;;;     reasons for allowing the -if-not versions equal status,
997 ;;;     particularly remove-if-not (== filter).
998 ;;;
999 ;;;     This is only an informal understanding, I grant you, but
1000 ;;;     perhaps it's worth optimizing the -if-not versions in the same
1001 ;;;     way as the others?
1002 ;;;
1003 ;;; FIXME: Maybe remove uses of these deprecated functions (and
1004 ;;; definitely of :TEST-NOT) within the implementation of SBCL.
1005 (macrolet ((define-find-position-if-not (fun-name values-index)
1006                `(deftransform ,fun-name ((predicate sequence &key
1007                                           from-end (start 0)
1008                                           end key))
1009                  '(nth-value
1010                    ,values-index
1011                    (%find-position-if-not (%coerce-callable-to-fun predicate)
1012                     sequence from-end
1013                     start end
1014                     (effective-find-position-key key))))))
1015   (define-find-position-if-not find-if-not 0)
1016   (define-find-position-if-not position-if-not 1))