0.7.7.33:
[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 (define-source-transform mapc (function list &rest more-lists)
52   (mapfoo-transform function (cons list more-lists) nil t))
53
54 (define-source-transform mapcar (function list &rest more-lists)
55   (mapfoo-transform function (cons list more-lists) :list t))
56
57 (define-source-transform mapcan (function list &rest more-lists)
58   (mapfoo-transform function (cons list more-lists) :nconc t))
59
60 (define-source-transform mapl (function list &rest more-lists)
61   (mapfoo-transform function (cons list more-lists) nil nil))
62
63 (define-source-transform maplist (function list &rest more-lists)
64   (mapfoo-transform function (cons list more-lists) :list nil))
65
66 (define-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 (bug "impossible (?) sequence type"))))
165             (t
166              (let* ((seq-args (make-gensym-list (length seqs)))
167                     (index-bindingoids
168                      (mapcar (lambda (seq-arg seq-supertype)
169                                (let ((i (gensym "I"))) 
170                                  (ecase seq-supertype
171                                    (vector `(,i 0 (1+ ,i)))
172                                    (list `(,i ,seq-arg (rest ,i))))))
173                              seq-args seq-supertypes))
174                     (indices (mapcar #'first index-bindingoids))
175                     (index-decls (mapcar (lambda (index seq-supertype)
176                                            `(type ,(ecase seq-supertype
177                                                      (vector 'index)
178                                                      (list 'list))
179                                                   ,index))
180                                          indices seq-supertypes))
181                     (tests (mapcar (lambda (seq-arg seq-supertype index)
182                                      (ecase seq-supertype
183                                        (vector `(>= ,index (length ,seq-arg)))
184                                        (list `(endp ,index))))
185                                    seq-args seq-supertypes indices))
186                     (values (mapcar (lambda (seq-arg seq-supertype index)
187                                       (ecase seq-supertype
188                                         (vector `(aref ,seq-arg ,index))
189                                         (list `(first ,index))))
190                                     seq-args seq-supertypes indices)))
191                (multiple-value-bind (push-dacc final-result)
192                    (ecase result-supertype
193                      (null (values nil nil))
194                      (list (values `(push dacc acc) `(nreverse acc)))
195                      (vector (values `(push dacc acc)
196                                      `(coerce (nreverse acc)
197                                               ',result-type-value))))
198                  ;; (We use the same idiom, of returning a LAMBDA from
199                  ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
200                  ;; FUNCALL and ALIEN-FUNCALL, and for the same
201                  ;; reason: we need to get the runtime values of each
202                  ;; of the &REST vars.)
203                  `(lambda (result-type fun ,@seq-args)
204                     (declare (ignore result-type))
205                     (do ((really-fun (%coerce-callable-to-fun fun))
206                          ,@index-bindingoids
207                          (acc nil))
208                     ((or ,@tests)
209                      ,final-result)
210                     (declare ,@index-decls)
211                     (declare (type list acc))
212                     (declare (ignorable acc))
213                     (let ((dacc (funcall really-fun ,@values)))
214                       (declare (ignorable dacc))
215                       ,push-dacc))))))))))
216 \f
217 (deftransform elt ((s i) ((simple-array * (*)) *) *)
218   '(aref s i))
219
220 (deftransform elt ((s i) (list *) *)
221   '(nth i s))
222
223 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) *)
224   '(%aset s i v))
225
226 (deftransform %setelt ((s i v) (list * *))
227   '(setf (car (nthcdr i s)) v))
228
229 (macrolet ((def (name)
230              `(deftransform ,name ((e l &key (test #'eql)) * *
231                                    :node node)
232                 (unless (constant-continuation-p l)
233                   (give-up-ir1-transform))
234
235                 (let ((val (continuation-value l)))
236                   (unless (policy node
237                                   (or (= speed 3)
238                                       (and (>= speed space)
239                                            (<= (length val) 5))))
240                     (give-up-ir1-transform))
241
242                   (labels ((frob (els)
243                              (if els
244                                  `(if (funcall test e ',(car els))
245                                       ',els
246                                       ,(frob (cdr els)))
247                                  nil)))
248                     (frob val))))))
249   (def member)
250   (def memq))
251
252 ;;; FIXME: We have rewritten the original code that used DOLIST to this
253 ;;; more natural MACROLET.  However, the original code suggested that when
254 ;;; this was done, a few bytes could be saved by a call to a shared
255 ;;; function.  This remains to be done.
256 (macrolet ((def (fun eq-fun)
257              `(deftransform ,fun ((item list &key test) (t list &rest t) *)
258                 "convert to EQ test"
259                 ;; FIXME: The scope of this transformation could be
260                 ;; widened somewhat, letting it work whenever the test is
261                 ;; 'EQL and we know from the type of ITEM that it #'EQ
262                 ;; works like #'EQL on it. (E.g. types FIXNUM, CHARACTER,
263                 ;; and SYMBOL.)
264                 ;;   If TEST is EQ, apply transform, else
265                 ;;   if test is not EQL, then give up on transform, else
266                 ;;   if ITEM is not a NUMBER or is a FIXNUM, apply
267                 ;;   transform, else give up on transform.
268                 (cond (test
269                        (unless (continuation-fun-is test '(eq))
270                          (give-up-ir1-transform)))
271                       ((types-equal-or-intersect (continuation-type item)
272                                                  (specifier-type 'number))
273                        (give-up-ir1-transform "Item might be a number.")))
274                 `(,',eq-fun item list))))
275   (def delete delq)
276   (def assoc assq)
277   (def member memq))
278
279 (deftransform delete-if ((pred list) (t list))
280   "open code"
281   '(do ((x list (cdr x))
282         (splice '()))
283        ((endp x) list)
284      (cond ((funcall pred (car x))
285             (if (null splice)
286                 (setq list (cdr x))
287                 (rplacd splice (cdr x))))
288            (T (setq splice x)))))
289
290 (deftransform fill ((seq item &key (start 0) (end (length seq)))
291                     (vector t &key (:start t) (:end index))
292                     *
293                     :policy (> speed space))
294   "open code"
295   (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
296     (values 
297      `(with-array-data ((data seq)
298                         (start start)
299                         (end end))
300        (declare (type (simple-array ,element-type 1) data))
301        (declare (type fixnum start end))
302        (do ((i start (1+ i)))
303            ((= i end) seq)
304          (declare (type index i))
305          ;; WITH-ARRAY-DATA did our range checks once and for all, so
306          ;; it'd be wasteful to check again on every AREF...
307          (declare (optimize (safety 0))) 
308          (setf (aref data i) item)))
309      ;; ... though we still need to check that the new element can fit
310      ;; into the vector in safe code. -- CSR, 2002-07-05
311      `((declare (type ,element-type item))))))
312 \f
313 ;;;; utilities
314
315 ;;; Return true if CONT's only use is a non-NOTINLINE reference to a
316 ;;; global function with one of the specified NAMES.
317 (defun continuation-fun-is (cont names)
318   (declare (type continuation cont) (list names))
319   (let ((use (continuation-use cont)))
320     (and (ref-p use)
321          (let ((leaf (ref-leaf use)))
322            (and (global-var-p leaf)
323                 (eq (global-var-kind leaf) :global-function)
324                 (not (null (member (leaf-source-name leaf) names
325                                    :test #'equal))))))))
326
327 ;;; If CONT is a constant continuation, the return the constant value.
328 ;;; If it is null, then return default, otherwise quietly give up the
329 ;;; IR1 transform.
330 ;;;
331 ;;; ### Probably should take an ARG and flame using the NAME.
332 (defun constant-value-or-lose (cont &optional default)
333   (declare (type (or continuation null) cont))
334   (cond ((not cont) default)
335         ((constant-continuation-p cont)
336          (continuation-value cont))
337         (t
338          (give-up-ir1-transform))))
339
340 ;;; FIXME: Why is this code commented out? (Why *was* it commented
341 ;;; out? We inherited this situation from cmucl-2.4.8, with no
342 ;;; explanation.) Should we just delete this code?
343 #|
344 ;;; This is a frob whose job it is to make it easier to pass around
345 ;;; the arguments to IR1 transforms. It bundles together the name of
346 ;;; the argument (which should be referenced in any expansion), and
347 ;;; the continuation for that argument (or NIL if unsupplied.)
348 (defstruct (arg (:constructor %make-arg (name cont))
349                 (:copier nil))
350   (name nil :type symbol)
351   (cont nil :type (or continuation null)))
352 (defmacro make-arg (name)
353   `(%make-arg ',name ,name))
354
355 ;;; If Arg is null or its CONT is null, then return Default, otherwise
356 ;;; return Arg's NAME.
357 (defun default-arg (arg default)
358   (declare (type (or arg null) arg))
359   (if (and arg (arg-cont arg))
360       (arg-name arg)
361       default))
362
363 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
364 ;;; CONT must be a constant continuation whose value we return. If not, we
365 ;;; give up.
366 (defun arg-constant-value (arg default)
367   (declare (type (or arg null) arg))
368   (if (and arg (arg-cont arg))
369       (let ((cont (arg-cont arg)))
370         (unless (constant-continuation-p cont)
371           (give-up-ir1-transform "Argument is not constant: ~S."
372                                  (arg-name arg)))
373         (continuation-value from-end))
374       default))
375
376 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
377 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
378 (defun arg-eql (arg default x)
379   (declare (type (or arg null) x))
380   (if (and arg (arg-cont arg))
381       (let ((cont (arg-cont arg)))
382         (and (constant-continuation-p cont)
383              (eql (continuation-value cont) x)))
384       (eql default x)))
385
386 (defstruct (iterator (:copier nil))
387   ;; The kind of iterator.
388   (kind nil (member :normal :result))
389   ;; A list of LET* bindings to create the initial state.
390   (binds nil :type list)
391   ;; A list of declarations for Binds.
392   (decls nil :type list)
393   ;; A form that returns the current value. This may be set with SETF to set
394   ;; the current value.
395   (current (error "Must specify CURRENT."))
396   ;; In a :NORMAL iterator, a form that tests whether there is a current value.
397   (done nil)
398   ;; In a :RESULT iterator, a form that truncates the result at the current
399   ;; position and returns it.
400   (result nil)
401   ;; A form that returns the initial total number of values. The result is
402   ;; undefined after NEXT has been evaluated.
403   (length (error "Must specify LENGTH."))
404   ;; A form that advances the state to the next value. It is an error to call
405   ;; this when the iterator is Done.
406   (next (error "Must specify NEXT.")))
407
408 ;;; Type of an index var that can go negative (in the from-end case.)
409 (deftype neg-index ()
410   `(integer -1 ,most-positive-fixnum))
411
412 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
413 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
414 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
415 ;;; the index of the current element in the sequence.
416 ;;;
417 ;;; If we can't tell whether the sequence is a list or a vector, or whether
418 ;;; the iteration is forward or backward, then GIVE-UP.
419 (defun make-sequence-iterator (sequence type &key start end from-end index)
420   (declare (symbol sequence) (type ctype type)
421            (type (or arg null) start end from-end)
422            (type (or symbol null) index))
423   (let ((from-end (arg-constant-value from-end nil)))
424     (cond ((csubtypep type (specifier-type 'vector))
425            (let* ((n-stop (gensym))
426                   (n-idx (or index (gensym)))
427                   (start (default-arg 0 start))
428                   (end (default-arg `(length ,sequence) end)))
429              (make-iterator
430               :kind :normal
431               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
432                        (,n-stop ,(if from-end `(1- ,start) ,end)))
433               :decls `((type neg-index ,n-idx ,n-stop))
434               :current `(aref ,sequence ,n-idx)
435               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
436               :next `(setq ,n-idx
437                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
438               :length (if from-end
439                           `(- ,n-idx ,n-stop)
440                           `(- ,n-stop ,n-idx)))))
441           ((csubtypep type (specifier-type 'list))
442            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
443                   (n-current (gensym))
444                   (start-p (not (arg-eql start 0 0)))
445                   (end-p (not (arg-eql end nil nil)))
446                   (start (default-arg start 0))
447                   (end (default-arg end nil)))
448              (make-iterator
449               :binds `((,n-current
450                         ,(if from-end
451                              (if (or start-p end-p)
452                                  `(nreverse (subseq ,sequence ,start
453                                                     ,@(when end `(,end))))
454                                  `(reverse ,sequence))
455                              (if start-p
456                                  `(nthcdr ,start ,sequence)
457                                  sequence)))
458                        ,@(when n-stop
459                            `((,n-stop (nthcdr (the index
460                                                    (- ,end ,start))
461                                               ,n-current))))
462                        ,@(when index
463                            `((,index ,(if from-end `(1- ,end) start)))))
464               :kind :normal
465               :decls `((list ,n-current ,n-end)
466                        ,@(when index `((type neg-index ,index))))
467               :current `(car ,n-current)
468               :done `(eq ,n-current ,n-stop)
469               :length `(- ,(or end `(length ,sequence)) ,start)
470               :next `(progn
471                        (setq ,n-current (cdr ,n-current))
472                        ,@(when index
473                            `((setq ,n-idx
474                                    ,(if from-end
475                                         `(1- ,index)
476                                         `(1+ ,index)))))))))
477           (t
478            (give-up-ir1-transform
479             "can't tell whether sequence is a list or a vector")))))
480
481 ;;; Make an iterator used for constructing result sequences. Name is a
482 ;;; variable to be bound to the result sequence. Type is the type of result
483 ;;; sequence to make. Length is an expression to be evaluated to get the
484 ;;; maximum length of the result (not evaluated in list case.)
485 (defun make-result-sequence-iterator (name type length)
486   (declare (symbol name) (type ctype type))
487
488 ;;; Define each NAME as a local macro that will call the value of the
489 ;;; function arg with the given arguments. If the argument isn't known to be a
490 ;;; function, give them an efficiency note and reference a coerced version.
491 (defmacro coerce-funs (specs &body body)
492   #!+sb-doc
493   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
494   (collect ((binds)
495             (defs))
496     (dolist (spec specs)
497       `(let ((body (progn ,@body))
498              (n-fun (arg-name ,(second spec)))
499              (fun-cont (arg-cont ,(second spec))))
500          (cond ((not fun-cont)
501                 `(macrolet ((,',(first spec) (&rest args)
502                              `(,',',(third spec) ,@args)))
503                    ,body))
504                ((not (csubtypep (continuation-type fun-cont)
505                                 (specifier-type 'function)))
506                 (when (policy *compiler-error-context*
507                               (> speed inhibit-warnings))
508                   (compiler-note
509                    "~S may not be a function, so must coerce at run-time."
510                    n-fun))
511                 (once-only ((n-fun `(if (functionp ,n-fun)
512                                         ,n-fun
513                                         (symbol-function ,n-fun))))
514                   `(macrolet ((,',(first spec) (&rest args)
515                                `(funcall ,',n-fun ,@args)))
516                      ,body)))
517                (t
518                 `(macrolet ((,',(first spec) (&rest args)
519                               `(funcall ,',n-fun ,@args)))
520                    ,body)))))))
521
522 ;;; Wrap code around the result of the body to define Name as a local macro
523 ;;; that returns true when its arguments satisfy the test according to the Args
524 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
525 ;;; transform.
526 (defmacro with-sequence-test ((name test test-not) &body body)
527   `(let ((not-p (arg-cont ,test-not)))
528      (when (and (arg-cont ,test) not-p)
529        (abort-ir1-transform "Both ~S and ~S were supplied."
530                             (arg-name ,test)
531                             (arg-name ,test-not)))
532      (coerce-funs ((,name (if not-p ,test-not ,test) eql))
533        ,@body)))
534 |#
535 \f
536 ;;;; hairy sequence transforms
537
538 ;;; FIXME: no hairy sequence transforms in SBCL?
539 \f
540 ;;;; string operations
541
542 ;;; We transform the case-sensitive string predicates into a non-keyword
543 ;;; version. This is an IR1 transform so that we don't have to worry about
544 ;;; changing the order of evaluation.
545 (macrolet ((def (fun pred*)
546              `(deftransform ,fun ((string1 string2 &key (start1 0) end1
547                                                          (start2 0) end2)
548                                    * *)
549                 `(,',pred* string1 string2 start1 end1 start2 end2))))
550   (def string< string<*)
551   (def string> string>*)
552   (def string<= string<=*)
553   (def string>= string>=*)
554   (def string= string=*)
555   (def string/= string/=*))
556
557 ;;; Return a form that tests the free variables STRING1 and STRING2
558 ;;; for the ordering relationship specified by LESSP and EQUALP. The
559 ;;; start and end are also gotten from the environment. Both strings
560 ;;; must be SIMPLE-STRINGs.
561 (macrolet ((def (name lessp equalp)
562              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
563                                     (simple-string simple-string t t t t) *)
564                 `(let* ((end1 (if (not end1) (length string1) end1))
565                         (end2 (if (not end2) (length string2) end2))
566                         (index (sb!impl::%sp-string-compare
567                                 string1 start1 end1 string2 start2 end2)))
568                   (if index
569                       (cond ((= index ,(if ',lessp 'end1 'end2)) index)
570                             ((= index ,(if ',lessp 'end2 'end1)) nil)
571                             ((,(if ',lessp 'char< 'char>)
572                                (schar string1 index)
573                                (schar string2
574                                       (truly-the index
575                                                  (+ index
576                                                     (truly-the fixnum
577                                                                (- start2
578                                                                   start1))))))
579                              index)
580                             (t nil))
581                       ,(if ',equalp 'end1 nil))))))
582   (def string<* t nil)
583   (def string<=* t t)
584   (def string>* nil nil)
585   (def string>=* nil t))
586
587 (macrolet ((def (name result-fun)
588              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
589                                    (simple-string simple-string t t t t) *)
590                 `(,',result-fun
591                   (sb!impl::%sp-string-compare
592                    string1 start1 (or end1 (length string1))
593                    string2 start2 (or end2 (length string2)))))))
594   (def string=* not)
595   (def string/=* identity))
596
597 \f
598 ;;;; string-only transforms for sequence functions
599 ;;;;
600 ;;;; Note: CMU CL had more of these, including transforms for
601 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
602 ;;;; transforms for functions which cons, since our GC overhead is
603 ;;;; sufficiently large that it doesn't seem worth it to try to
604 ;;;; economize on function call overhead or on the overhead of runtime
605 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
606 ;;;; a full call to CONCATENATE would have to look up the sequence
607 ;;;; type, which can be really slow.
608 ;;;;
609 ;;;; FIXME: It would be nicer for these transforms to work for any
610 ;;;; calls when all arguments are vectors with the same element type,
611 ;;;; rather than restricting them to STRINGs only.
612
613 ;;; Moved here from generic/vm-tran.lisp to satisfy clisp
614 ;;;
615 ;;; FIXME: It would be good to implement SB!XC:DEFCONSTANT, and use
616 ;;; use that here, so that the compiler is born knowing this value.
617 ;;; FIXME: Add a comment telling whether this holds for all vectors
618 ;;; or only for vectors based on simple arrays (non-adjustable, etc.).
619 (def!constant vector-data-bit-offset
620   (* sb!vm:vector-data-offset sb!vm:n-word-bits))
621
622 ;;; FIXME: Shouldn't we be testing for legality of
623 ;;;   * START1, START2, END1, and END2 indices?
624 ;;;   * size of copied string relative to destination string?
625 ;;; (Either there should be tests conditional on SAFETY>=SPEED, or
626 ;;; the transform should be conditional on SPEED>SAFETY.)
627 ;;;
628 ;;; FIXME: Also, the transform should probably be dependent on
629 ;;; SPEED>SPACE.
630 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
631                                 end1 end2)
632                        (simple-string simple-string &rest t))
633   `(locally
634      (declare (optimize (safety 0)))
635      (bit-bash-copy string2
636                     (the index
637                          (+ (the index (* start2 sb!vm:n-byte-bits))
638                             ,vector-data-bit-offset))
639                     string1
640                     (the index
641                          (+ (the index (* start1 sb!vm:n-byte-bits))
642                             ,vector-data-bit-offset))
643                     (the index
644                          (* (min (the index (- (or end1 (length string1))
645                                                start1))
646                                  (the index (- (or end2 (length string2))
647                                                start2)))
648                             sb!vm:n-byte-bits)))
649      string1))
650
651 ;;; FIXME: It seems as though it should be possible to make a DEFUN
652 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
653 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
654 ;;; at least once DYNAMIC-EXTENT works.
655 ;;;
656 ;;; FIXME: currently KLUDGEed because of bug 188
657 (deftransform concatenate ((rtype &rest sequences)
658                            (t &rest simple-string)
659                            simple-string
660                            :policy (< safety 3))
661   (collect ((lets)
662             (forms)
663             (all-lengths)
664             (args))
665     (dolist (seq sequences)
666       (declare (ignorable seq))
667       (let ((n-seq (gensym))
668             (n-length (gensym)))
669         (args n-seq)
670         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
671         (all-lengths n-length)
672         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
673                                res start
674                                ,n-length))
675         (forms `(setq start (opaque-identity (+ start ,n-length))))))
676     `(lambda (rtype ,@(args))
677        (declare (ignore rtype))
678        ;; KLUDGE
679        (flet ((opaque-identity (x) x))
680          (declare (notinline opaque-identity))
681          (let* (,@(lets)
682                   (res (make-string (truncate (the index (+ ,@(all-lengths)))
683                                               sb!vm:n-byte-bits)))
684                   (start ,vector-data-bit-offset))
685            (declare (type index start ,@(all-lengths)))
686            ,@(forms)
687            res)))))
688 \f
689 ;;;; CONS accessor DERIVE-TYPE optimizers
690
691 (defoptimizer (car derive-type) ((cons))
692   (let ((type (continuation-type cons))
693         (null-type (specifier-type 'null)))
694     (cond ((eq type null-type)
695            null-type)
696           ((cons-type-p type)
697            (cons-type-car-type type)))))
698
699 (defoptimizer (cdr derive-type) ((cons))
700   (let ((type (continuation-type cons))
701         (null-type (specifier-type 'null)))
702     (cond ((eq type null-type)
703            null-type)
704           ((cons-type-p type)
705            (cons-type-cdr-type type)))))
706 \f
707 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
708
709 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
710 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
711 ;;; expansion, so we factor out the condition into this function.
712 (defun check-inlineability-of-find-position-if (sequence from-end)
713   (let ((ctype (continuation-type sequence)))
714     (cond ((csubtypep ctype (specifier-type 'vector))
715            ;; It's not worth trying to inline vector code unless we
716            ;; know a fair amount about it at compile time.
717            (upgraded-element-type-specifier-or-give-up sequence)
718            (unless (constant-continuation-p from-end)
719              (give-up-ir1-transform
720               "FROM-END argument value not known at compile time")))
721           ((csubtypep ctype (specifier-type 'list))
722            ;; Inlining on lists is generally worthwhile.
723            ) 
724           (t
725            (give-up-ir1-transform
726             "sequence type not known at compile time")))))
727
728 ;;; %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for LIST data
729 (macrolet ((def (name condition)
730              `(deftransform ,name ((predicate sequence from-end start end key)
731                                    (function list t t t function)
732                                    *
733                                    :policy (> speed space)
734                                    :important t)
735                 "expand inline"
736                 `(let ((index 0)
737                        (find nil)
738                        (position nil))
739                    (declare (type index index))
740                    (dolist (i sequence (values find position))
741                      (let ((key-i (funcall key i)))
742                        (when (and end (>= index end))
743                          (return (values find position)))
744                        (when (>= index start)
745                          (,',condition (funcall predicate key-i)
746                           ;; This hack of dealing with non-NIL
747                           ;; FROM-END for list data by iterating
748                           ;; forward through the list and keeping
749                           ;; track of the last time we found a match
750                           ;; might be more screwy than what the user
751                           ;; expects, but it seems to be allowed by
752                           ;; the ANSI standard. (And if the user is
753                           ;; screwy enough to ask for FROM-END
754                           ;; behavior on list data, turnabout is
755                           ;; fair play.)
756                           ;;
757                           ;; It's also not enormously efficient,
758                           ;; calling PREDICATE and KEY more often
759                           ;; than necessary; but all the
760                           ;; alternatives seem to have their own
761                           ;; efficiency problems.
762                           (if from-end
763                               (setf find i
764                                     position index)
765                               (return (values i index))))))
766                      (incf index))))))
767   (def %find-position-if when)
768   (def %find-position-if-not unless))
769                       
770 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
771 ;;; without loss of efficiency. (I.e., the optimizer should be able
772 ;;; to straighten everything out.)
773 (deftransform %find-position ((item sequence from-end start end key test)
774                               (t list t t t t t)
775                               *
776                               :policy (> speed space)
777                               :important t)
778   "expand inline"
779   '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
780                         ;; I'm having difficulty believing I'm
781                         ;; reading it right, but as far as I can see,
782                         ;; the only guidance that ANSI gives for the
783                         ;; order of arguments to asymmetric tests is
784                         ;; the character-set dependent example from
785                         ;; the definition of FIND,
786                         ;;   (find #\d "here are some.." :test #'char>)
787                         ;;     => #\Space
788                         ;; (In ASCII, we have (CHAR> #\d #\SPACE)=>T.)
789                         ;; (Neither the POSITION definition page nor
790                         ;; section 17.2 ("Rules about Test Functions")
791                         ;; seem to consider the possibility of
792                         ;; asymmetry.)
793                         ;;
794                         ;; So, judging from the example, we want to
795                         ;; do (FUNCALL TEST-FUN ITEM I), because
796                         ;; (FUNCALL #'CHAR> #\d #\SPACE)=>T.
797                         ;;
798                         ;; -- WHN (whose attention was drawn to it by
799                         ;;         Alexey Dejneka's bug report/fix)
800                         (lambda (i)
801                           (funcall test-fun item i)))
802                       sequence
803                       from-end
804                       start
805                       end
806                       (%coerce-callable-to-fun key)))
807
808 ;;; The inline expansions for the VECTOR case are saved as macros so
809 ;;; that we can share them between the DEFTRANSFORMs and the default
810 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
811 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
812 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
813                                                             from-end
814                                                             start
815                                                             end-arg
816                                                             element
817                                                             done-p-expr)
818   (let ((offset (gensym "OFFSET"))
819         (block (gensym "BLOCK"))
820         (index (gensym "INDEX"))
821         (n-sequence (gensym "N-SEQUENCE-"))
822         (sequence (gensym "SEQUENCE"))
823         (n-end (gensym "N-END-"))
824         (end (gensym "END-")))
825     `(let ((,n-sequence ,sequence-arg)
826            (,n-end ,end-arg))
827        (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
828                          (,start ,start)
829                          (,end (or ,n-end (length ,n-sequence))))
830          (block ,block
831            (macrolet ((maybe-return ()
832                         '(let ((,element (aref ,sequence ,index)))
833                            (when ,done-p-expr
834                              (return-from ,block
835                                (values ,element
836                                        (- ,index ,offset)))))))
837              (if ,from-end
838                  (loop for ,index
839                        ;; (If we aren't fastidious about declaring that 
840                        ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
841                        ;; can send us off into never-never land, since
842                        ;; INDEX is initialized to -1.)
843                        of-type index-or-minus-1
844                        from (1- ,end) downto ,start do
845                        (maybe-return))
846                  (loop for ,index of-type index from ,start below ,end do
847                        (maybe-return))))
848            (values nil nil))))))
849
850 (def!macro %find-position-vector-macro (item sequence
851                                              from-end start end key test)
852   (let ((element (gensym "ELEMENT")))
853     (%find-position-or-find-position-if-vector-expansion
854      sequence
855      from-end
856      start
857      end
858      element
859      ;; (See the LIST transform for a discussion of the correct
860      ;; argument order, i.e. whether the searched-for ,ITEM goes before
861      ;; or after the checked sequence element.)
862      `(funcall ,test ,item (funcall ,key ,element)))))
863
864 (def!macro %find-position-if-vector-macro (predicate sequence
865                                                      from-end start end key)
866   (let ((element (gensym "ELEMENT")))
867     (%find-position-or-find-position-if-vector-expansion
868      sequence
869      from-end
870      start
871      end
872      element
873      `(funcall ,predicate (funcall ,key ,element)))))
874
875 (def!macro %find-position-if-not-vector-macro (predicate sequence
876                                                          from-end start end key)
877   (let ((element (gensym "ELEMENT")))
878     (%find-position-or-find-position-if-vector-expansion
879      sequence
880      from-end
881      start
882      end
883      element
884      `(not (funcall ,predicate (funcall ,key ,element))))))
885
886 ;;; %FIND-POSITION, %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for
887 ;;; VECTOR data
888 (deftransform %find-position-if ((predicate sequence from-end start end key)
889                                  (function vector t t t function)
890                                  *
891                                  :policy (> speed space)
892                                  :important t)
893   "expand inline"
894   (check-inlineability-of-find-position-if sequence from-end)
895   '(%find-position-if-vector-macro predicate sequence
896                                    from-end start end key))
897
898 (deftransform %find-position-if-not ((predicate sequence from-end start end key)
899                                      (function vector t t t function)
900                                      *
901                                      :policy (> speed space)
902                                      :important t)
903   "expand inline"
904   (check-inlineability-of-find-position-if sequence from-end)
905   '(%find-position-if-not-vector-macro predicate sequence
906                                        from-end start end key))
907
908 (deftransform %find-position ((item sequence from-end start end key test)
909                               (t vector t t t function function)
910                               *
911                               :policy (> speed space)
912                               :important t)
913   "expand inline"
914   (check-inlineability-of-find-position-if sequence from-end)
915   '(%find-position-vector-macro item sequence
916                                 from-end start end key test))