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