8c493b121cda7ab07f524f541f6ddd04184b4c3d
[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 ((call `(funcall ,fn . ,(args-to-fn)))
30             (endtest `(or ,@(tests))))
31         (ecase accumulate
32           (:nconc
33            (let ((temp (gensym))
34                  (map-result (gensym)))
35              `(let ((,map-result (list nil)))
36                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
37                               (,endtest (cdr ,map-result))
38                   (setq ,temp (last (nconc ,temp ,call)))))))
39           (:list
40            (let ((temp (gensym))
41                  (map-result (gensym)))
42              `(let ((,map-result (list nil)))
43                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
44                               (,endtest (cdr ,map-result))
45                   (rplacd ,temp (setq ,temp (list ,call)))))))
46           ((nil)
47            `(let ((,n-first ,(first arglists)))
48               (do-anonymous ,(do-clauses)
49                             (,endtest ,n-first) ,call))))))))
50
51 (def-source-transform mapc (function list &rest more-lists)
52   (mapfoo-transform function (cons list more-lists) nil t))
53
54 (def-source-transform mapcar (function list &rest more-lists)
55   (mapfoo-transform function (cons list more-lists) :list t))
56
57 (def-source-transform mapcan (function list &rest more-lists)
58   (mapfoo-transform function (cons list more-lists) :nconc t))
59
60 (def-source-transform mapl (function list &rest more-lists)
61   (mapfoo-transform function (cons list more-lists) nil nil))
62
63 (def-source-transform maplist (function list &rest more-lists)
64   (mapfoo-transform function (cons list more-lists) :list nil))
65
66 (def-source-transform mapcon (function list &rest more-lists)
67   (mapfoo-transform function (cons list more-lists) :nconc nil))
68 \f
69 ;;;; mapping onto sequences: the MAP function
70
71 ;;; MAP is %MAP plus a check to make sure that any length specified in
72 ;;; the result type matches the actual result. We also wrap it in a
73 ;;; TRULY-THE for the most specific type we can determine.
74 (deftransform map ((result-type-arg fun &rest seqs) * * :node node)
75   (let* ((seq-names (make-gensym-list (length seqs)))
76          (bare `(%map result-type-arg fun ,@seq-names))
77          (constant-result-type-arg-p (constant-continuation-p result-type-arg))
78          ;; what we know about the type of the result. (Note that the
79          ;; "result type" argument is not necessarily the type of the
80          ;; result, since NIL means the result has NULL type.)
81          (result-type (if (not constant-result-type-arg-p)
82                           'consed-sequence
83                           (let ((result-type-arg-value
84                                  (continuation-value result-type-arg)))
85                             (if (null result-type-arg-value)
86                                 'null
87                                 result-type-arg-value)))))
88     `(lambda (result-type-arg fun ,@seq-names)
89        (truly-the ,result-type
90          ,(cond ((policy node (> speed safety))
91                  bare)
92                 ((not constant-result-type-arg-p)
93                  `(sequence-of-checked-length-given-type ,bare
94                                                          result-type-arg))
95                 (t
96                  (let ((result-ctype (specifier-type result-type)))
97                    (if (array-type-p result-ctype)
98                        (let* ((dims (array-type-dimensions result-ctype))
99                               (dim (first dims)))
100                          (if (eq dim '*)
101                              bare
102                              `(vector-of-checked-length-given-length ,bare
103                                                                      ,dim)))
104                        bare))))))))
105
106 ;;; Try to compile %MAP efficiently when we can determine sequence
107 ;;; argument types at compile time.
108 ;;;
109 ;;; Note: This transform was written to allow open coding of
110 ;;; quantifiers by expressing them in terms of (MAP NIL ..). For
111 ;;; non-NIL values of RESULT-TYPE, it's still useful, but not
112 ;;; necessarily as efficient as possible. In particular, it will be
113 ;;; inefficient when RESULT-TYPE is a SIMPLE-ARRAY with specialized
114 ;;; numeric element types. It should be straightforward to make it
115 ;;; handle that case more efficiently, but it's left as an exercise to
116 ;;; the reader, because the code is complicated enough already and I
117 ;;; don't happen to need that functionality right now. -- WHN 20000410
118 (deftransform %map ((result-type fun &rest seqs) * * :policy (>= speed space))
119   "open code"
120   (unless seqs (abort-ir1-transform "no sequence args"))
121   (unless (constant-continuation-p result-type)
122     (give-up-ir1-transform "RESULT-TYPE argument not constant"))
123   (labels (;; 1-valued SUBTYPEP, fails unless second value of SUBTYPEP is true
124            (fn-1subtypep (fn x y)
125              (multiple-value-bind (subtype-p valid-p) (funcall fn x y)
126                (if valid-p
127                    subtype-p
128                    (give-up-ir1-transform
129                     "can't analyze sequence type relationship"))))
130            (1subtypep (x y) (fn-1subtypep #'sb!xc:subtypep x y))
131            (1csubtypep (x y) (fn-1subtypep #'csubtypep x y))
132            (seq-supertype (seq)
133              (let ((ctype (continuation-type seq)))
134                (cond ((1csubtypep ctype (specifier-type 'vector)) 'vector)
135                      ((1csubtypep ctype (specifier-type 'list)) 'list)
136                      (t
137                       (give-up-ir1-transform
138                        "can't determine sequence argument type"))))))
139     (let* ((result-type-value (continuation-value result-type))
140            (result-supertype (cond ((null result-type-value) 'null)
141                                    ((1subtypep result-type-value 'vector)
142                                     'vector)
143                                    ((1subtypep result-type-value 'list)
144                                     'list)
145                                    (t
146                                     (give-up-ir1-transform
147                                      "can't determine result type"))))
148            (seq-supertypes (mapcar #'seq-supertype seqs)))
149       (cond ((and result-type-value (= 1 (length seqs)))
150              ;; The consing arity-1 cases can be implemented
151              ;; reasonably efficiently as function calls, and the cost
152              ;; of consing should be significantly larger than
153              ;; function call overhead, so we always compile these
154              ;; cases as full calls regardless of speed-versus-space
155              ;; optimization policy.
156              (cond ((subtypep 'list result-type-value)
157                     '(apply #'%map-to-list-arity-1 fun seqs))
158                    (;; (This one can be inefficient due to COERCE, but
159                     ;; the current open-coded implementation has the
160                     ;; same problem.)
161                     (subtypep result-type-value 'vector)
162                     `(coerce (apply #'%map-to-simple-vector-arity-1 fun seqs)
163                              ',result-type-value))
164                    (t (give-up-ir1-transform
165                        "internal error: unexpected sequence type"))))
166             (t
167              (let* ((seq-args (make-gensym-list (length seqs)))
168                     (index-bindingoids
169                      (mapcar (lambda (seq-arg seq-supertype)
170                                (let ((i (gensym "I"))) 
171                                  (ecase seq-supertype
172                                    (vector `(,i 0 (1+ ,i)))
173                                    (list `(,i ,seq-arg (rest ,i))))))
174                              seq-args seq-supertypes))
175                     (indices (mapcar #'first index-bindingoids))
176                     (index-decls (mapcar (lambda (index seq-supertype)
177                                            `(type ,(ecase seq-supertype
178                                                      (vector 'index)
179                                                      (list 'list))
180                                                   ,index))
181                                          indices seq-supertypes))
182                     (tests (mapcar (lambda (seq-arg seq-supertype index)
183                                      (ecase seq-supertype
184                                        (vector `(>= ,index (length ,seq-arg)))
185                                        (list `(endp ,index))))
186                                    seq-args seq-supertypes indices))
187                     (values (mapcar (lambda (seq-arg seq-supertype index)
188                                       (ecase seq-supertype
189                                         (vector `(aref ,seq-arg ,index))
190                                         (list `(first ,index))))
191                                     seq-args seq-supertypes indices)))
192                (multiple-value-bind (push-dacc final-result)
193                    (ecase result-supertype
194                      (null (values nil nil))
195                      (list (values `(push dacc acc) `(nreverse acc)))
196                      (vector (values `(push dacc acc)
197                                      `(coerce (nreverse acc)
198                                               ',result-type-value))))
199                  ;; (We use the same idiom, of returning a LAMBDA from
200                  ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
201                  ;; FUNCALL and ALIEN-FUNCALL, and for the same
202                  ;; reason: we need to get the runtime values of each
203                  ;; of the &REST vars.)
204                  `(lambda (result-type fun ,@seq-args)
205                     (declare (ignore result-type))
206                     (do ((really-fun (%coerce-callable-to-function fun))
207                          ,@index-bindingoids
208                          (acc nil))
209                     ((or ,@tests)
210                      ,final-result)
211                     (declare ,@index-decls)
212                     (declare (type list acc))
213                     (declare (ignorable acc))
214                     (let ((dacc (funcall really-fun ,@values)))
215                       (declare (ignorable dacc))
216                       ,push-dacc))))))))))
217 \f
218 (deftransform elt ((s i) ((simple-array * (*)) *) * :when :both)
219   '(aref s i))
220
221 (deftransform elt ((s i) (list *) * :when :both)
222   '(nth i s))
223
224 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) * :when :both)
225   '(%aset s i v))
226
227 (deftransform %setelt ((s i v) (list * *))
228   '(setf (car (nthcdr i s)) v))
229
230 ;;; FIXME: I still think (DOLIST (..) (DEFTRANSFORM ..)) is weird.
231 ;;; For that matter, it would be nice to use DEF-FROB for these
232 ;;; sorts of things, so folks looking for the definitions of
233 ;;; FOO can search for '\(def.*\<foo\>' and have a chance in hell..
234 (dolist (name '(member memq))
235   (deftransform name ((e l &key (test #'eql)) '* '* :node node :when :both
236                       :eval-name t)
237     (unless (constant-continuation-p l)
238       (give-up-ir1-transform))
239
240     (let ((val (continuation-value l)))
241       (unless (policy node
242                       (or (= speed 3)
243                           (and (>= speed space)
244                                (<= (length val) 5))))
245         (give-up-ir1-transform))
246
247       (labels ((frob (els)
248                  (if els
249                      `(if (funcall test e ',(car els))
250                           ',els
251                           ,(frob (cdr els)))
252                      'nil)))
253         (frob val)))))
254
255 ;;; FIXME: Rewrite this so that these definitions of DELETE, ASSOC, and MEMBER
256 ;;; are lexically findable:
257 ;;; (MACROLET ((DEF-FROB (X Y) ..))
258 ;;;   (DEF-FROB DELETE DELQ)
259 ;;;   (DEF-FROB ASSOC ASSQ)
260 ;;;   (DEF-FROB MEMBER MEMQ))
261 ;;; And while I'm at it, I could save a few byte by implementing the
262 ;;; transform body as call to a shared function instead of duplicated
263 ;;; macroexpanded code.
264 (dolist (x '((delete delq)
265              (assoc assq)
266              (member memq)))
267   (destructuring-bind (fun eq-fun) x
268     (deftransform fun ((item list &key test) '(t list &rest t) '*
269                         :eval-name t)
270       "convert to EQ test"
271       ;; FIXME: The scope of this transformation could be widened somewhat,
272       ;; letting it work whenever the test is 'EQL and we know from the
273       ;; type of ITEM that it #'EQ works like #'EQL on it. (E.g. types
274       ;; FIXNUM, CHARACTER, and SYMBOL.)
275       ;;   If TEST is EQ, apply transform, else
276       ;;   if test is not EQL, then give up on transform, else
277       ;;   if ITEM is not a NUMBER or is a FIXNUM, apply transform, else
278       ;;   give up on transform.
279       (cond (test
280              (unless (continuation-function-is test '(eq))
281                (give-up-ir1-transform)))
282             ((types-intersect (continuation-type item)
283                               (specifier-type 'number))
284              (give-up-ir1-transform "Item might be a number.")))
285       `(,eq-fun item list))))
286
287 (deftransform delete-if ((pred list) (t list))
288   "open code"
289   '(do ((x list (cdr x))
290         (splice '()))
291        ((endp x) list)
292      (cond ((funcall pred (car x))
293             (if (null splice)
294                 (setq list (cdr x))
295                 (rplacd splice (cdr x))))
296            (T (setq splice x)))))
297
298 (deftransform fill ((seq item &key (start 0) (end (length seq)))
299                     (simple-array t &key (:start t) (:end index)))
300   "open code"
301   '(do ((i start (1+ i)))
302        ((= i end) seq)
303      (declare (type index i))
304      (setf (aref seq i) item)))
305
306 (deftransform position ((item list &key (test #'eql)) (t list))
307   "open code"
308   '(do ((i 0 (1+ i))
309         (l list (cdr l)))
310        ((endp l) nil)
311      (declare (type index i))
312      (when (funcall test item (car l)) (return i))))
313
314 (deftransform position ((item vec &key (test #'eql) (start 0)
315                               (end (length vec)))
316                         (t simple-array &key (:start t) (:end index)))
317   "open code"
318   '(do ((i start (1+ i)))
319        ((= i end) nil)
320      (declare (type index i))
321      (when (funcall test item (aref vec i)) (return i))))
322
323 ;;; names of predicates that compute the same value as CHAR= when
324 ;;; applied to characters
325 (defconstant char=-functions '(eql equal char=))
326
327 (deftransform search ((string1 string2 &key (start1 0) end1 (start2 0) end2
328                                test)
329                       (simple-string simple-string &rest t))
330   (unless (or (not test)
331               (continuation-function-is test char=-functions))
332     (give-up-ir1-transform))
333   '(sb!impl::%sp-string-search string1 start1 (or end1 (length string1))
334                                string2 start2 (or end2 (length string2))))
335
336 (deftransform position ((item sequence &key from-end test (start 0) end)
337                         (t simple-string &rest t))
338   (unless (or (not test)
339               (continuation-function-is test char=-functions))
340     (give-up-ir1-transform))
341   `(and (typep item 'character)
342         (,(if (constant-value-or-lose from-end)
343               'sb!impl::%sp-reverse-find-character
344               'sb!impl::%sp-find-character)
345          sequence start (or end (length sequence))
346          item)))
347
348 (deftransform find ((item sequence &key from-end (test #'eql) (start 0) end)
349                     (t simple-string &rest t))
350   `(if (position item sequence
351                  ,@(when from-end `(:from-end from-end))
352                  :test test :start start :end end)
353        item
354        nil))
355 \f
356 ;;;; utilities
357
358 ;;; Return true if Cont's only use is a non-notinline reference to a global
359 ;;; function with one of the specified Names.
360 (defun continuation-function-is (cont names)
361   (declare (type continuation cont) (list names))
362   (let ((use (continuation-use cont)))
363     (and (ref-p use)
364          (let ((leaf (ref-leaf use)))
365            (and (global-var-p leaf)
366                 (eq (global-var-kind leaf) :global-function)
367                 (not (null (member (leaf-name leaf) names :test #'equal))))))))
368
369 ;;; If Cont is a constant continuation, the return the constant value. If
370 ;;; it is null, then return default, otherwise quietly GIVE-UP.
371 ;;; ### Probably should take an ARG and flame using the NAME.
372 (defun constant-value-or-lose (cont &optional default)
373   (declare (type (or continuation null) cont))
374   (cond ((not cont) default)
375         ((constant-continuation-p cont)
376          (continuation-value cont))
377         (t
378          (give-up-ir1-transform))))
379
380 #|
381 ;;; This is a frob whose job it is to make it easier to pass around the
382 ;;; arguments to IR1 transforms. It bundles together the name of the argument
383 ;;; (which should be referenced in any expansion), and the continuation for
384 ;;; that argument (or NIL if unsupplied.)
385 (defstruct (arg (:constructor %make-arg (name cont)))
386   (name nil :type symbol)
387   (cont nil :type (or continuation null)))
388 (defmacro make-arg (name)
389   `(%make-arg ',name ,name))
390
391 ;;; If Arg is null or its CONT is null, then return Default, otherwise
392 ;;; return Arg's NAME.
393 (defun default-arg (arg default)
394   (declare (type (or arg null) arg))
395   (if (and arg (arg-cont arg))
396       (arg-name arg)
397       default))
398
399 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
400 ;;; CONT must be a constant continuation whose value we return. If not, we
401 ;;; give up.
402 (defun arg-constant-value (arg default)
403   (declare (type (or arg null) arg))
404   (if (and arg (arg-cont arg))
405       (let ((cont (arg-cont arg)))
406         (unless (constant-continuation-p cont)
407           (give-up-ir1-transform "Argument is not constant: ~S."
408                                  (arg-name arg)))
409         (continuation-value from-end))
410       default))
411
412 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
413 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
414 (defun arg-eql (arg default x)
415   (declare (type (or arg null) x))
416   (if (and arg (arg-cont arg))
417       (let ((cont (arg-cont arg)))
418         (and (constant-continuation-p cont)
419              (eql (continuation-value cont) x)))
420       (eql default x)))
421
422 (defstruct iterator
423   ;; The kind of iterator.
424   (kind nil (member :normal :result))
425   ;; A list of LET* bindings to create the initial state.
426   (binds nil :type list)
427   ;; A list of declarations for Binds.
428   (decls nil :type list)
429   ;; A form that returns the current value. This may be set with SETF to set
430   ;; the current value.
431   (current (error "Must specify CURRENT."))
432   ;; In a :Normal iterator, a form that tests whether there is a current value.
433   (done nil)
434   ;; In a :Result iterator, a form that truncates the result at the current
435   ;; position and returns it.
436   (result nil)
437   ;; A form that returns the initial total number of values. The result is
438   ;; undefined after NEXT has been evaluated.
439   (length (error "Must specify LENGTH."))
440   ;; A form that advances the state to the next value. It is an error to call
441   ;; this when the iterator is Done.
442   (next (error "Must specify NEXT.")))
443
444 ;;; Type of an index var that can go negative (in the from-end case.)
445 (deftype neg-index ()
446   `(integer -1 ,most-positive-fixnum))
447
448 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
449 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
450 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
451 ;;; the index of the current element in the sequence.
452 ;;;
453 ;;; If we can't tell whether the sequence is a list or a vector, or whether
454 ;;; the iteration is forward or backward, then GIVE-UP.
455 (defun make-sequence-iterator (sequence type &key start end from-end index)
456   (declare (symbol sequence) (type ctype type)
457            (type (or arg null) start end from-end)
458            (type (or symbol null) index))
459   (let ((from-end (arg-constant-value from-end nil)))
460     (cond ((csubtypep type (specifier-type 'vector))
461            (let* ((n-stop (gensym))
462                   (n-idx (or index (gensym)))
463                   (start (default-arg 0 start))
464                   (end (default-arg `(length ,sequence) end)))
465              (make-iterator
466               :kind :normal
467               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
468                        (,n-stop ,(if from-end `(1- ,start) ,end)))
469               :decls `((type neg-index ,n-idx ,n-stop))
470               :current `(aref ,sequence ,n-idx)
471               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
472               :next `(setq ,n-idx
473                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
474               :length (if from-end
475                           `(- ,n-idx ,n-stop)
476                           `(- ,n-stop ,n-idx)))))
477           ((csubtypep type (specifier-type 'list))
478            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
479                   (n-current (gensym))
480                   (start-p (not (arg-eql start 0 0)))
481                   (end-p (not (arg-eql end nil nil)))
482                   (start (default-arg start 0))
483                   (end (default-arg end nil)))
484              (make-iterator
485               :binds `((,n-current
486                         ,(if from-end
487                              (if (or start-p end-p)
488                                  `(nreverse (subseq ,sequence ,start
489                                                     ,@(when end `(,end))))
490                                  `(reverse ,sequence))
491                              (if start-p
492                                  `(nthcdr ,start ,sequence)
493                                  sequence)))
494                        ,@(when n-stop
495                            `((,n-stop (nthcdr (the index
496                                                    (- ,end ,start))
497                                               ,n-current))))
498                        ,@(when index
499                            `((,index ,(if from-end `(1- ,end) start)))))
500               :kind :normal
501               :decls `((list ,n-current ,n-end)
502                        ,@(when index `((type neg-index ,index))))
503               :current `(car ,n-current)
504               :done `(eq ,n-current ,n-stop)
505               :length `(- ,(or end `(length ,sequence)) ,start)
506               :next `(progn
507                        (setq ,n-current (cdr ,n-current))
508                        ,@(when index
509                            `((setq ,n-idx
510                                    ,(if from-end
511                                         `(1- ,index)
512                                         `(1+ ,index)))))))))
513           (t
514            (give-up-ir1-transform
515             "can't tell whether sequence is a list or a vector")))))
516
517 ;;; Make an iterator used for constructing result sequences. Name is a
518 ;;; variable to be bound to the result sequence. Type is the type of result
519 ;;; sequence to make. Length is an expression to be evaluated to get the
520 ;;; maximum length of the result (not evaluated in list case.)
521 (defun make-result-sequence-iterator (name type length)
522   (declare (symbol name) (type ctype type))
523
524 ;;; Defines each Name as a local macro that will call the value of the
525 ;;; Fun-Arg with the given arguments. If the argument isn't known to be a
526 ;;; function, give them an efficiency note and reference a coerced version.
527 (defmacro coerce-functions (specs &body body)
528   #!+sb-doc
529   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
530   (collect ((binds)
531             (defs))
532     (dolist (spec specs)
533       `(let ((body (progn ,@body))
534              (n-fun (arg-name ,(second spec)))
535              (fun-cont (arg-cont ,(second spec))))
536          (cond ((not fun-cont)
537                 `(macrolet ((,',(first spec) (&rest args)
538                              `(,',',(third spec) ,@args)))
539                    ,body))
540                ((not (csubtypep (continuation-type fun-cont)
541                                 (specifier-type 'function)))
542                 (when (policy *compiler-error-context* (> speed brevity))
543                   (compiler-note
544                    "~S may not be a function, so must coerce at run-time."
545                    n-fun))
546                 (once-only ((n-fun `(if (functionp ,n-fun)
547                                         ,n-fun
548                                         (symbol-function ,n-fun))))
549                   `(macrolet ((,',(first spec) (&rest args)
550                                `(funcall ,',n-fun ,@args)))
551                      ,body)))
552                (t
553                 `(macrolet ((,',(first spec) (&rest args)
554                               `(funcall ,',n-fun ,@args)))
555                    ,body)))))))
556
557 ;;; Wrap code around the result of the body to define Name as a local macro
558 ;;; that returns true when its arguments satisfy the test according to the Args
559 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
560 ;;; transform.
561 (defmacro with-sequence-test ((name test test-not) &body body)
562   `(let ((not-p (arg-cont ,test-not)))
563      (when (and (arg-cont ,test) not-p)
564        (abort-ir1-transform "Both ~S and ~S were supplied."
565                             (arg-name ,test)
566                             (arg-name ,test-not)))
567      (coerce-functions ((,name (if not-p ,test-not ,test) eql))
568        ,@body)))
569 |#
570 \f
571 ;;;; hairy sequence transforms
572
573 ;;; FIXME: no hairy sequence transforms in SBCL?
574 \f
575 ;;;; string operations
576
577 ;;; We transform the case-sensitive string predicates into a non-keyword
578 ;;; version. This is an IR1 transform so that we don't have to worry about
579 ;;; changing the order of evaluation.
580 (dolist (stuff '((string< string<*)
581                  (string> string>*)
582                  (string<= string<=*)
583                  (string>= string>=*)
584                  (string= string=*)
585                  (string/= string/=*)))
586   (destructuring-bind (fun pred*) stuff
587     (deftransform fun ((string1 string2 &key (start1 0) end1
588                                 (start2 0) end2)
589                        '* '* :eval-name t)
590       `(,pred* string1 string2 start1 end1 start2 end2))))
591
592 ;;; Return a form that tests the free variables STRING1 and STRING2 for the
593 ;;; ordering relationship specified by Lessp and Equalp. The start and end are
594 ;;; also gotten from the environment. Both strings must be simple strings.
595 (dolist (stuff '((string<* t nil)
596                  (string<=* t t)
597                  (string>* nil nil)
598                  (string>=* nil t)))
599   (destructuring-bind (name lessp equalp) stuff
600     (deftransform name ((string1 string2 start1 end1 start2 end2)
601                         '(simple-string simple-string t t t t) '*
602                         :eval-name t)
603       `(let* ((end1 (if (not end1) (length string1) end1))
604               (end2 (if (not end2) (length string2) end2))
605               (index (sb!impl::%sp-string-compare
606                       string1 start1 end1 string2 start2 end2)))
607          (if index
608              (cond ((= index ,(if lessp 'end1 'end2)) index)
609                    ((= index ,(if lessp 'end2 'end1)) nil)
610                    ((,(if lessp 'char< 'char>)
611                      (schar string1 index)
612                      (schar string2
613                             (truly-the index
614                                        (+ index
615                                           (truly-the fixnum
616                                                      (- start2 start1))))))
617                     index)
618                    (t nil))
619              ,(if equalp 'end1 'nil))))))
620
621 (dolist (stuff '((string=* not)
622                  (string/=* identity)))
623   (destructuring-bind (name result-fun) stuff
624     (deftransform name ((string1 string2 start1 end1 start2 end2)
625                         '(simple-string simple-string t t t t) '*
626                         :eval-name t)
627       `(,result-fun
628         (sb!impl::%sp-string-compare
629          string1 start1 (or end1 (length string1))
630          string2 start2 (or end2 (length string2)))))))
631 \f
632 ;;;; string-only transforms for sequence functions
633 ;;;;
634 ;;;; Note: CMU CL had more of these, including transforms for
635 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
636 ;;;; transforms for functions which cons, since our GC overhead is
637 ;;;; sufficiently large that it doesn't seem worth it to try to
638 ;;;; economize on function call overhead or on the overhead of runtime
639 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
640 ;;;; a full call to CONCATENATE would have to look up the sequence
641 ;;;; type, which can be really slow.
642 ;;;;
643 ;;;; FIXME: It would be nicer for these transforms to work for any
644 ;;;; calls when all arguments are vectors with the same element type,
645 ;;;; rather than restricting them to STRINGs only.
646
647 ;;; FIXME: Shouldn't we be testing for legality of
648 ;;;   * START1, START2, END1, and END2 indices?
649 ;;;   * size of copied string relative to destination string?
650 ;;; (Either there should be tests conditional on SAFETY>=SPEED, or
651 ;;; the transform should be conditional on SPEED>SAFETY.)
652 ;;;
653 ;;; FIXME: Also, the transform should probably be dependent on
654 ;;; SPEED>SPACE.
655 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
656                                 end1 end2)
657                        (simple-string simple-string &rest t))
658   `(locally
659      (declare (optimize (safety 0)))
660      (bit-bash-copy string2
661                     (the index
662                          (+ (the index (* start2 sb!vm:byte-bits))
663                             ,vector-data-bit-offset))
664                     string1
665                     (the index
666                          (+ (the index (* start1 sb!vm:byte-bits))
667                             ,vector-data-bit-offset))
668                     (the index
669                          (* (min (the index (- (or end1 (length string1))
670                                                start1))
671                                  (the index (- (or end2 (length string2))
672                                                start2)))
673                             sb!vm:byte-bits)))
674      string1))
675
676 ;;; FIXME: It seems as though it should be possible to make a DEFUN
677 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
678 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
679 ;;; at least once DYNAMIC-EXTENT works.
680 (deftransform concatenate ((rtype &rest sequences)
681                            (t &rest simple-string)
682                            simple-string)
683   (collect ((lets)
684             (forms)
685             (all-lengths)
686             (args))
687     (dolist (seq sequences)
688       (declare (ignore seq))
689       (let ((n-seq (gensym))
690             (n-length (gensym)))
691         (args n-seq)
692         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:byte-bits))))
693         (all-lengths n-length)
694         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
695                                res start
696                                ,n-length))
697         (forms `(setq start (+ start ,n-length)))))
698     `(lambda (rtype ,@(args))
699        (declare (ignore rtype))
700        (let* (,@(lets)
701               (res (make-string (truncate (the index (+ ,@(all-lengths)))
702                                           sb!vm:byte-bits)))
703               (start ,vector-data-bit-offset))
704          (declare (type index start ,@(all-lengths)))
705          ,@(forms)
706          res))))