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